36 lines
710 B
Go
36 lines
710 B
Go
package crypto
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/rsa"
|
|
"crypto/x509"
|
|
"encoding/base64"
|
|
"encoding/pem"
|
|
)
|
|
|
|
func GenerateKeyPair(bytes int) (string, string, error) {
|
|
privateKey, err := rsa.GenerateKey(rand.Reader, bytes)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
|
|
err = privateKey.Validate()
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
|
|
privBlock := pem.Block{
|
|
Type: "RSA PRIVATE KEY",
|
|
Headers: nil,
|
|
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
|
|
}
|
|
|
|
privateKeyPEM := pem.EncodeToMemory(&privBlock)
|
|
|
|
pubBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
|
|
return string(privateKeyPEM), string(base64.StdEncoding.EncodeToString(pubBytes)), nil
|
|
}
|