-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoding.go
85 lines (73 loc) · 1.66 KB
/
encoding.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
package alipay
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
)
func packageData(originalData []byte, packageSize int) (r [][]byte) {
var src = make([]byte, len(originalData))
copy(src, originalData)
r = make([][]byte, 0)
if len(src) <= packageSize {
return append(r, src)
}
for len(src) > 0 {
var p = src[:packageSize]
r = append(r, p)
src = src[packageSize:]
if len(src) <= packageSize {
r = append(r, src)
break
}
}
return r
}
func RSAEncrypt(plaintext, key []byte) ([]byte, error) {
var err error
var block *pem.Block
block, _ = pem.Decode(key)
if block == nil {
return nil, errors.New("public key error")
}
var pubInterface interface{}
pubInterface, err = x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
var pub = pubInterface.(*rsa.PublicKey)
var data = packageData(plaintext, pub.N.BitLen()/8-11)
var cipherData []byte
for _, d := range data {
var c, e = rsa.EncryptPKCS1v15(rand.Reader, pub, d)
if e != nil {
return nil, e
}
cipherData = append(cipherData, c...)
}
return cipherData, nil
}
func RSADecrypt(ciphertext, key []byte) ([]byte, error) {
var err error
var block *pem.Block
block, _ = pem.Decode(key)
if block == nil {
return nil, errors.New("private key error")
}
var pri *rsa.PrivateKey
pri, err = x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
var data = packageData(ciphertext, pri.PublicKey.N.BitLen()/8)
var plainData []byte
for _, d := range data {
var p, e = rsa.DecryptPKCS1v15(rand.Reader, pri, d)
if e != nil {
return nil, e
}
plainData = append(plainData, p...)
}
return plainData, nil
}