-
Notifications
You must be signed in to change notification settings - Fork 0
/
encryption.go
109 lines (90 loc) · 1.91 KB
/
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
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
package decnet
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha512"
"crypto/x509"
"encoding/pem"
)
type Key struct {
publicKey *rsa.PublicKey
privateKey *rsa.PrivateKey
}
func GenerateKey() (*Key, error) {
k := new(Key)
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return k, err
}
k.publicKey = &privateKey.PublicKey
k.privateKey = privateKey
return k, nil
}
func (k Key) PublicKeyToPemString() string {
return string(
pem.EncodeToMemory(
&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: x509.MarshalPKCS1PublicKey(k.publicKey),
},
),
)
}
func (k Key) PrivateKeyToPemString() string {
return string(
pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(k.privateKey),
},
),
)
}
func (k *Key) Decrypt(encryptedMessage []byte) ([]byte, error) {
return rsa.DecryptOAEP(
sha512.New(),
rand.Reader,
k.privateKey,
pemStringToCipher(encryptedMessage),
nil,
)
}
func Encrypt(publicKey *rsa.PublicKey, plainText []byte) ([]byte, error) {
if publicKey == nil {
return plainText, nil
}
cipher, err := rsa.EncryptOAEP(sha512.New(), rand.Reader, publicKey, plainText, nil)
if err != nil {
return nil, err
}
return cipherToPemString(cipher), nil
}
func pemStringToCipher(encryptedMessage []byte) []byte {
b, _ := pem.Decode(encryptedMessage)
return b.Bytes
}
func convertBytesToPublicKey(keyBytes []byte) (*rsa.PublicKey, error) {
var err error
block, _ := pem.Decode(keyBytes)
blockBytes := block.Bytes
ok := x509.IsEncryptedPEMBlock(block)
if ok {
blockBytes, err = x509.DecryptPEMBlock(block, nil)
if err != nil {
return nil, err
}
}
publicKey, err := x509.ParsePKCS1PublicKey(blockBytes)
if err != nil {
return nil, err
}
return publicKey, nil
}
func cipherToPemString(cipher []byte) []byte {
return pem.EncodeToMemory(
&pem.Block{
Type: "MESSAGE",
Bytes: cipher,
},
)
}