Skip to content

Instantly share code, notes, and snippets.

@Grrrben
Last active November 1, 2018 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Grrrben/468ae117aead53847754fd2bf2261f2a to your computer and use it in GitHub Desktop.
Save Grrrben/468ae117aead53847754fd2bf2261f2a to your computer and use it in GitHub Desktop.
An RSA identity consists of a public and a private key.
// Decrypt a message using your private key.
// A received message should be encrypted using the receivers public key.
func (r *RsaIdentity) Decrypt(msg []byte) ([]byte, error) {
label := []byte("")
hash := sha256.New()
return rsa.DecryptOAEP(hash, rand.Reader, r.private, msg, label)
}
// Encrypt's the message using EncryptOAEP which encrypts the given message with RSA-OAEP.
// https://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding
// Returns the encrypted message and an error.
func (r *RsaIdentity) Encrypt(msg []byte, key *rsa.PublicKey) ([]byte, error) {
label := []byte("")
hash := sha256.New()
return rsa.EncryptOAEP(hash, rand.Reader, key, msg, label)
}
type RsaIdentity struct {
Public *rsa.PublicKey
private *rsa.PrivateKey
}
// Sign returns a signature made by combining the message and the signers private key
// With the r.Verify function, the signature can be checked.
func (r *RsaIdentity) Sign(msg []byte) ([]byte, error) {
return rsa.SignPKCS1v15(rand.Reader, r.private, crypto.SHA256, r.getHashSum(msg))
}
// Verify checks if a message is signed by a given Public Key
func (r *RsaIdentity) Verify(msg []byte, sig []byte, pk *rsa.PublicKey) error {
h := sha256.New()
h.Write(msg)
d := h.Sum(nil)
return rsa.VerifyPKCS1v15(pk, crypto.SHA256, d, sig)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment