package edgeencrypt import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "fmt" ) const ( RSA2048 = 2048 ) // GenerateRandomRSAKeyPair generates a random RSA key pair: private and public keys func GenerateRandomRSAKeyPair() (string, string, error) { privateKey, err := rsa.GenerateKey(rand.Reader, RSA2048) if err != nil { return "", "", fmt.Errorf("failed to generate private key: %w", err) } publicKey := &privateKey.PublicKey pubKeyString, err := ConvertRSAPublicKeyToPEM(publicKey) if err != nil { return "", "", fmt.Errorf("failed to convert public key to string: %w", err) } pkString := ConvertRSAPrivateKeyToPEM(privateKey) return pkString, pubKeyString, nil } // ConvertRSAPublicKeyToPEM converts rsa.PublicKey to pem format func ConvertRSAPublicKeyToPEM(key *rsa.PublicKey) (string, error) { block, err := x509.MarshalPKIXPublicKey(key) if err != nil { return "", fmt.Errorf("failed to marshal public key: %w", err) } pubPEM := pem.EncodeToMemory(&pem.Block{ Type: "PUBLIC KEY", Bytes: block, }) return string(pubPEM), nil } // ConvertRSAPrivateKeyToPEM converts rsa.PrivateKey to pem format func ConvertRSAPrivateKeyToPEM(key *rsa.PrivateKey) string { block := x509.MarshalPKCS1PrivateKey(key) privateKey := pem.EncodeToMemory(&pem.Block{ Type: "RSA PRIVATE KEY", Bytes: block, }) return string(privateKey) }