This repository has been archived by the owner on Feb 17, 2023. It is now read-only.
/
crypt.go
105 lines (97 loc) · 2.46 KB
/
crypt.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
package rsax
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/hex"
"github.com/go-leo/cryptox/base64x"
)
func EncryptToHex(plainText []byte, hexPubKey string) (string, error) {
pub, err := hex.DecodeString(hexPubKey)
if err != nil {
return "", err
}
cipherBytes, err := rsaEncrypt(plainText, pub)
if err != nil {
return "", err
}
return hex.EncodeToString(cipherBytes), nil
}
func DecryptByHex(hexCipherText, hexPriKey string) ([]byte, error) {
privateBytes, err := hex.DecodeString(hexPriKey)
if err != nil {
return nil, err
}
cipherTextBytes, err := hex.DecodeString(hexCipherText)
if err != nil {
return nil, err
}
return rsaDecrypt(cipherTextBytes, privateBytes)
}
func EncryptToBase64(plainText []byte, base64PubKey string) (string, error) {
pub, err := base64x.StdDecode(base64PubKey)
if err != nil {
return "", err
}
cipherBytes, err := rsaEncrypt(plainText, pub)
if err != nil {
return "", err
}
return base64x.StdEncode(cipherBytes), nil
}
func DecryptByBase64(base64CipherText, base64PriKey string) ([]byte, error) {
privateBytes, err := base64x.StdDecode(base64PriKey)
if err != nil {
return nil, err
}
cipherTextBytes, err := base64x.StdDecode(base64CipherText)
if err != nil {
return nil, err
}
return rsaDecrypt(cipherTextBytes, privateBytes)
}
func rsaEncrypt(plainText, publicKey []byte) ([]byte, error) {
pub, err := x509.ParsePKCS1PublicKey(publicKey)
if err != nil {
return nil, err
}
pubSize, plainTextSize := pub.Size(), len(plainText)
offSet, once := 0, pubSize-11
buffer := bytes.Buffer{}
for offSet < plainTextSize {
endIndex := offSet + once
if endIndex > plainTextSize {
endIndex = plainTextSize
}
bytesOnce, err := rsa.EncryptPKCS1v15(rand.Reader, pub, plainText[offSet:endIndex])
if err != nil {
return nil, err
}
buffer.Write(bytesOnce)
offSet = endIndex
}
return buffer.Bytes(), nil
}
func rsaDecrypt(cipherText, privateKey []byte) ([]byte, error) {
pri, err := x509.ParsePKCS1PrivateKey(privateKey)
if err != nil {
return []byte{}, err
}
priSize, cipherTextSize := pri.Size(), len(cipherText)
var offSet = 0
var buffer = bytes.Buffer{}
for offSet < cipherTextSize {
endIndex := offSet + priSize
if endIndex > cipherTextSize {
endIndex = cipherTextSize
}
bytesOnce, err := rsa.DecryptPKCS1v15(rand.Reader, pri, cipherText[offSet:endIndex])
if err != nil {
return nil, err
}
buffer.Write(bytesOnce)
offSet = endIndex
}
return buffer.Bytes(), nil
}