我在这里有这个C#代码,我试图将它移植到PHP。此代码使用特定的IV和密钥加密和解密文本。我试图将其转换为PHP,但我不了解它所拥有的C#字节数组IV。这是IV,然后是Key。
private static readonly byte[] IV = new byte[32]
{
(byte) 143,
(byte) 18,
(byte) 207,
(byte) 184,
(byte) 193,
(byte) 173,
(byte) 252,
(byte) 103,
(byte) 12,
(byte) 202,
(byte) 6,
(byte) 9,
(byte) 162,
(byte) 187,
(byte) 221,
(byte) 66,
(byte) 81,
(byte) 192,
(byte) 51,
(byte) 186,
(byte) 197,
(byte) 251,
(byte) 90,
(byte) 247,
(byte) 111,
(byte) 237,
(byte) 182,
(byte) 168,
(byte) 195,
(byte) 0,
(byte) 156,
(byte) 133
};
private static readonly byte[] Key = new byte[32]
{
(byte) 130,
(byte) 94,
(byte) 5,
(byte) 131,
(byte) 159,
(byte) 45,
(byte) 165,
(byte) 206,
(byte) 66,
(byte) 115,
(byte) 19,
(byte) 144,
(byte) 242,
(byte) 142,
(byte) 97,
(byte) 6,
(byte) 50,
(byte) 47,
(byte) 92,
(byte) 70,
(byte) 241,
(byte) 179,
(byte) 77,
(byte) 121,
(byte) 222,
(byte) 243,
(byte) 13,
(byte) 171,
(byte) 16,
(byte) 92,
(byte) 197,
(byte) 174
};
我尝试将其转换为字符串,但我收到了很多奇怪的字符。在PHP中,我希望能够这样做:
base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, "KEY_HERE", $text, MCRYPT_MODE_ECB, "IV HERE", MCRYPT_RAND)))
以下是C#加密和解密功能:
private string EncryptCommand(string command)
{
using (Rijndael rijndael = (Rijndael) new RijndaelManaged())
{
rijndael.KeySize = 256;
rijndael.BlockSize = 256;
rijndael.Padding = PaddingMode.PKCS7;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream((Stream) memoryStream, rijndael.CreateEncryptor(API.Key, API.IV), CryptoStreamMode.Write))
{
byte[] bytes = Encoding.UTF8.GetBytes(command);
cryptoStream.Write(bytes, 0, bytes.Length);
cryptoStream.FlushFinalBlock();
return Convert.ToBase64String(memoryStream.ToArray());
}
}
}
}
private byte[] DecryptCommand(byte[] command)
{
using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
{
rijndaelManaged.KeySize = 256;
rijndaelManaged.BlockSize = 256;
rijndaelManaged.Padding = PaddingMode.PKCS7;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream((Stream) memoryStream, rijndaelManaged.CreateDecryptor(API.Key, API.IV), CryptoStreamMode.Write))
{
cryptoStream.Write(command, 0, command.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
}
}
}
我遇到问题的主要部分是将IV和Key转换为可以放入PHP函数的字符串。任何帮助表示赞赏。
答案 0 :(得分:2)
字节数组的等价物是PHP中的字符串。
$iv = array(143,18,207,184,193,173,252,103,12,202,6,9,162,187,221,66,81,192,51,186,197,251,90,247,111,237,182,168,195,0,156,133);
$key = array(130,94,5,131,159,45,165,206,66,115,19,144,242,142,97,6,50,47,92,70,241,179,77,121,222,243,13,171,16,92,197,174);
$str_iv = implode(array_map("chr", $iv));
$str_key = implode(array_map("chr", $key));
所以我所做的就是获取你的字节数组并将每个数组值转换为ASCII字符并将它们连接成一个字符串。
我已确认$str_iv
等于Encoding.ASCII.GetString(Key, 0, Key.Length)
。