private static readonly byte[] IV = new byte[8] { 240, 3, 45, 29, 0, 76, 173, 59 };
public string Decrypt(string encryptedData,string key)
{
encryptedData = HttpUtility.UrlDecode(encryptedData);
byte[] buf = Convert.FromBase64String(encryptedData);
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
des.IV = IV;
return Encoding.ASCII.GetString(
des.CreateDecryptor().TransformFinalBlock(
buf,
0,
buf.Length
)
);
}
}
有没有办法将上面的.Net代码转换为PHP,以便我可以解密从.Net代码发送的PHP中的数据?
答案 0 :(得分:1)
答案 1 :(得分:1)
我不是加密专家,但这应该是有效的例子......
# original C# code
# private static readonly byte[] IV = new byte[8] { 240, 3, 45, 29, 0, 76, 173, 59 };
# public string Decrypt(string encryptedData,string key)
# {
# encryptedData = HttpUtility.UrlDecode(encryptedData);
# byte[] buf = Convert.FromBase64String(encryptedData);
# TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
# MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
# des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
# des.IV = IV;
# return Encoding.ASCII.GetString(
# des.CreateDecryptor().TransformFinalBlock(
# buf,
# 0,
# buf.Length
# )
# );
# }
# }
// packs array into bytestring
function pack_array($a) {
$out = null;
foreach ($a as $i) { $out .= chr(ord(substr($i,0,1))); }
var_dump(($out));
return $out;
}
class Sample {
public static $IV = array( 240, 3, 45, 29, 0, 76, 173, 59 );
public static $key = 's3cr3tk3yl0ng1n4ph';
// 3des encryption
public static function Encrypt($data) {
$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
$ks = mcrypt_enc_get_key_size($td);
// create key
$key = substr(md5(self::$key), 0, $ks);
// pack IV
$IVPacked = pack_array(self::$IV);
mcrypt_generic_init($td, $key, $IVPacked);
$encryptedData = mcrypt_generic($td, $data);
mcrypt_generic_deinit($td);
$encryptedData = base64_encode($encryptedData);
$encryptedData = urlencode($encryptedData);
return $encryptedData;
}
// 3des decryption
public static function Decrypt($encryptedData, $key) {
$td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');
$encryptedData = urldecode($encryptedData);
$encryptedData = base64_decode($encryptedData);
$key = substr(md5($key), 0, mcrypt_enc_get_key_size($td));
$IVPacked = pack_array(self::$IV);
mcrypt_generic_init($td, $key, $IVPacked);
$decryptedData = mdecrypt_generic($td, $encryptedData);
mcrypt_generic_deinit($td);
return $decryptedData;
}
}
// __main__
$data = "methodname=GetClientшђшђ";
var_dump($data);
//var_dump(unpack_str($data, strlen($data)));
$encryptedData = Sample::Encrypt($data);
//var_dump(bin2hex(Sample::$IV));
var_dump (bin2hex($encryptedData));
$decryptedData = Sample::Decrypt($encryptedData, Sample::$key);
var_dump($decryptedData);
echo "\n";