/
rsa.go
128 lines (109 loc) · 2.6 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package encoding
import (
"crypto"
"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 = make([]byte, 0, 0)
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 = make([]byte, 0, 0)
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
}
func SignPKCS1v15(src, key []byte, hash crypto.Hash) ([]byte, error) {
var h = hash.New()
h.Write(src)
var hashed = h.Sum(nil)
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
}
return rsa.SignPKCS1v15(rand.Reader, pri, hash, hashed)
}
func VerifyPKCS1v15(src, sig, key []byte, hash crypto.Hash) error {
var h = hash.New()
h.Write(src)
var hashed = h.Sum(nil)
var err error
var block *pem.Block
block, _ = pem.Decode(key)
if block == nil {
return errors.New("public key error")
}
var pubInterface interface{}
pubInterface, err = x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return err
}
var pub = pubInterface.(*rsa.PublicKey)
return rsa.VerifyPKCS1v15(pub, hash, hashed, sig)
}