Skip to content

Instantly share code, notes, and snippets.

@aymanalzarrad
Last active March 27, 2024 13:59
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 aymanalzarrad/645260fb5ad78b8b0f7d639e24c80c90 to your computer and use it in GitHub Desktop.
Save aymanalzarrad/645260fb5ad78b8b0f7d639e24c80c90 to your computer and use it in GitHub Desktop.
Golang RSA key pair string and PEM generator
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