What I need to do recently is that php returns a 3des encrypted URL to .net, and then the .net side decrypts it. The implementation of php has never been able to match the .net end. I will write it down here first and hope to see some guidance from experts. There are countless people on the Internet who copy it without verifying it personally. I hope everyone can adhere to the rigorous method in the future.
Before the PHP encryption extension library Mcrypt encrypts and decrypts data, it first creates an initialization vector, referred to as iv for short. From $iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher,$modes),MCRYPT_RAND); it can be seen that creating an initialization vector requires two parameters: size specifies the size of iv; source is the source of iv, where the value MCRYPT_RAND is the system random number.
The function mcrypt_get_iv_size($cipher,$modes) returns the initialization vector size. The parameters cipher and mode refer to the algorithm and encryption mode respectively.
Php code
function encrypt($input){//数据加密 $key=md5("XXXXXXXXX",TRUE); $key=base64_encode($key); $size = mcrypt_get_block_size(MCRYPT_3DES,MCRYPT_MODE_ECB); $input = $this->pkcs5_pad($input, $size); //$key = str_pad($this->key,24,'0'); $key = str_pad($key,24,'0'); $td = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_ECB, ''); // $iv = @mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);//初始化向量 $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_3DES,MCRYPT_MODE_ECB), MCRYPT_RAND); @mcrypt_generic_init($td, $key, $iv); $data = mcrypt_generic($td, $input); mcrypt_generic_deinit($td); mcrypt_module_close($td); // $data = base64_encode($this->PaddingPKCS7($data)); $data = base64_encode($data); return $data; }
Php code
function pkcs5_pad ($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); }
The code on the .net side is implemented as follows:
C# code
var des = new TripleDESCryptoServiceProvider(); var hashMd5 = new MD5CryptoServiceProvider(); des.Key = hashMd5.ComputeHash(Encoding.Default.GetBytes(strKey)); des.Mode = CipherMode.ECB; des.Padding = PaddingMode.Zeros; var desEncrypt = des.CreateEncryptor(); var buffer = Encoding.Default.GetBytes(strString); return Convert.ToBase64String(desEncrypt.TransformFinalBlock(buffer, 0, buffer.Length));
I found another way to implement php, but none of them work.
Php code
function encrypt($string) { //加密用的密钥文件 $key=md5("XXXXXXXXXXXX",TRUE); $key=base64_encode($key); //加密方法 $cipher_alg = MCRYPT_TRIPLEDES; //初始化向量来增加安全性 $iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg,MCRYPT_MODE_ECB), MCRYPT_RAND); //开始加密 $encrypted_string = mcrypt_encrypt($cipher_alg, $key, $string, MCRYPT_MODE_ECB, $iv); return base64_encode($encrypted_string);//转化成16进制 }