You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法用VB.Net复现AES在线编码器示例结果的问题排查

AES加密结果不一致问题排查

问题场景

使用在线工具加密文本test,参数如下:

  • 加密模式:ECB
  • 密钥长度:128位
  • 密钥:1234567890123456
    得到的Base64加密结果为:3fvaLg5IDlveswuXzhVQcw==

但使用以下VB.Net函数加密时,得到结果为6mhZOr1dQ7PWqbRGzmMgjg==,调整填充方式后仍无法匹配:

Public Shared Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
    Dim AES As New System.Security.Cryptography.RijndaelManaged
    Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
    Dim encrypted As String = ""
    Try
        Dim hash(31) As Byte
        Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
        Array.Copy(temp, 0, hash, 0, 16)
        Array.Copy(temp, 0, hash, 15, 16)
        AES.Key = hash
        AES.Mode = CipherMode.ECB

        Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
        Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
        encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
        Return encrypted
    Catch ex As Exception
        Return ex.ToString
    End Try
End Function

问题根源

  1. 密钥处理逻辑错误
    在线工具直接将密钥字符串1234567890123456的ASCII字节作为128位AES密钥(刚好16字节,符合128位要求)。但你的代码对密钥做了MD5哈希(生成16字节),再通过Array.Copy拼接成32字节的密钥,实际使用的是256位AES密钥,和在线工具的128位密钥完全不匹配,这是结果不一致的核心原因。

  2. 密钥长度不匹配
    代码中设置的AES.Key是32字节,会自动将RijndaelManaged的密钥长度设为256位,而在线工具用的是128位,加密算法的密钥长度不同,结果必然无法一致。

修正后的代码

要和在线工具结果一致,需直接使用原始密钥的字节作为128位密钥,去掉不必要的MD5哈希和拼接步骤:

Public Shared Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
    Dim AES As New System.Security.Cryptography.RijndaelManaged
    Dim encrypted As String = ""
    Try
        ' 直接将密钥字符串转为ASCII字节(16字节,对应128位密钥)
        AES.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(pass)
        AES.Mode = CipherMode.ECB
        ' 显式设置填充方式为PKCS7(和在线工具默认逻辑一致)
        AES.Padding = PaddingMode.PKCS7

        Dim encryptor As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
        Dim buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
        encrypted = Convert.ToBase64String(encryptor.TransformFinalBlock(buffer, 0, buffer.Length))
        Return encrypted
    Catch ex As Exception
        Return ex.ToString
    End Try
End Function

验证说明

修正后调用AES_Encrypt("test", "1234567890123456"),得到的结果将和在线工具一致:3fvaLg5IDlveswuXzhVQcw==。

注:你已知晓ECB模式的安全性问题,此处仅为匹配在线工具结果做修正,实际生产环境请使用更安全的模式(如CBC、GCM等)并配合IV向量。

内容的提问来源于stack exchange,提问作者ilvi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 15:00:57