-
Notifications
You must be signed in to change notification settings - Fork 0
/
rsa.go
86 lines (75 loc) · 1.7 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
package crypt
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"fmt"
)
// EncryptRSA encrypts the given message with RSA-OAEP and using SHA-256 (default) or SHA-512.
func (e *Encoder) EncryptRSA(text string) (ciphertext []byte, err error) {
pubKey, err := x509.ParsePKIXPublicKey(e.PubKeyBlock.Bytes)
if err != nil {
err = fmt.Errorf("error parsing public key: %v", err)
return
}
rsaPubKey, ok := pubKey.(*rsa.PublicKey)
if !ok {
err = fmt.Errorf("failed to cast public key to RSA public key")
return
}
var hashAlg crypto.Hash
switch e.HashAlg {
case SHA512:
hashAlg = crypto.SHA512
default:
hashAlg = crypto.SHA256
}
// encrypt the data using RSA-OAEP
ciphertext, err = rsa.EncryptOAEP(
hashAlg.New(),
rand.Reader,
rsaPubKey,
[]byte(text),
nil,
)
if err != nil {
err = fmt.Errorf("error encrypting data: %v", err)
return
}
return
}
// DecryptRSA decrypts the given message with RSA-OAEP and using SHA-256 (default) or SHA-512.
func (d *Decoder) DecryptRSA(ciphertext []byte) (text string, err error) {
priKey, err := x509.ParsePKCS8PrivateKey(d.PriKeyBlock.Bytes)
if err != nil {
err = fmt.Errorf("error parsing private key: %v", err)
return
}
rsaPriKey, ok := priKey.(*rsa.PrivateKey)
if !ok {
err = fmt.Errorf("failed to cast private key to RSA private key")
return
}
var hashAlg crypto.Hash
switch d.HashAlg {
case SHA512:
hashAlg = crypto.SHA512
default:
hashAlg = crypto.SHA256
}
// decrypt the data using RSA-OAEP
plaintext, err := rsa.DecryptOAEP(
hashAlg.New(),
rand.Reader,
rsaPriKey,
ciphertext,
nil,
)
if err != nil {
err = fmt.Errorf("error decrypting data: %v", err)
return
}
text = string(plaintext)
return
}