Skip to content

Instantly share code, notes, and snippets.

@smallyunet
Last active May 5, 2022 04:30
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 smallyunet/af284ee9b73e7a11ea23eaa0c7a04183 to your computer and use it in GitHub Desktop.
Save smallyunet/af284ee9b73e7a11ea23eaa0c7a04183 to your computer and use it in GitHub Desktop.
Golang RSA encrypt and decrypt example
package crypto
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
)
func RSAGenerateKey() (*rsa.PrivateKey, *rsa.PublicKey) {
// here 2048 is the number of bits for RSA
// 1024 - 4096 supported
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
publicKey := &privateKey.PublicKey
return privateKey, publicKey
}
func RSAEncrypt(data []byte, pubKey rsa.PublicKey) []byte {
label := []byte("OAEP Encrypted")
rng := rand.Reader
cipherData, err := rsa.EncryptOAEP(sha256.New(), rng, &pubKey, data, label)
if err != nil {
panic(err)
}
return cipherData
}
func RSADecrypt(cipherData []byte, privKey rsa.PrivateKey) []byte {
label := []byte("OAEP Encrypted")
rng := rand.Reader
data, err := rsa.DecryptOAEP(sha256.New(), rng, &privKey, cipherData, label)
if err != nil {
panic(err)
}
return data
}
package crypto
import (
"testing"
)
func TestRSA(t *testing.T) {
data := []byte("hello world")
privKey, publicKey := RSAGenerateKey()
encrypt := RSAEncrypt(data, *publicKey)
decrypt := RSADecrypt(encrypt, *privKey)
t.Log(string(decrypt))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment