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 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动