Skip to content

Instantly share code, notes, and snippets.

@mjarkk
Created January 28, 2019 09:32
Show Gist options
  • Save mjarkk/e24eab63d0878f7364700f2ae7def82c to your computer and use it in GitHub Desktop.
Save mjarkk/e24eab63d0878f7364700f2ae7def82c to your computer and use it in GitHub Desktop.
Encrpyt and decrpyt with a public and private key using RSA
func main() {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Fatal(err)
}
// Generate keyFile to memory
keyFile := pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: x509.MarshalPKCS1PublicKey(&key.PublicKey)})
// Create a public key from the public keyFile
pubBlock, _ := pem.Decode(keyFile)
pub, err := x509.ParsePKCS1PublicKey(pubBlock.Bytes)
if err != nil {
log.Fatal(err)
}
// toSend is what will be encrypted and decrpyted again
// The part before the | is the hashed public key
toSend := fmt.Sprintf("%x|%v", sha256.Sum256(keyFile), "Password for: github.com")
// This part encrypts the data
encryptedData, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pub, []byte(toSend), []byte("PUBLIC KEY HOST"))
if err != nil {
log.Fatal(err)
}
// Here we decrypt the message again
outMsg, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, key, encryptedData, []byte("PUBLIC KEY HOST"))
if err != nil {
log.Fatal(err)
}
// print the output
fmt.Println(string(outMsg))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment