...
1 package edgeencrypt
2
3 import (
4 "crypto/rand"
5 "crypto/rsa"
6 "crypto/x509"
7 "encoding/pem"
8 "fmt"
9 )
10
11 const (
12 RSA2048 = 2048
13 )
14
15
16 func GenerateRandomRSAKeyPair() (string, string, error) {
17 privateKey, err := rsa.GenerateKey(rand.Reader, RSA2048)
18 if err != nil {
19 return "", "", fmt.Errorf("failed to generate private key: %w", err)
20 }
21 publicKey := &privateKey.PublicKey
22
23 pubKeyString, err := ConvertRSAPublicKeyToPEM(publicKey)
24 if err != nil {
25 return "", "", fmt.Errorf("failed to convert public key to string: %w", err)
26 }
27
28 pkString := ConvertRSAPrivateKeyToPEM(privateKey)
29
30 return pkString, pubKeyString, nil
31 }
32
33
34 func ConvertRSAPublicKeyToPEM(key *rsa.PublicKey) (string, error) {
35 block, err := x509.MarshalPKIXPublicKey(key)
36 if err != nil {
37 return "", fmt.Errorf("failed to marshal public key: %w", err)
38 }
39 pubPEM := pem.EncodeToMemory(&pem.Block{
40 Type: "PUBLIC KEY",
41 Bytes: block,
42 })
43 return string(pubPEM), nil
44 }
45
46
47 func ConvertRSAPrivateKeyToPEM(key *rsa.PrivateKey) string {
48 block := x509.MarshalPKCS1PrivateKey(key)
49 privateKey := pem.EncodeToMemory(&pem.Block{
50 Type: "RSA PRIVATE KEY",
51 Bytes: block,
52 })
53 return string(privateKey)
54 }
55
View as plain text