首页 > 解决方案 > JS - VB.Net - CBC 加密

问题描述

我想加密 js 和 vb.net 中的特定字符串。我希望两者都出现相同的加密字符串。

为此,我使用 AES CBC 加密。现在我找到了以下JS代码:

const ENC_KEY = "bf3c199c2470cb477d907b1e0917c17b"; // set random encryption key
const IV = "5183666c72eec9e4"; // set random initialisation vector

在 VB.Net 中:

 Dim KEY_128 As Byte() = {41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41}
 Dim IV_128 As Byte() = {41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41}

问题是我只有 VB.Net 的代码,其中键为字节,Js 中为字符串。现在我不知道如何获得与字节相同的密钥作为字符串。有人对此有想法吗?

如果您需要进一步的加密代码:

JS:

var encrypt = ((val) => {
let cipher = crypto.createCipheriv('aes-256-cbc', ENC_KEY, IV);
let encrypted = cipher.update(val, 'utf8', 'base64');
encrypted += cipher.final('base64');
return encrypted;
});

message.channel.send(encrypt(phrase));

VB.Net:

Private Sub btnEncrypt_Click()
    Dim sPlainText As String = Me.TextBox1.Text
    If Not String.IsNullOrEmpty(sPlainText) Then
        Dim memoryStream As MemoryStream = New MemoryStream()
        Dim cryptoStream As CryptoStream = New CryptoStream(memoryStream, Me.encryptor, CryptoStreamMode.Write)
        cryptoStream.Write(Me.enc.GetBytes(sPlainText), 0, sPlainText.Length)
        cryptoStream.FlushFinalBlock()
        Me.TextBox1.Text = Convert.ToBase64String(memoryStream.ToArray())
        memoryStream.Close()
        cryptoStream.Close()
    End If
End Sub

标签: javascriptvb.net

解决方案


调用时只需使用 aTypedArray而不是字符串crypto.createCipheriv

const arrayKey = new Int8Array(32);
arrayKey[0] = 41;
arrayKey[1] = 41;
...
arrayKey[31] = 41;

接着:

let cipher = crypto.createCipheriv('aes-256-cbc', arrayKey, IV);

对 IV 执行相同的操作。

有关 TypedArray 的更多信息


推荐阅读