-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrsa.go
37 lines (31 loc) · 842 Bytes
/
rsa.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//** Utility function to generate RSA PrivateKey and PublicKey in PEM format.
//** This can be used for testing purpose.
package utils
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
)
// constants for error code
const (
ErrKeyGen = "key generation error"
ErrPubKey = "public Key marshalling error"
)
// GenRSAKeyPair generates and returns RSA private key, public pem with error
func GenRSAKeyPair() (*rsa.PrivateKey, []byte, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, []byte{}, errors.New(ErrKeyGen)
}
bytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
return nil, []byte{}, errors.New(ErrPubKey)
}
pem := pem.EncodeToMemory(&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: bytes,
})
return privateKey, pem, nil
}