【问题标题】:Convert PHP code that create encryption key to c# MD5将创建加密密钥的 PHP 代码转换为 c# MD5
【发布时间】:2020-11-06 02:33:21
【问题描述】:

我正在尝试将以下创建加密密钥的代码转换为 c# 结果我需要 $key ** 和 ** $iv

$passphrase = 'asdfghjkl';
$salt =  '123456789' // for test purposes I fixed the value but it should be openssl_random_pseudo_bytes(8);
        $salted = '';
        $dx = '';
        while (strlen($salted) < 48) {
            $dx = md5($dx . $passphrase . $salt, true);
            $salted .= $dx;
        }
        $key = substr($salted, 0, 32);
        $iv = substr($salted, 32, 16);

到目前为止我能做什么

string passphrase = "asdfghjkl";
string salt = "123456789";
string key, iv;

byte[] salted = new byte[0];
byte[] dx = new byte[0];

while (salted.Length < 48)
      {
        string a = passphrase + salt;
        byte[] b = Encoding.UTF8.GetBytes(a);

        byte[] rv = new byte[dx.Length + b.Length];
        System.Buffer.BlockCopy(dx, 0, rv, 0, dx.Length);
        System.Buffer.BlockCopy(b, 0, rv, dx.Length, b.Length);

        //dx = MD5CryptoServiceProvider.Create().ComputeHash(rv);
        using (MD5 md5 = MD5.Create())
              {
                dx = md5.ComputeHash(rv);
              }

        byte[] rx = new byte[salted.Length + dx.Length];
        System.Buffer.BlockCopy(salted, 0, rx, 0, salted.Length);
        System.Buffer.BlockCopy(dx, 0, rx, salted.Length, dx.Length);

        salted = rx;
      }
string utfString1 = Encoding.UTF8.GetString(salted);
key = utfString1.Substring( 0, 32);
iv = utfString1.Substring(32, 16);

但我没有得到相同的结果

谢谢

【问题讨论】:

  • 这是一种非常低效的方法来创建盐和密钥。你必须这样做吗?
  • 不幸的是我必须这样做,我必须使用这个散列与另一个系统交谈
  • 这通常是一个编码问题。检查你的 php 正在使用什么。另外:md5 不安全!它已经被破解了几十年。另外:在 php 中,您应该自己散列密码,而是使用 passwod_hash()password_verify()
  • @JohnConde:因为这是从密码派生的密钥,所以应该很慢。这实际上太快了。像PBKDF2 这样的标准是更好的选择。
  • @FranzGleichmann & JohnConde 你们说的都是对的,但是我没有能力改变 php 代码,我只需要把它转换成 c#,这样我就可以连接到系统了

标签: c# php encryption byte md5


【解决方案1】:

调用的 PHP md5 函数将以原始二进制格式(16 字节)返回 md5 哈希。阅读有关PHP md5 的更多信息。

这是 .NET 中的等价物。

...
var passphrase = Encoding.UTF8.GetBytes("asdfghjkl");
var salt = Encoding.UTF8.GetBytes("123456789");
var salted = new List<byte>();
var dx = new byte[0];
using (var md5 = MD5.Create())
{
    do
    {
        var bytesToHash = dx.Concat(passphrase).Concat(salt);
        dx = md5.ComputeHash(bytesToHash.ToArray());
        salted.AddRange(dx);
    } while (salted.Count < 48);
}

var key = salted.Take(32).ToArray();
var iv = salted.Skip(32).Take(16).ToArray();
...

如果要检查输出,请使用 PHP base64_encode 函数和 .NET Convert.ToBase64String,然后比较 base64 字符串。

【讨论】:

    猜你喜欢
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多