C# 和 PHP 中的 TripleDES 加密是不一样的


TripleDES encryption in c# and php is not same

PHP 代码

define('SECRET', 'Your key here');
$data = 'test';
$enc = mcrypt_cbc(MCRYPT_TRIPLEDES, SECRET, $data, MCRYPT_ENCRYPT, '12345678');
$url .= urlencode($password);

C# 代码

byte[] key = ec.GetBytes("Your key here");
byte[] iv = ec.GetBytes("12345678");
byte[] data = ec.GetBytes("test");
byte[] enc = new byte[0];
TripleDES tdes = TripleDES.Create();
tdes.IV = iv;
tdes.Key = key;
tdes.Mode = CipherMode.CBC;
tdes.Padding = PaddingMode.Zeros;
ICryptoTransform ict = tdes.CreateEncryptor();
enc = ict.TransformFinalBlock(data, 0, data.Length);
string szEnc = HttpContext.Current.Server.UrlEncode(
    Encoding.ASCII.GetString(enc)
    );

我的问题是:PHP 中的 $url 值和 c# 中的 szEnc 值不同。

问:我的 C# 代码中有什么问题?

很多事情都可能出错 - 但是我在处理stringbyte[]时看到了很多编码(即非加密(问题。

永远不要假设它们会转换为任何东西,包括 ASCII。

Encoding.ASCII.GetString(enc)

如果您有不可打印的字符,则无需...然后,这将不是返回的字符串的一部分,也不会进行 URL 编码。对于PHP来说,这是正确的,但这并不意味着它在每种情况下都遵循相同的规则。

我也不能告诉你代码是什么样的:

ec.GetBytes("Your key here");

会做?!?如果您使用的是 Unicode 编码器,那么它不会为您提供与 ASCII 编码器相同的功能。

除了编码之外,还要检查您使用的PaddingMode是否与 PHP 使用的匹配。