DES Encryption in PHP and C#(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 加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 和 C# 中的 DES 加密
基础教程推荐
- PHP 类:全局变量作为类中的属性 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
