用PHP解密一个用C#编写的3DES字符串

时间:2012-01-20 15:37:11

标签: php encryption 3des tripledes

我必须在PHP中解密用这个C#类编码的字符串(它是here

using System;
using System.Security.Cryptography;
using System.Text;

public static class Encryption
{
   public static string Encrypt(string input, string key)
   {
      byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
      TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
      tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
      tripleDES.Mode = CipherMode.ECB;
      tripleDES.Padding = PaddingMode.PKCS7;
      ICryptoTransform cTransform = tripleDES.CreateEncryptor();
      byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
      tripleDES.Clear();
      return Convert.ToBase64String(resultArray, 0, resultArray.Length);
   }

   public static string Decrypt(string input, string key)
   {
      byte[] inputArray = Convert.FromBase64String(input);
      TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
      tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
      tripleDES.Mode = CipherMode.ECB;
      tripleDES.Padding = PaddingMode.PKCS7;
      ICryptoTransform cTransform = tripleDES.CreateDecryptor();
      byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
      tripleDES.Clear();
      return UTF8Encoding.UTF8.GetString(resultArray);
   }
}

我尝试过在网络上找到的不同示例,但似乎没有任何效果。我认为第一个问题来自php mcrypt_generic_init中的$ iv参数,然后另一个问题是php函数中缺少填充。 你能帮我转一下PHP中的c#Decrypt函数吗? 谢谢。

2 个答案:

答案 0 :(得分:2)

因为IV在ECB模式下无关紧要,我们可以忽略它。但是,mcrypt不是很宽松。我们仍然需要提供 IV,即使它是假的。

// We'll be encrypting this data
    $key = 'password';
    $data = 'The quick brown fox jumped over the lazy dogs.';
    $encrypted = null;

// 3des in ECB mode
    $m = mcrypt_module_open(MCRYPT_3DES, null, MCRYPT_MODE_ECB, null);
// Our IV will be enough NUL bytes to satisfy mcrypt.
    $fake_iv = str_repeat(chr(0), mcrypt_enc_get_iv_size($m));
    mcrypt_generic_init($m, $key, $fake_iv);
    $encrypted = mcrypt_generic($m, $data);
// "s/6HOXpVyMyFdSPYUgIgneMRY0o3Kubkwc++hSg9kC4Sw0TWsNTqzrhXY3z4PH9w"
    echo base64_encode($encrypted), "\n";
    unset($m);

// And now, in reverse!
    $n = mcrypt_module_open(MCRYPT_3DES, null, MCRYPT_MODE_ECB, null);
// Another fake IV
    $fake_iv = str_repeat(chr(0), mcrypt_enc_get_iv_size($n));
    mcrypt_generic_init($n, $key, $fake_iv);
    $original = mdecrypt_generic($n, $encrypted);
// string(48) "The quick brown fox jumped over the lazy dogs."
    var_dump($original);

同样,如果您坚持使用ECB模式,您只想这样做。 ECB模式可能非常糟糕。您可能需要查看the Wikipedia article on block cipher modes以获取更多信息。

这里唯一没有处理的是填充。 mcrypt不允许你选择填充方法,并根据密码做一些不同的事情。通常,它根本不添加任何填充。

如果您选择的填充方法使用NUL字节,则需要自己预先填充数据以确保互操作性。您可以使用mcrypt_get_block_sizestr_pad STR_PAD_RIGHT选项来执行此操作。

同样,您可能需要在解密后从右侧修剪NUL字节。 trim的第二个参数会有所帮助。

答案 1 :(得分:2)

即使我今天尝试了PHP和C#的代码

<?php
$key64 = "YOUR_KEY";
$iv64 = "YOUR_IV";


$keybytes = base64_decode($key64);
$ivbytes = base64_decode($iv64);

$text = ("4111111111111111");

// Padding the text
$padding = strlen($text)%8;
for($i=$padding; $i<8; $i++){
   $text .= chr(8-$padding);
}

$decryptRaw = mcrypt_encrypt(MCRYPT_3DES, $keybytes, $text, MCRYPT_MODE_CBC, $ivbytes);
$encoded = base64_encode($decryptRaw);

print "$encoded<br/>";
$encryptedString64 = $encoded;
$decryptbytes = base64_decode($encryptedString64);

$decryptRaw = mcrypt_decrypt(MCRYPT_3DES, $keybytes, $decryptbytes, MCRYPT_MODE_CBC, $ivbytes);
$decryptString=trim($decryptRaw,"\x00..\x1F");
print "$decryptString<br/>";

?>

C#

private string Decrypt(string encryptedValue)
{
    SymmetricAlgorithm tripleDESKey = SymmetricAlgorithm.Create("TripleDES") ;
    tripleDESKey.Key = Convert.FromBase64String("YOUR_KEY");
    tripleDESKey.IV = Convert.FromBase64String("YOUR_IV") ;

    MemoryStream encryptedStream = new MemoryStream();
    encryptedStream.Write(Convert.FromBase64String(encryptedValue), 0,
    Convert.FromBase64String(encryptedValue).Length);
    encryptedStream.Position = 0;
    CryptoStream cs = new CryptoStream(encryptedStream,
    tripleDESKey.CreateDecryptor(), CryptoStreamMode.Read);
    MemoryStream decryptedStream = new MemoryStream();

    byte[] buf = new byte[2049];
    int bytesRead = 0;
    bytesRead = cs.Read(buf, 0, buf.Length);
    while ((bytesRead > 0))
    {
        decryptedStream.Write(buf, 0, bytesRead);
        bytesRead = cs.Read(buf, 0, buf.Length);
    }
    return Encoding.ASCII.GetString(decryptedStream.ToArray());
}
private string Encrypt(string encrypt)
{
    SymmetricAlgorithm sa = SymmetricAlgorithm.Create("TripleDES") ;
    sa.Key = Convert.FromBase64String("YOUR_KEY");
    sa.IV = Convert.FromBase64String("YOUR_IV") ;
    byte[] inputByteArray = Encoding.ASCII.GetBytes(encrypt);
    MemoryStream mS = new MemoryStream();
    ICryptoTransform trans = sa.CreateEncryptor();
    byte[] buf = new byte[2049];
    CryptoStream cs = new CryptoStream(mS, trans, CryptoStreamMode.Write);
    cs.Write(inputByteArray, 0, inputByteArray.Length);
    cs.FlushFinalBlock();
    return Convert.ToBase64String(mS.ToArray());
}