/
encryption.go
52 lines (41 loc) · 976 Bytes
/
encryption.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
42
43
44
45
46
47
48
49
50
51
52
package main
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
)
func generateRSAKeyPair(hash crypto.Hash, modulusLength int) (*RSAKeyPair, error) {
key, err := rsa.GenerateKey(rand.Reader, modulusLength)
if err != nil {
return nil, err
}
publicBuffer, err := x509.MarshalPKIXPublicKey(key.Public())
if err != nil {
return nil, err
}
public := pem.EncodeToMemory(
&pem.Block{
Type: "PUBLIC KEY",
Bytes: publicBuffer,
},
)
decrypt := func(ciphertext []byte) ([]byte, error) {
return key.Decrypt(nil, ciphertext, &rsa.OAEPOptions{Hash: hash})
}
keyPair := &RSAKeyPair{
PrivateKey: key,
PublicKey: key.Public().(*rsa.PublicKey),
PublicKeyBytes: public,
Decrypt: decrypt,
}
return keyPair, nil
}
type RSAKeyPair struct {
PrivateKey *rsa.PrivateKey
PublicKey *rsa.PublicKey
PublicKeyBytes []byte
Decrypt Decrypt
}
type Decrypt func(ciphertext []byte) ([]byte, error)