以下の C# Aes 暗号化に相当する PHP コードを提供してください。別の php AES 暗号化を試しましたが、役に立たず、出力が一致しません。事前に感謝します。
ここで使用されるキーと iv の値は 16 進数で、期待される出力は 16 進数です。
C#:
public class AESAlgorithm
{
public static string GeneratePrivateKey()
{
string str;
RijndaelManaged rijndaelManaged = null;
try
{
rijndaelManaged = new RijndaelManaged();
rijndaelManaged.KeySize = 128;
rijndaelManaged.GenerateKey();
str = ConvertByteArrayToHexString(rijndaelManaged.Key);
}
finally
{
if (rijndaelManaged == null)
{
rijndaelManaged.Clear();
}
}
return str;
}
public static string GenerateAuthKey(string timestamp, string appCode, string attUid, string privateKey)
{
return Encrypt(String.Format("{0}|{1}|{2}", timestamp, appCode, attUid), privateKey);
}
public static string Encrypt(string textToEncrypt, string hexStringKey)
{
string str1;
RijndaelManaged rijndaelManaged = null;
try
{
rijndaelManaged = new RijndaelManaged();
rijndaelManaged.Mode = CipherMode.CBC;
rijndaelManaged.Padding = PaddingMode.PKCS7;
rijndaelManaged.KeySize = 128;
rijndaelManaged.BlockSize = 128;
byte[] bs1 = ConvertHexStringToByteArray(hexStringKey);
rijndaelManaged.Key = bs1;
rijndaelManaged.IV = bs1;
ICryptoTransform iCryptoTransform = rijndaelManaged.CreateEncryptor();
byte[] bs2 = Encoding.UTF8.GetBytes(textToEncrypt);
str1 = ConvertByteArrayToHexString(iCryptoTransform.TransformFinalBlock(bs2, 0, (int)bs2.Length));
}
finally
{
if (rijndaelManaged == null)
{
rijndaelManaged.Clear();
}
}
return str1;
}
public static string Decrypt(string hexStringToDecrypt, string hexStringKey)
{
string str1;
RijndaelManaged rijndaelManaged = null;
try
{
rijndaelManaged = new RijndaelManaged();
rijndaelManaged.Mode = CipherMode.CBC;
rijndaelManaged.Padding = PaddingMode.PKCS7;
rijndaelManaged.KeySize = 128;
rijndaelManaged.BlockSize = 128;
byte[] bs1 = ConvertHexStringToByteArray(hexStringToDecrypt);
byte[] bs2 = ConvertHexStringToByteArray(hexStringKey);
rijndaelManaged.Key = bs2;
rijndaelManaged.IV = bs2;
byte[] bs3 = rijndaelManaged.CreateDecryptor().TransformFinalBlock(bs1, 0, (int)bs1.Length);
str1 = Encoding.UTF8.GetString(bs3);
}
finally
{
if (rijndaelManaged == null)
{
rijndaelManaged.Clear();
}
}
return str1;
}
private static string ConvertByteArrayToHexString(byte[] input)
{
bool flag;
StringBuilder stringBuilder = new StringBuilder();
byte[] bs = input;
int i = 0;
do
{
byte b = bs[i];
stringBuilder.AppendFormat("{0:x2}", b);
i++;
flag = i < (int)bs.Length;
}
while (flag);
return stringBuilder.ToString();
}
private static byte[] ConvertHexStringToByteArray(string hexString)
{
bool flag = (hexString.Length & 1) == 0;
if (!flag)
{
throw new ArgumentOutOfRangeException("hexString", hexString, "hexString must contain an even number of characters.");
}
byte[] bs1 = new byte[hexString.Length / 2];
int i = 0;
do
{
bs1[i / 2] = Byte.Parse(hexString.Substring(i, 2), NumberStyles.HexNumber);
i += 2;
flag = i < hexString.Length;
}
while (flag);
return bs1;
}
}