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

问题描述

我有这个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,hash,16)
            Array.copy (temp,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,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#),如何获得结果“ kR / 1uaFarptS5 + n951MVsQ ==“,使用算法“ AES-128-对文本” abc”和盐“ 123”进行加密欧洲央行”?

解决方法

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

在VB代码中,使用了32个字节的密钥。由于在.NET中,密钥大小决定了AES变体,因此将应用AES-256。此外,传递的密钥不直接使用,而是实际的密钥是从摘要MD5的传递值中得出的。

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

...
'Dim hash(31) As Byte
'Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
'Array.Copy(temp,hash,16)
'Array.Copy(temp,15,16)
'AES.Key = hash
Dim keyPadded(15) As Byte
Dim key = System.Text.ASCIIEncoding.ASCII.GetBytes(pass)
Array.Copy(key,keyPadded,Math.Min(16,key.Length))
AES.Key = keyPadded
...

一些说明:

  • 在PHP代码中,密钥称为$salt。这具有误导性,因为salt的含义不同。
  • ECB模式通常是不安全的。
  • AES-128使用16个字节的密钥。 123不是一个强键(但也许这只是一个虚拟值)。
  • 如果123不代表密钥,而是代表密钥的密码,那么通常不应该使用MD5,而应使用PBKDF2Argon2等经过特殊设计的算法,另请参见here