crypto-js 库 AES 加密解密的 go 实现
1
2
3
4
5
6
7
8
9
10
11
12
13
var CryptoJS = require("crypto-js");
var data = [{id: 1}, {id: 2}]
// Encrypt
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'secret key 123').toString();
// Decrypt
var bytes = CryptoJS.AES.decrypt(ciphertext, 'secret key 123');
var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
console.log(decryptedData); // [{id: 1}, {id: 2}]
golang 实现
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
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
func encrypt(key []byte, text []byte) []byte {
c, _ := aes.NewCipher(key)
gcm, _ := cipher.NewGCM(c)
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
result := gcm.Seal(nonce, nonce, text, nil)
return result
}
func decrypt(key []byte, ciphertext []byte) string {
c, _ := aes.NewCipher(key)
gcm, _ := cipher.NewGCM(c)
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
panic("ciphertext size is less than nonceSize")
}
var nonce []byte
nonce, ciphertext = ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, _ := gcm.Open(nil, nonce, ciphertext, nil)
return string(plaintext)
}
func main() {
text := []byte("待加密的字符串")
key := []byte("T+U2YMDrIz2G+fsasSZ+mQ==")
secret := encrypt(key, text)
plainString := decrypt(key, secret)
fmt.Println(plainString, string(text) == plainString)
}
本文网址: https://golangnote.com/topic/280.html 转摘请注明来源