-
Notifications
You must be signed in to change notification settings - Fork 0
/
rsa.go
111 lines (97 loc) · 2.32 KB
/
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package secrets
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha512"
"crypto/x509"
"encoding/pem"
"fmt"
)
const (
DefaultEncryptionBits = 2048
blockTYpeRSAPublicKey = "RSA PUBLIC KEY"
blockTypeRSAPrivateKey = "RSA PRIVATE KEY"
)
type RSA struct {
Bits int
}
func NewRSAHandler(bits int) *RSA {
if bits == 0 {
bits = DefaultEncryptionBits
}
return &RSA{Bits: bits}
}
func (r *RSA) EncryptWithPublicKey(msg []byte, key []byte) ([]byte, error) {
publicKey, err := BytesToPublicKey(key)
if err != nil {
return nil, err
}
hash := sha512.New()
ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, publicKey, msg, nil)
if err != nil {
return nil, err
}
return ciphertext, nil
}
func (r *RSA) DecryptWithPrivateKey(msg []byte, key []byte) ([]byte, error) {
privateKey, err := BytesToPrivateKey(key)
if err != nil {
return nil, err
}
hash := sha512.New()
plaintext, err := rsa.DecryptOAEP(hash, rand.Reader, privateKey, msg, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
func (r *RSA) GenerateKeyPair() ([]byte, []byte, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, r.Bits)
if err != nil {
return nil, nil, err
}
publicKeyBytes, err := PublicKeyToBytes(&privateKey.PublicKey)
if err != nil {
return nil, nil, err
}
return PrivateKeyToBytes(privateKey), publicKeyBytes, nil
}
func PrivateKeyToBytes(priv *rsa.PrivateKey) []byte {
return pem.EncodeToMemory(
&pem.Block{
Type: blockTypeRSAPrivateKey,
Bytes: x509.MarshalPKCS1PrivateKey(priv),
},
)
}
func PublicKeyToBytes(pub *rsa.PublicKey) ([]byte, error) {
pubASN1, err := x509.MarshalPKIXPublicKey(pub)
if err != nil {
return nil, err
}
pubBytes := pem.EncodeToMemory(&pem.Block{
Type: blockTYpeRSAPublicKey,
Bytes: pubASN1,
})
return pubBytes, nil
}
func BytesToPrivateKey(privateKey []byte) (*rsa.PrivateKey, error) {
block, _ := pem.Decode(privateKey)
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return key, nil
}
func BytesToPublicKey(publicKey []byte) (*rsa.PublicKey, error) {
block, _ := pem.Decode(publicKey)
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
key, ok := publicKeyInterface.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("cannot decode bytes to public key")
}
return key, nil
}