Skip to content

Instantly share code, notes, and snippets.

@ustropo
Created November 7, 2020 16:40
Show Gist options
  • Save ustropo/3887e7db364bcff720730e7aac9af7a3 to your computer and use it in GitHub Desktop.
Save ustropo/3887e7db364bcff720730e7aac9af7a3 to your computer and use it in GitHub Desktop.
Example using RSA to encrypt, decrypt, sign and verify.
package main
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"fmt"
)
// Generate a key pair (private and public) based on number of bits
func generateKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey) {
// This method requires a random number of bits.
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
panic(err)
}
// The public key is part of the PrivateKey struct
return privateKey, &privateKey.PublicKey
}
func main() {
// Generate a 2048-bits key
privateKey, publicKey := generateKeyPair(2048)
message := []byte("super secret message")
// This method ensures that a different cipher is generated each time
cipherText, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, message, nil)
if err != nil {
panic(err)
}
fmt.Printf("Encrypted: %v\n", cipherText)
decMessage, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey, cipherText, nil)
if err != nil {
panic(err)
}
fmt.Printf("Original: %s\n", string(decMessage))
// We actually sign the hashed message
msgHash := sha256.New()
_, err = msgHash.Write(message)
if err != nil {
panic(err)
}
msgHashSum := msgHash.Sum(nil)
signature, err := rsa.SignPSS(rand.Reader, privateKey, crypto.SHA256, msgHashSum, nil)
if err != nil {
panic(err)
}
fmt.Printf("Signature: %v\n", signature)
err = rsa.VerifyPSS(publicKey, crypto.SHA256, msgHashSum, signature, nil)
if err != nil {
fmt.Println("Verification failed: ", err)
} else {
fmt.Println("Message verified.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment