-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.go
80 lines (69 loc) · 1.52 KB
/
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
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
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
)
func encrypt(rsaPublicKey string, content string) (string, error) {
if rsaPublicKey == "" {
return content, nil
}
pubKey, err := base64.StdEncoding.DecodeString(rsaPublicKey)
if err != nil {
return "", err
}
block, _ := pem.Decode([]byte(pubKey))
if block == nil {
return "", errors.New("failed to parse PEM block containing the public key")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return "", err
}
encryptedBytes, err := rsa.EncryptOAEP(
sha256.New(),
rand.Reader,
pub.(*rsa.PublicKey),
[]byte(content),
nil)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(encryptedBytes), nil
}
func decrypt(rsaPrivateKey string, encryptBytes string) (string, error) {
if rsaPrivateKey == "" {
return encryptBytes, nil
}
prvKey, err := base64.StdEncoding.DecodeString(rsaPrivateKey)
if err != nil {
return "", err
}
block, _ := pem.Decode([]byte(prvKey))
if block == nil {
return "", errors.New("failed to parse PEM block containing the private key")
}
prv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return "", err
}
ciphertext, err := base64.StdEncoding.DecodeString(encryptBytes)
if err != nil {
return "", err
}
decryptedBytes, err := rsa.DecryptOAEP(
sha256.New(),
rand.Reader,
prv,
[]byte(ciphertext),
nil,
)
if err != nil {
return "", err
}
return string(decryptedBytes), nil
}