我使用以下Node JS代码加密了一些JSON Text: -
var algorithm = 'aes-256-ctr';
var crypto = require('crypto');
var password = "6A80FD8D38D579D1090F6CDB62C729311781E4BA31CD7D804BD7BF5AEC3BFC2D"
var typedRequest = {"abc":"cde"}
var cipher = crypto.createCipher(algorithm, password);
var hashRequest = cipher.update(JSON.stringify(typedRequest),
'utf8', 'hex');
hashRequest += cipher.final('hex');
现在,我想在Golang中解密这个encryptedText。但是我无法找到任何方法来实现这一点,因为在Golang的几乎所有AES 256 CTR的解密逻辑示例中,我发现它在解密时总是需要IV但我在Node JS中没有使用相同的。我已经在Golang中写了一些东西,但它没有正确解密并且现在给出错误: -
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"fmt"
)
func main() {
encKey := "6A80FD8D38D579D1090F6CDB62C729311781E4BA31CD7D804BD7BF5AEC3BFC2D"
cipherText := "746c17cd10f8f86646f843ac2a"
encKeyDecoded, err := hex.DecodeString(encKey)
if err != nil {
panic(err)
}
cipherTextDecoded, err := hex.DecodeString(cipherText)
if err != nil {
panic(err)
}
iv := cipherTextDecoded[:aes.BlockSize]
block, err := aes.NewCipher([]byte(encKeyDecoded))
if err != nil {
panic(err)
}
cipherTextBytes := []byte(cipherTextDecoded)
plaintext := make([]byte, len(cipherTextBytes) - aes.BlockSize)
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(plaintext, cipherTextBytes[aes.BlockSize:])
fmt.Println(string(plaintext))
}
我们非常感谢您获取正确的Golang代码的任何帮助。感谢
=====================================
现在,我在接受答案的建议后更新了以下内容: -
这是我的节点js代码: -
var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
password = '6A80FD8D38D579D1090F6CDB62CA34CA',
// do not use a global iv for production,
// generate a new one for each encryption
iv = '79b67e539e7fcadf'
var typedRequest = {"abc":"cde"}
var cipher = crypto.createCipheriv(algorithm, password, iv);
var hashRequest = cipher.update(JSON.stringify(typedRequest),
'utf8', 'hex');
hashRequest += iv.toString('hex') + cipher.final('hex');
这是我的Go代码: -
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"fmt"
)
func main() {
encKey := "6A80FD8D38D579D1090F6CDB62CA34CA"
cipherText := "af7d1eb42107549a7e3adbce1a79b67e539e7fcadf" // Got from above
encKeyDecoded, err := hex.DecodeString(encKey)
if err != nil {
panic(err)
}
cipherTextDecoded, err := hex.DecodeString(cipherText)
if err != nil {
panic(err)
}
block, err := aes.NewCipher([]byte(encKeyDecoded))
if err != nil {
panic(err)
}
iv := cipherTextDecoded[:aes.BlockSize]
cipherTextBytes := []byte(cipherTextDecoded)
plaintext := make([]byte, len(cipherTextBytes) - aes.BlockSize)
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(plaintext, cipherTextBytes[aes.BlockSize:])
fmt.Println(string(plaintext))
}
现在,我正在以解密的形式获得完全不同的东西。
答案 0 :(得分:3)
您的NodeJS代码不正确。 CTR模式需要IV,调用crypto.createCipher
是CTR模式的未定义行为。
根据Crypto的NodeJS文档,您应该使用crypto.createCipheriv
。您的Golang代码尝试从明文开头检索此IV,因此您需要将其放在NodeJS代码中。
对于每个加密操作,IV应该是唯一的,建议使用CSPRNG。