Skip to content

Instantly share code, notes, and snippets.

@stvoidit
Last active November 22, 2022 00:21
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 stvoidit/042849c457e8c878b35da949c4fa6587 to your computer and use it in GitHub Desktop.
Save stvoidit/042849c457e8c878b35da949c4fa6587 to your computer and use it in GitHub Desktop.
RSA keygen + encrypt + decrypt
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
)
func main() {
priv, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
panic(err)
}
pem.Encode(os.Stdout, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(priv),
})
fmt.Println()
pem.Encode(os.Stdout, &pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: x509.MarshalPKCS1PublicKey(&priv.PublicKey),
})
fmt.Println()
messageEnc, err := rsa.EncryptPKCS1v15(rand.Reader, &priv.PublicKey, []byte("Hello! World!"))
if err != nil {
panic(err)
}
pem.Encode(os.Stdout, &pem.Block{
Type: "MESSAGE",
Bytes: messageEnc,
})
fmt.Println()
messageDec, err := rsa.DecryptPKCS1v15(rand.Reader, priv, messageEnc)
if err != nil {
panic(err)
}
fmt.Println(string(messageDec))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment