简体   繁体   English

c#和php中的TripleDES加密不一样

[英]TripleDES encryption in c# and php is not same

PHP code PHP代码

define('SECRET', 'Your key here');
$data = 'test';

$enc = mcrypt_cbc(MCRYPT_TRIPLEDES, SECRET, $data, MCRYPT_ENCRYPT, '12345678');

$url .= urlencode($password);

C# code 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)
    );

My problem: The value of $url in PHP and szEnc in c# is not same. 我的问题:PHP中的$ url和c#中的szEnc的值不相同。

Question: what wrong in my c# code? 问题:我的c#代码有什么问题?

A lot of things can go wrong - but I've seen quite a lot of encoding (ie non cryptographic) issue when dealing with string and byte[] . 很多事情都可能出错 - 但在处理stringbyte[]时,我看到了很多编码(即非加密)问题。

Never assume they will convert into anything, including ASCII. 永远不要假设他们会转换成任何东西,包括ASCII。

Encoding.ASCII.GetString(enc)

If you have unprintable characters, NUL... then this will not be part of the returned string and won't be url-encoded. 如果你有不可打印的字符,NUL ...那么这将不是返回字符串的一部分,也不会被url编码。 This is ask true for PHP but it does not means it follows the same rule in every case. 这对于PHP来说是真的,但并不意味着它在每种情况下都遵循相同的规则。

Also I can't tell you what code like: 另外我不能告诉你什么代码:

ec.GetBytes("Your key here");

will do ?!? 会做 ?!? If you're using an Unicode encoder then it won't give you the same as an ASCII encoder. 如果您使用的是Unicode编码器,那么它将不会与ASCII编码器相同。

Beside encoding also check that the PaddingMode you use match the one used by PHP. 除了编码之外,还要检查您使用的PaddingMode是否与PHP使用的匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM