为了账号安全,请及时绑定邮箱和手机立即绑定

加密:使用 vb.net 得到的结果与 php 不同

加密:使用 vb.net 得到的结果与 php 不同

PHP
繁花如伊 2023-11-03 21:23:55
我有这个 php 代码$plain_text = "abc";$salt = "123";echo $encrypted_text = openssl_encrypt($plain_text, "AES-128-ECB", $salt);// result: kR/1uaFarptS5+n951MVsQ==我在vb.net上尝试了几种方法(类和函数),但是用这种语言加密的结果每次都与上面使用php的不一样。例如这个:Public 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 = Security.Cryptography.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        End Try    End Function sEnc = AES_Encrypt("abc", "123") Console.WriteLine(sEnc)'result: Z3hCHcS0b2zJ7fEod3jcrw==请问,使用 vb.net(无 C#),如何使用算法“AES-128-ECB”获得文本“abc”和盐“123”的加密结果“kR/1uaFarptS5+n951MVsQ==”?
查看完整描述

1 回答

?
慕雪6442864

TA贡献1812条经验 获得超5个赞

由于AES-128-ECBPHP代码中的规范,ECB模式下使用AES-128,即密钥长度为16字节。但由于仅应用了 3 字节大键 ( 123),PHP 将值填充到必要的 16 字节大小0x00。请注意,如果密钥太长,则会被截断。


在 VB 代码中使用 32 字节密钥。由于在 .NET 中,密钥大小决定了 AES 变体,因此应用 AES-256。而且,传递的密钥并不是直接使用的,而是根据传递的值与摘要MD5推导出实际的密钥。


为了让VB代码返回PHP代码的结果,PHP代码的逻辑必须在VB代码中实现:


...

'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

Dim keyPadded(15) As Byte

Dim key = System.Text.ASCIIEncoding.ASCII.GetBytes(pass)

Array.Copy(key, 0, keyPadded, 0, Math.Min(16, key.Length))

AES.Key = keyPadded

...

几点说明:

  • 在 PHP 代码中,该键称为$salt. 这是误导,因为盐有不同的含义。

  • ECB模式通常是不安全的。

  • AES -128 使用 16 字节密钥。123不是一个强键(但也许这只是一个虚拟值)。

  • 如果123不代表密钥,而是派生密钥的密码,那么通常不应使用 MD5,而应使用专门设计的算法,例如PBKDF2或Argon2。


查看完整回答
反对 回复 2023-11-03
  • 1 回答
  • 0 关注
  • 73 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信