Last active
November 22, 2022 00:21
-
-
Save stvoidit/042849c457e8c878b35da949c4fa6587 to your computer and use it in GitHub Desktop.
RSA keygen + encrypt + decrypt
This file contains hidden or 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 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