当我用C#加密时,我得到arTdPqWOg6VppOqUD6mGITjb24 x5vJjfAufNQ4DN7rVEtpDmhFnMeJGg4n5y1BN
static void Main(string[] args) { Encoding byteEncoder = Encoding.Default; String key = "ShHhd8a08JhJiho98ayslcjh"; String message = "Let us meet at 9 o'clock at the secret place."; String encryption = Encrypt(message,key,false); String decryption = Decrypt(encryption,false); Console.WriteLine("Message: {0}",message); Console.WriteLine("Encryption: {0}",encryption); Console.WriteLine("Decryption: {0}",decryption); } public static string Encrypt(string toEncrypt,string key,bool useHashing) { byte[] keyArray; byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray,toEncryptArray.Length); return Convert.ToBase64String(resultArray,resultArray.Length); } public static string Decrypt(string toDecrypt,bool useHashing) { byte[] keyArray; byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray,toEncryptArray.Length); return UTF8Encoding.UTF8.GetString(resultArray); }
当我用PHP加密时,我得到:arTdPqWOg6VppOqUD6mGITjb24 x5vJjfAufNQ4DN7rVEtpDmhFnMVM W / WFlksR
<?PHP $key = "ShHhd8a08JhJiho98ayslcjh"; $input = "Let us meet at 9 o'clock at the secret place."; $td = mcrypt_module_open('tripledes','','ecb',''); $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td),MCRYPT_RAND); mcrypt_generic_init($td,$key,$iv); $encrypted_data = mcrypt_generic($td,$input); mcrypt_generic_deinit($td); mcrypt_module_close($td); echo base64_encode($encrypted_data); ?>
我对密码学知之甚少,无法弄清楚原因.有任何想法吗?谢谢.
彼得是对的. PHP只是用零填充,而你在C#代码中使用PKCS#7.这是一些应该正确的代码:
原文链接:https://www.f2er.com/php/130424.htmlfunction pkcs7_pad($text,$blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad),$pad); } $input = pkcs7_pad("Let us meet at 9 o'clock at the secret place.",16);
或者,你应该能够将它放在你的C#代码中:
tdes.Padding = PaddingMode.Zeros;
并且它也有效(虽然稍微不那么安全).