Last active
March 27, 2024 13:59
-
-
Save aymanalzarrad/645260fb5ad78b8b0f7d639e24c80c90 to your computer and use it in GitHub Desktop.
Golang RSA key pair string and PEM generator
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 utils | |
import ( | |
"crypto/rand" | |
"crypto/rsa" | |
"crypto/x509" | |
"encoding/base64" | |
"encoding/pem" | |
) | |
type KeyPair struct { | |
public []byte | |
private []byte | |
} | |
func (keyPair *KeyPair) GetPublic() string { | |
return base64.StdEncoding.EncodeToString(keyPair.public) | |
} | |
func (keyPair *KeyPair) GetPrivate() string { | |
return base64.StdEncoding.EncodeToString(keyPair.private) | |
} | |
func (keyPair *KeyPair) GetPublicPEM() string { | |
return string(pem.EncodeToMemory( | |
&pem.Block{ | |
Type: "RSA PUBLIC KEY", | |
Bytes: keyPair.public, | |
}, | |
)) | |
} | |
func (keyPair *KeyPair) GetPrivatePEM() string { | |
return string(pem.EncodeToMemory( | |
&pem.Block{ | |
Type: "RSA PRIVATE KEY", | |
Bytes: keyPair.private, | |
}, | |
)) | |
} | |
func GenerateKeyPair() (*KeyPair, error) { | |
key, err := rsa.GenerateKey(rand.Reader, 4096) | |
if err != nil { | |
return nil, err | |
} | |
return &KeyPair{ | |
private: x509.MarshalPKCS1PrivateKey(key), | |
public: x509.MarshalPKCS1PublicKey(key.Public().(*rsa.PublicKey)), | |
}, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment