Last active
May 5, 2022 04:30
-
-
Save smallyunet/af284ee9b73e7a11ea23eaa0c7a04183 to your computer and use it in GitHub Desktop.
Golang RSA encrypt and decrypt example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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