任何人都可以为以下 C# Aes 加密提供等效的 PHP 代码,我尝试了不同的 php AES 加密,但没有用,输出不匹配,在此先感谢。
这里使用的 key 和 iv 值是十六进制的,预期的输出是十六进制的。
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;
}
}