Skip to content

Commit 9f0b424

Browse files
committed
add crypto
1 parent 1d398d0 commit 9f0b424

19 files changed

+2277
-0
lines changed

pkg/gocrypto/README.md

Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
## gocrypto
2+
3+
Commonly used `one-way encryption`, `symmetric encryption and decryption`, `asymmetric encryption and decryption` libraries, including hash, aes, des, rsa.
4+
5+
<br>
6+
7+
## Example of use
8+
9+
### Hash one-way encryption
10+
11+
```go
12+
import "github.com/zhufuyi/sponge/pkg/gocrypto"
13+
14+
var hashRawData = []byte("hash_abcdefghijklmnopqrstuvwxyz0123456789")
15+
16+
// independent hash functions
17+
gocrypto.Md5(hashRawData)
18+
gocrypto.Sha1(hashRawData)
19+
gocrypto.Sha256(hashRawData)
20+
gocrypto.Sha512(hashRawData)
21+
22+
// hash collection, specify the execution of the corresponding hash function
23+
// according to the hash type
24+
gocrypto.Hash(crypto.MD5, hashRawData)
25+
gocrypto.Hash(crypto.SHA3_224, hashRawData)
26+
gocrypto.Hash(crypto.SHA256, hashRawData)
27+
gocrypto.Hash(crypto.SHA3_224, hashRawData)
28+
gocrypto.Hash(crypto.BLAKE2s_256, hashRawData)
29+
```
30+
31+
<br>
32+
33+
###Password hash and checksum with salt
34+
35+
The password registered by the user is stored in the database through hash, and the password registered is compared with the hash value to judge whether the password is correct all the time, so as to ensure that only the user knows the plaintext of the password.
36+
37+
```go
38+
import "github.com/zhufuyi/sponge/pkg/gocrypto"
39+
40+
pwd := "123"
41+
42+
// hash
43+
hashStr, err := gocrypto.HashAndSaltPassword(pwd)
44+
if err != nil {
45+
return err
46+
}
47+
48+
// check password
49+
ok := gocrypto.VerifyPassword(pwd, hashStr)
50+
if !ok {
51+
return errors.New("passwords mismatch")
52+
}
53+
```
54+
55+
<br>
56+
57+
### AES encrypt and decrypt
58+
59+
AES (`Advanced Encryption Standard`) Advanced Encryption Standard, designed to replace `DES`, has four packet encryption modes: ECB CBC CFB CTR.
60+
61+
There are four functions `AesEncrypt`, `AesDecrypt`, `AesEncryptHex`, `AesDecryptHex`.
62+
63+
```go
64+
import "github.com/zhufuyi/sponge/pkg/gocrypto"
65+
66+
var (
67+
aesRawData = []byte("aes_abcdefghijklmnopqrstuvwxyz0123456789")
68+
aesKey = []byte("aesKey0123456789aesKey0123456789")
69+
)
70+
71+
// AesEncrypt and AesDecrypt have default values for their arguments:
72+
// default mode is ECB, can be modified to CBC CTR CFB
73+
// default key length is 16, which can be modified to 24 32
74+
75+
// default mode is ECB, default key length is 16
76+
cypherData, _ := gocrypto.AesEncrypt(aesRawData) // encrypt
77+
raw, _ := gocrypto.AesDecrypt(cypherData) // decrypt, return to original
78+
79+
// mode is ECB, key length is 32
80+
cypherData, _ := gocrypto.AesEncrypt(aesRawData, gocrypto.WithAesKey(aesKey)) // encrypt
81+
raw, _ := gocrypto.AesDecrypt(cypherData, gocrypto.WithAesKey(aesKey)) // decrypt
82+
83+
// mode is CTR, default key length is 16
84+
cypherData, _ := gocrypto.AesEncrypt(aesRawData, gocrypto.WithAesModeCTR()) // encrypt
85+
raw, _ := gocrypto.AesDecrypt(cypherData, gocrypto.WithAesModeCTR()) // decrypt
86+
87+
// mode is CBC, key length is 32
88+
cypherData, _ := gocrypto.AesEncrypt(aesRawData, gocrypto.WithAesModeECB(), gocrypto.WithAesKey(aesKey)) // encrypt
89+
raw, _ := gocrypto.AesDecrypt(cypherData, gocrypto.WithAesModeECB(), gocrypto.WithAesKey(aesKey)) // decrypt
90+
91+
92+
// AesEncryptHex and AesDecryptHex functions, the ciphertext of these two functions is transcoded by hex,
93+
// and used in exactly the same way as AesEncrypt and AesDecrypt.
94+
```
95+
<br>
96+
97+
### DES encrypt and decrypt
98+
99+
DES (`Data Encryption Standard`) data encryption standard, is currently one of the most popular encryption algorithms, there are four packet encryption mode: ECB CBC CFB CTR.
100+
101+
There are four functions `DesEncrypt`, `DesDecrypt`, `DesEncryptHex`, `DesDecryptHex`.
102+
103+
```go
104+
import "github.com/zhufuyi/sponge/pkg/gocrypto"
105+
106+
var (
107+
desRawData = []byte("des_abcdefghijklmnopqrstuvwxyz0123456789")
108+
desKey = []byte("desKey0123456789desKey0123456789")
109+
)
110+
// PKCS#1
111+
var publicKey = []byte(`
112+
-----BEGIN PUBLIC KEY-----
113+
xxxxxx
114+
-----END PUBLIC KEY-----
115+
`)
116+
117+
var privateKey = []byte(`
118+
-----BEGIN RSA PRIVATE KEY-----
119+
xxxxxx
120+
-----END RSA PRIVATE KEY-----
121+
`)
122+
123+
// DesEncrypt and DesDecrypt have default values for their arguments:
124+
// default mode is ECB, can be modified to CBC CTR CFB
125+
// default key length is 16, which can be modified to 24 32
126+
127+
// default mode is ECB, default key length is 16
128+
cypherData, _ := gocrypto.DesEncrypt(desRawData) // encrypt
129+
raw, _ := gocrypto.DesDecrypt(cypherData) // decrypt
130+
131+
// mode is ECB, key length is 32
132+
cypherData, _ := gocrypto.DesEncrypt(desRawData, gocrypto.WithDesKey(desKey)) // encrypt
133+
raw, _ := gocrypto.DesDecrypt(cypherData, gocrypto.WithDesKey(desKey)) // decrypt
134+
135+
// mode is CTR, default key length is 16
136+
cypherData, _ := gocrypto.DesEncrypt(desRawData, gocrypto.WithDesModeCTR()) // encrypt
137+
raw, _ := gocrypto.DesDecrypt(cypherData, gocrypto.WithDesModeCTR()) // decrypt
138+
139+
// mode is CBC, key length is 32
140+
cypherData, _ := gocrypto.DesEncrypt(desRawData, gocrypto.WithDesModeECB(), gocrypto.WithDesKey(desKey)) // encrypt
141+
raw, _ := gocrypto.DesDecrypt(cypherData, gocrypto.WithDesModeECB(), gocrypto.WithDesKey(desKey)) // decrypt
142+
143+
144+
// DesEncryptHex and DesDecryptHex functions, the ciphertext of these two functions is transcoded by hex,
145+
// and used in exactly the same way as DesEncrypt and DesDecrypt.
146+
```
147+
148+
<br>
149+
150+
### RSA asymmetric encryption and decryption
151+
152+
#### RSA encryption and decryption
153+
154+
The public key is used for encryption, and the private key is used for decryption. For example, if someone uses the public key to encrypt information and send it to you, you have the private key to decrypt the information content.
155+
156+
There are four functions: `RsaEncrypt`, `RsaDecrypt`, `RsaEncryptHex`, `RsaDecryptHex`.
157+
158+
```go
159+
import "github.com/zhufuyi/sponge/pkg/gocrypto"
160+
161+
var rsaRawData = []byte("rsa_abcdefghijklmnopqrstuvwxyz0123456789")
162+
// PKCS#1
163+
var publicKey = []byte(`
164+
-----BEGIN PUBLIC KEY-----
165+
xxxxxx
166+
-----END PUBLIC KEY-----
167+
`)
168+
169+
var privateKey = []byte(`
170+
-----BEGIN RSA PRIVATE KEY-----
171+
xxxxxx
172+
-----END RSA PRIVATE KEY-----
173+
`)
174+
175+
// RsaEncrypt and RsaDecrypt have default values for their arguments:
176+
// default key pair format: PKCS#1, can be modified to PKCS#8
177+
178+
// default key pair format is PKCS#1
179+
cypherData, _ := gocrypto.RsaEncrypt(publicKey, rsaRawData) // encrypt
180+
raw, _ := gocrypto.RsaDecrypt(privateKey, cypherData) // decrypt
181+
182+
// key pair format is PKCS#8
183+
cypherData, _ := gocrypto.RsaEncrypt(publicKey, rsaRawData, gocrypto.WithRsaFormatPKCS8()) // encrypt
184+
raw, _ := gocrypto.RsaDecrypt(privateKey, cypherData, gocrypto.WithRsaFormatPKCS8()) // decrypt
185+
186+
187+
// RsaEncryptHex and RsaDecryptHex functions, the ciphertext of these two functions is transcoded by hex,
188+
// and used in exactly the same way as RsaEncrypt and RsaDecrypt.
189+
```
190+
191+
<br>
192+
193+
#### RSA signature and signature verification
194+
195+
The private key is used to sign, and the public key is used to verify the signature. For example, you sign your identity with the private key, and others verify whether your identity can be trusted through the public key.
196+
197+
There are four functions: `RsaSign`, `RsaVerify`, `RsaSignBase64`, `RsaVerifyBase64`.
198+
199+
```go
200+
import "github.com/zhufuyi/sponge/pkg/gocrypto"
201+
202+
var rsaRawData = []byte("rsa_abcdefghijklmnopqrstuvwxyz0123456789")
203+
204+
// RsaEncrypt and RsaDecrypt have default values for their arguments:
205+
// default key pair format is PKCS#1, can be modified to PKCS#8
206+
// default hash is sha1, can be modified to sha256, sha512
207+
208+
// default key pair format is PKCS#1, default hash is sha1
209+
signData, _ := gocrypto.RsaSign(privateKey, rsaRawData) // signature
210+
err := gocrypto.RsaVerify(publicKey, rsaRawData, signData) // signature verification
211+
212+
// default key pair format is PKCS#1, hash is sha256
213+
signData, _ := gocrypto.RsaSign(privateKey, rsaRawData, gocrypto.WithRsaHashTypeSha256()) // signature
214+
err := gocrypto.RsaVerify(publicKey, rsaRawData, signData, gocrypto.WithRsaHashTypeSha256()) // signature verification
215+
216+
// key pair format is PKCS#8, default hash is sha1
217+
signData, _ := gocrypto.RsaSign(privateKey, rsaRawData, gocrypto.WithRsaFormatPKCS8()) // signature
218+
err := gocrypto.RsaVerify(publicKey, rsaRawData, signData, gocrypto.WithRsaFormatPKCS8()) // signature verification
219+
220+
// key pair format is PKCS#8, hash is sha512
221+
signData, _ := gocrypto.RsaSign(privateKey, rsaRawData, gocrypto.WithRsaFormatPKCS8(), gocrypto.WithRsaHashTypeSha512()) // signature
222+
err := gocrypto.RsaVerify(publicKey, rsaRawData, signData, gocrypto.WithRsaFormatPKCS8(), gocrypto.WithRsaHashTypeSha512()) // signature verification
223+
224+
225+
// The ciphertext of RsaSignBase64 and RsaVerifyBase64 is base64 transcoded
226+
// and used exactly the same as RsaSign and RsaVerify.
227+
```

pkg/gocrypto/aes.go

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// Symmetric encryption AES, the advanced encryption standard with
2+
// the highest level of security, has gradually replaced DES as the new
3+
// generation of symmetric encryption standard.
4+
5+
package gocrypto
6+
7+
import (
8+
"encoding/hex"
9+
"errors"
10+
11+
"testCode/pkg/gocrypto/wcipher"
12+
)
13+
14+
// AesEncrypt aes encryption, returns ciphertext is not transcoded
15+
func AesEncrypt(rawData []byte, opts ...AesOption) ([]byte, error) {
16+
o := defaultAesOptions()
17+
o.apply(opts...)
18+
19+
return aesEncrypt(o.mode, rawData, o.aesKey)
20+
}
21+
22+
// AesDecrypt aes decryption, parameter input un-transcode cipher text
23+
func AesDecrypt(cipherData []byte, opts ...AesOption) ([]byte, error) {
24+
o := defaultAesOptions()
25+
o.apply(opts...)
26+
27+
return aesDecrypt(o.mode, cipherData, o.aesKey)
28+
}
29+
30+
// AesEncryptHex aes encryption, the returned ciphertext is transcoded
31+
func AesEncryptHex(rawData string, opts ...AesOption) (string, error) {
32+
o := defaultAesOptions()
33+
o.apply(opts...)
34+
35+
cipherData, err := aesEncrypt(o.mode, []byte(rawData), o.aesKey)
36+
if err != nil {
37+
return "", err
38+
}
39+
40+
return hex.EncodeToString(cipherData), nil
41+
}
42+
43+
// AesDecryptHex aes decryption, parameter input has been transcoded ciphertext string
44+
func AesDecryptHex(cipherStr string, opts ...AesOption) (string, error) {
45+
o := defaultAesOptions()
46+
o.apply(opts...)
47+
48+
cipherData, err := hex.DecodeString(cipherStr)
49+
if err != nil {
50+
return "", err
51+
}
52+
53+
rawData, err := aesDecrypt(o.mode, cipherData, o.aesKey)
54+
if err != nil {
55+
return "", err
56+
}
57+
58+
return string(rawData), nil
59+
}
60+
61+
func getCipherMode(mode string) (wcipher.CipherMode, error) {
62+
var cipherMode wcipher.CipherMode
63+
switch mode {
64+
case modeECB:
65+
cipherMode = wcipher.NewECBMode()
66+
case modeCBC:
67+
cipherMode = wcipher.NewCBCMode()
68+
case modeCFB:
69+
cipherMode = wcipher.NewCFBMode()
70+
case modeCTR:
71+
cipherMode = wcipher.NewCTRMode()
72+
default:
73+
return nil, errors.New("unknown mode = " + mode)
74+
}
75+
76+
return cipherMode, nil
77+
}
78+
79+
func aesEncrypt(mode string, rawData []byte, key []byte) ([]byte, error) {
80+
cipherMode, err := getCipherMode(mode)
81+
if err != nil {
82+
return nil, err
83+
}
84+
85+
cip, err := wcipher.NewAESWith(key, cipherMode)
86+
if err != nil {
87+
return nil, err
88+
}
89+
90+
return cip.Encrypt(rawData), nil
91+
}
92+
93+
func aesDecrypt(mode string, cipherData []byte, key []byte) ([]byte, error) {
94+
cipherMode, err := getCipherMode(mode)
95+
if err != nil {
96+
return nil, err
97+
}
98+
99+
cip, err := wcipher.NewAESWith(key, cipherMode)
100+
if err != nil {
101+
return nil, err
102+
}
103+
104+
return cip.Decrypt(cipherData), nil
105+
}

0 commit comments

Comments
 (0)