C# 使用C解密PHP加密的字符串#
我有这个PHP函数来加密字符串C# 使用C解密PHP加密的字符串#,c#,php,C#,Php,我有这个PHP函数来加密字符串 function addpadding($string, $blocksize = 16) { $len = strlen($string); $pad = $blocksize - ($len % $blocksize); $string .= str_repeat(chr($pad), $pad); return $string; } function AESEncrypt($message, $keystring, $IVst
function addpadding($string, $blocksize = 16)
{
$len = strlen($string);
$pad = $blocksize - ($len % $blocksize);
$string .= str_repeat(chr($pad), $pad);
return $string;
}
function AESEncrypt($message, $keystring, $IVstring){
$IV_UTF = mb_convert_encoding($IVstring, 'UTF-8');
$KEY_UTF = $keystring;
return base64_encode( mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $KEY_UTF, addpadding($message), MCRYPT_MODE_CBC, $IV_UTF));
}
现在,我需要使用C#解密此函数加密的字符串,但由于我是C#新手,除了基于此加密函数编写解密函数(此函数与上面的PHP函数匹配)外,我无法做任何其他事情:
这就是我试图做的(但没有运气):
谢谢你的帮助 可能的副本由c#加密并由php解密。我试图编写一个基于加密函数的解密函数,但失败了。关于其他加密/解密问题,它们的加密函数的输出与我的不同,因此它们的解密函数不会做任何事情。我必须让它与其他使用objective-c的东西匹配,我做到了,所以我不想更改我的加密函数。如果你能帮助我,那么请。
public static string EncryptString(string message, string KeyString, string IVString)
{
byte[] Key = ASCIIEncoding.UTF8.GetBytes(KeyString);
byte[] IV = ASCIIEncoding.UTF8.GetBytes(IVString);
string encrypted = null;
RijndaelManaged rj = new RijndaelManaged();
rj.Key = Key;
rj.IV = IV;
rj.Mode = CipherMode.CBC;
try
{
MemoryStream ms = new MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(message);
sw.Close();
}
cs.Close();
}
byte[] encoded = ms.ToArray();
encrypted = Convert.ToBase64String(encoded);
ms.Close();
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("A file error occurred: {0}", e.Message);
return null;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: {0}", e.Message);
}
finally
{
rj.Clear();
}
return encrypted;
}
string enctext = EncryptString("test", "qwertyuiopasdfghjklzxcvbnmqwerty", _"1234567890123456");
// Decrypt a byte array into a byte array using a key and an IV
private byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
{
byte[] decryptedData;
//string plaintext = null;
//MemoryStream ms = new MemoryStream(cipherData);
RijndaelManaged alg = new RijndaelManaged();
alg.KeySize = 256;
alg.BlockSize = 128;
alg.Key = Key;
alg.IV = IV;
alg.Mode = CipherMode.CBC;
alg.Padding = PaddingMode.Zeros;
//Array.Copy(Key, 0, IV, 0, IV.Length);
ICryptoTransform decryptor = alg.CreateDecryptor(alg.Key, alg.IV);
using(MemoryStream ms = new MemoryStream(cipherData))
{
using (CryptoStream csDecrypt = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sw = new StreamReader(csDecrypt))
{
sw.ReadToEnd();
sw.Close();
}
csDecrypt.Close();
decryptedData = ms.ToArray();
}
}
//byte[] decryptedData = System.Text.Encoding.Unicode.GetBytes(plaintext);
return decryptedData;
}