我有一个test.php,内容如下:
echo encrypt("something");
function encrypt($str)
{
$enc_key = "my key is 8 char long";
$ivArray=array( 0x10, 0x12, 5, 0x11, 0x23, 1, 0x55, 0x43 );
$iv=null;
foreach ($ivArray as $element)
$iv.=CHR($element);
return strtoupper(bin2hex(base64_encode(mcrypt_encrypt(MCRYPT_DES, $enc_key, $str, MCRYPT_MODE_CBC, $iv))));
}
然后在我的C#代码上:
private static byte[] iv = new byte[] { 0x10, 0x12, 5, 0x11, 0x23, 1, 0x55, 0x43 };
public string ConvertString(string input, string myKey)
{
try
{
input = byteArrayString(input);
byte[] bytes = Encoding.UTF8.GetBytes(myKey);
byte[] buffer = Convert.FromBase64String(input);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream stream = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(bytes, iv), CryptoStreamMode.Write);
stream2.Write(buffer, 0, buffer.Length);
stream2.FlushFinalBlock();
return Encoding.UTF8.GetString(stream.ToArray());
}
catch
{
return string.Empty;
}
}
private string byteArrayString(string input)
{
byte[] buffer = new byte[input.Length / 2];
for (int i = 0; i < input.Length; i += 2)
{
if (i < input.Length)
{
buffer[i / 2] = (byte)((Uri.FromHex(input[i]) * 0x10) + Uri.FromHex(input[i + 1]));
}
}
return Encoding.UTF8.GetString(buffer);
}
如果我在C#上完成所有工作,那么从PHP到C#的区别在于从PHP产生的加密中的12个字节。
我在PHP方面做错了什么来匹配加密?
更新(PKCS7):
$block = mcrypt_get_block_size('des', 'cbc');
$len = strlen($str);
$padding = $block - ($len % $block);
$str .= str_repeat(chr($padding),$padding);
答案 0 :(得分:1)
使用CodesInChaos帮助我已经用PHP下面的代码解决了它,以正确填充它。
CodesInChaos如果您想发布回复,我会将其标记为正确答案,否则我会将其标记为。
$block = mcrypt_get_block_size('des', 'cbc');
$len = strlen($str);
$padding = $block - ($len % $block);
$str .= str_repeat(chr($padding),$padding);