forked from little-gg-bound/go-adyen-ces
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrsa.go
53 lines (48 loc) · 1.17 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
package adyen
import (
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/hex"
"math/big"
)
type adrsa struct {
publicKey *rsa.PublicKey
privateKey *rsa.PrivateKey
}
func (r *adrsa) SetPublicKey(pubHex string, e int) error {
k := &rsa.PublicKey{}
dec, err := hex.DecodeString(pubHex)
if err != nil {
return err
}
k.N = new(big.Int).SetBytes(dec)
k.E = e
r.publicKey = k
return nil
}
func (r *adrsa) Encrypt(str string, encoding string) (string, error) {
bytes := []byte(str)
res, err := rsa.EncryptPKCS1v15(rand.Reader, r.publicKey, bytes)
if err != nil {
return "", err
}
if encoding == "base64" {
return base64.StdEncoding.EncodeToString(res), nil
}
return hex.EncodeToString(res), nil
}
func (r *adrsa) Encrypt2(bytes []byte, encoding string) (string, error) {
res, err := rsa.EncryptPKCS1v15(rand.Reader, r.publicKey, bytes)
if err != nil {
return "", err
}
if encoding == "base64" {
return base64.StdEncoding.EncodeToString(res), nil
}
return hex.EncodeToString(res), nil
}
func NewRsa() *adrsa {
rs := &adrsa{}
return rs
}