У меня есть код на C # для шифрования и дешифрования. Иногда расшифрованный вывод не выглядит правильным. Я не получаю ошибку, но после того, как я делаю:
UTF8Encoding encoder = new UTF8Encoding();
string strres = encoder.GetString(plainTextBytes);
вывод в strres
примерно такой:
N%�S
ɷ,as
��_9�R����c!���SJ�?���ķ}{��
Я использую следующий код:
static public string RijndaelEncrypt(string DataToEncrypt, string IV,string Key)
{
ASCIIEncoding ByteConverter = new ASCIIEncoding();
byte[] dataToEncrypt;
byte[] encryptedData;
dataToEncrypt = Encoding.UTF8.GetBytes(DataToEncrypt);
using (Rijndael myRijndael = Rijndael.Create())
{
myRijndael.IV = ByteConverter.GetBytes(string.Concat(IV, KeyPart));
myRijndael.Mode = CipherMode.CBC;
myRijndael.Padding = PaddingMode.Zeros;
for (int i = Key.Length; i < myRijndael.Key.Length; i++)
{
Key=string.Concat(Key,"a");
}
myRijndael.Key = ByteConverter.GetBytes(Key.Substring(0,myRijndael.Key.Length));
encryptedData = new byte[dataToEncrypt.Length];
using (MemoryStream fout = new MemoryStream(dataToEncrypt.Length))
{
using (CryptoStream encStream = new CryptoStream(fout, myRijndael.CreateEncryptor(myRijndael.Key, myRijndael.IV), CryptoStreamMode.Write))
{
encStream.Write(dataToEncrypt, 0, dataToEncrypt.Length);
encStream.FlushFinalBlock();
encryptedData = fout.ToArray();
}
}
}
return Convert.ToBase64String(encryptedData);
}
static public string RijndaelDecrypt(string DataToDecrypt, string IV, string Key)
{
ASCIIEncoding ByteConverter = new ASCIIEncoding();
byte[] dataToDecrypt = Convert.FromBase64String(DataToDecrypt.Replace(" ","+"));
byte[] decryptedData =new byte[dataToDecrypt.Length];
int decryptedByteCount=0;
using (Rijndael myRijndael = Rijndael.Create())
{
myRijndael.IV = ByteConverter.GetBytes(string.Concat(IV, KeyPart));
myRijndael.Mode = CipherMode.CBC;
myRijndael.Padding = PaddingMode.Zeros ;
int i123 = myRijndael.BlockSize;
for (int i = Key.Length; i < myRijndael.Key.Length; i++)
{
Key = string.Concat(Key,"a");
}
myRijndael.Key = ByteConverter.GetBytes(Key.Substring(0, myRijndael.Key.Length));
var fout = new MemoryStream(dataToDecrypt);
var cryptoStream = new CryptoStream(fout,myRijndael.CreateDecryptor(myRijndael.Key,myRijndael.IV), CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[decryptedData.Length];
decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
fout.Close();
cryptoStream.Close();
UTF8Encoding encoder = new UTF8Encoding();
string strres = encoder.GetString(plainTextBytes); //new String(plainTextBytes,);// Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
return strres;
}
}