dongwei4444 2010-11-22 23:27
浏览 37
已采纳

PHP和C#中的DES加密

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

The C# code looks like the following:

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;
}

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 :)

  • 写回答

2条回答 默认 最新

  • douzi6992 2010-11-23 14:00
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了