package crypto import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" ) // CreatePrivateKey generates an RSA keypair func CreatePrivateKey() *rsa.PrivateKey { pk, _ := rsa.GenerateKey(rand.Reader, 4096) return pk } // Serialize an rsa.PrivateKey func Serialize(privateKey *rsa.PrivateKey) string { // Use x509 to encode the private key privateKeyBytes, _ := x509.MarshalPKCS8PrivateKey(privateKey) // Use pem to encode the private key privateKeyPem := pem.EncodeToMemory( &pem.Block{ Type: "PRIVATE KEY", Bytes: privateKeyBytes, }, ) return string(privateKeyPem) } // Deserialize a string back to a rsa.PrivateKey func Deserialize(serializedPK string) *rsa.PrivateKey { // Decode the PEM encoded private key block, _ := pem.Decode([]byte(serializedPK)) // Decode the x509 encoded private key privateKey, _ := x509.ParsePKCS8PrivateKey(block.Bytes) return privateKey.(*rsa.PrivateKey) }