【发布时间】:2016-01-27 04:56:44
【问题描述】:
需要将以下函数从PHP转换为C#(asp.net)
function encrypt_3DES($message, $key){
// Se establece un IV por defecto
$bytes = array(0,0,0,0,0,0,0,0); //byte [] IV = {0, 0, 0, 0, 0, 0, 0, 0}
$iv = implode(array_map("chr", $bytes)); //PHP 4 >= 4.0.2
// Se cifra
$ciphertext = mcrypt_encrypt(MCRYPT_3DES, $key, $message, MCRYPT_MODE_CBC, $iv); //PHP 4 >= 4.0.2
return $ciphertext;
}
在哪里
$message 是要编码的字符串,$key 是关键
$key 是 base 64 编码,在调用函数之前被解码
$key = $this->decodeBase64($key);
$ciphertext = $this->encrypt_3DES($message, $key);
按照我使用的 C# 代码:
key = Base64Decode(key);
ciphertext = encrypt_3DES(order, key,true);
在哪里
private string Base64Decode(string base64EncodedData)
{
byte[] base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return Encoding.GetEncoding(28591).GetString(base64EncodedBytes);
// 28591 for php compatibility
}
和
private string encrypt_3DES(string message, string k,bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(message);
//If hashing use get hashcode regards to your key
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(Encoding.GetEncoding(28591).GetBytes(k));
//Always release the resources and flush data
// of the Cryptographic service provide. Best Practice
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.GetEncoding(28591).GetBytes(k);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
//transform the specified region of bytes array to resultArray
byte[] resultArray =
cTransform.TransformFinalBlock(toEncryptArray, 0,
toEncryptArray.Length);
//Release resources held by TripleDes Encryptor
tdes.Clear();
//Return the encrypted data into unreadable string format
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
PHP 和 C# 的结果不一样。
【问题讨论】:
-
C# 中的散列、密码模式和密码填充存在一些差异。此外,考虑到 C# 代码的外观,您的 PHP 代码似乎不完整。您能否另外提供一些示例消息和密钥?
-
你应该使用 CBC,一个显式的 IV,你应该使用一个由字节组成的键,而不是一个字符串。如果你在方法参数中使用字符串,你已经迷路了。
-
@Artjom B. 完整源代码在以下链接link
-
@Maarten Bodewes 这是信用卡支付电路的接口。密钥以 Base 64 编码的字符串形式提供。银行 IT 部门不提供 C# 接口。所以我正在尝试从 PHP 翻译。感谢您的建议。
-
对不起,我的意思是你不应该使用 after base 64 解码的字符串。解码后,您应该使用字节。 IE。只需
base64EncodedBytes和byte[] k作为参数。
标签: c# php asp.net encryption 3des