本文介紹了PHP 和 C# 中的 DES 加密的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試實現與在 C# 代碼中但在 PHP 中相同的 DES 加密.
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.
非常歡迎任何幫助:)
推薦答案
檢查您的 padding.默認情況下,PHP 在內部使用二進制 NULL 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).
這篇關于PHP 和 C# 中的 DES 加密的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!