我试图在C#代码中使用与PHP相同的DES编码。
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中所做的代码如下:
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);
}
但我无法找到问题所在,因为他们没有为同一输入提供相同的结果。
非常欢迎任何帮助:)
答案 0 :(得分:2)
检查padding。 PHP默认使用二进制NULL \x00
填充要加密的数据,这绝对不是.NET中的默认填充模式(默认情况下,它们很可能使用PKCS7填充)。
答案 1 :(得分:2)
非常感谢你们。帮助我同样的问题。 这里填写PKCS7:How to add/remove PKCS7 padding from an AES encrypted string?只需将ecb更改为cbc
这是我使用的简短快照:
$key = "29393651";
$iv = $key;
$pass_enc = $mypassword;
$block = mcrypt_get_block_size('des', 'cbc');
$pad = $block - (strlen($pass_enc) % $block);
$pass_enc .= str_repeat(chr($pad), $pad);
$pass_enc = mcrypt_encrypt(MCRYPT_DES, $key, $pass_enc, MCRYPT_MODE_CBC, $iv);
$pass_enc = base64_encode ($pass_enc);