forked from davecheney/pub
/
crypto.go
41 lines (38 loc) · 929 Bytes
/
crypto.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
38
39
40
41
// package crypto provides a simple interface to common cryptographic primitives.
package crypto
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
)
type Keypair struct {
PublicKey []byte
PrivateKey []byte
}
func GenerateRSAKeypair() (*Keypair, error) {
privatekey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
publickey := &privatekey.PublicKey
privateKeyBytes := x509.MarshalPKCS1PrivateKey(privatekey)
privateKeyBlock := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: privateKeyBytes,
}
privateKeyPem := pem.EncodeToMemory(privateKeyBlock)
publicKeyBytes, err := x509.MarshalPKIXPublicKey(publickey)
if err != nil {
return nil, err
}
publicKeyBlock := &pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyBytes,
}
publicKeyPem := pem.EncodeToMemory(publicKeyBlock)
return &Keypair{
PublicKey: publicKeyPem,
PrivateKey: privateKeyPem,
}, nil
}