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}]如何在与CryptoJS.AES兼容的Golang中加密/解密?
发布于 2021-04-26 17:31:33
加密策略通常是不管平台而设计的。您看到的密码AES加密是在JS中实现AES加密的。Go在密码包下提供它。Go的文档是开始查找加密代码的好地方。
为了加快速度,下面是一个例子:
加密:
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")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, _ := gcm.Open(nil, nonce, ciphertext, nil)
return string(plaintext)
}用法:
func main() {
text := []byte("TEXT TO ENCRYPT AND DECRYPT")
key := []byte("5v8y/B?E(G+KbPeShVmYq3t6w9z$C&12")
secret := encrypt(key, text)
plainString := decrypt(key, secret)
fmt.Println(plainString)
}操场这里上的工作实例
注意:请确保根据您的喜好处理错误。
https://stackoverflow.com/questions/67270166
复制相似问题