【发布时间】:2020-10-08 08:10:08
【问题描述】:
我有一个用例,必须使用 AES 256 算法对文本进行编码和发送。客户端代码在 C# 中,它将解密代码。
JS中的加密代码:
const crypto = require('crypto');
algorithm = 'aes-256-cbc',
secret = '1234567890123456',
keystring = crypto.createHash('sha256').update(String(secret)).digest('base64').substr(0, 16);
iv = crypto.createHash('sha256').update(String(secret)).digest('base64').substr(0, 16);
inputEncoding = 'utf8',
outputEncoding = 'base64';
function encrypt(text) {
let cipher = crypto.createCipheriv('aes-256-cbc', keystring, iv);
let encrypted = cipher.update(text, inputEncoding, outputEncoding)
encrypted += cipher.final(outputEncoding);
return encrypted;
}
客户端使用的更新代码:
var keybytes = Encoding.UTF8.GetBytes(passwordKey);
var iv = Encoding.UTF8.GetBytes(passwordKey);
private byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv)
{
try
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
{
throw new ArgumentNullException("plainText");
}
if (key == null || key.Length <= 0)
{
throw new ArgumentNullException("key");
}
if (iv == null || iv.Length <= 0)
{
throw new ArgumentNullException("key");
}
byte[] encrypted;
// Create a RijndaelManaged object
// with the specified key and IV.
using (var rijAlg = new RijndaelManaged())
{
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.PKCS7;
rijAlg.FeedbackSize = 128;
rijAlg.Key = key;
rijAlg.IV = iv;
// Create a decrytor to perform the stream transform.
var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
catch (Exception ex)
{
throw ex;
//LoggerCS.logError("Utility", "EncryptStringToBytes", JsonConvert.SerializeObject(null), ex.ToString(), ex.StackTrace);
}
return null;
}
在 C# 中使用的 keyString 和 IV 值相同,并且使用 Utf8 加密。在 Node JS 中寻找等效的操作。
【问题讨论】:
-
为小提琴点赞,干得好,祝你好运
-
您是否有理由忽略
algorithm并将其硬编码为aes-128-cbc? -
@John - 没有理由,我试图查看用户过去关于相同问题的其他建议,并尝试了 aes-128。
-
我只是想知道这是否是您的问题,因为您的 C# 代码使用 AES-256。
-
@Topaco - 我在这里有点困惑。 C# 使用 256 的块大小。如果必须将其更改为 128 以使其成为 aes-256 算法,那在我的情况下是不可行的。 C# 代码早已投入生产,无法修改。只有 Node JS 实现与 C# 同步。
标签: javascript c# node.js aes cryptojs