DES加密在PHP和C# [英] DES Encryption in PHP and C#

查看:198
本文介绍了DES加密在PHP和C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想才达到相同的DES encription,我在C#代码,但在PHP已经

I'm trying to achive the same DES encription that I've in an C# code but in PHP.

C#代码如下所示:

public static string EncriptarCadena(string strEncriptar)
{
    DESCryptoServiceProvider provider;

    MemoryStream stream;
    CryptoStream stream2;
    string str2;
    string str = "29393651";
    byte[] buffer2 = new byte[] { 0x45, 50, 0xa5, 0x18, 0x67, 0x58, 0xac, 0xba };
    byte[] bytes = new byte[0];
    try
    {
        bytes = Encoding.UTF8.GetBytes(str.Substring(0, 8));
        provider = new DESCryptoServiceProvider();
        byte[] buffer = Encoding.UTF8.GetBytes(strEncriptar);
        stream = new MemoryStream();
        stream2 = new CryptoStream(stream, provider.CreateEncryptor(bytes, buffer2), CryptoStreamMode.Write);
        stream2.Write(buffer, 0, buffer.Length);
        stream2.FlushFinalBlock();
        str2 = Convert.ToBase64String(stream.ToArray());
    }
    catch (Exception)
    {
        str2 = "";
    }
    finally
    {
        provider = null;
        stream = null;
        stream2 = null;
    }
    return str2;
}

和我做过到目前为止在PHP代码如下:

And the code that I've done till now in PHP is the following:

function encrypt($string) {
    //Key
    $key = "29393651";
    $ivArray=array( 0x45, 50, 0xa5, 0x18, 0x67, 0x58, 0xac, 0xba );
    $iv=null;
    foreach ($ivArray as $element)
        $iv.=CHR($element);

    echo "Key: $key    IV: $iv<br>";

    $encrypted_string = mcrypt_encrypt(MCRYPT_DES, $key, $string, MCRYPT_MODE_CBC, $iv);

    return base64_encode($encrypted_string);
}



但我找不到哪里出了问题,因为他们不,给予相同的输入相同的结果。

But I can't find where is the problem, as they don't give the same result for the same input.

任何帮助将是非常值得欢迎的:)

Any help will be very welcome :)

推荐答案

检查您的填充。 PHP内部垫中的数据与二进制空值 \x00 被默认加密这是不明确.NET中默认填充模式(最有可能的,他们使用PKCS7填充默认情况下)

Check your padding. PHP internally pads the data to be encrypted with binary NULLs \x00 by default which is definitively not the default padding mode in .NET (most likely they use PKCS7 padding by default).

这篇关于DES加密在PHP和C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆