Шифрование строк - не получается реализовать расшифровку - C#
Формулировка задачи:
Доброго времени суток, продолжаю разбираться в .NET и вновь прошу помощи у Гуру.
Сейчас пробую вкурить шифрование, а именно AES через класс AesManaged: шифрует он все превосходно, а вот обратно как-то не идет, в чем Ваш покорный дурак?
P.S. Заранее спасибо, листинг прилагаю.
Класс для шифрования и дешифрования строки с парой тематических методов, двумя конструкторами и полями для хранения алгоритма шифрования, ключика и соли:
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace AES_Symmetric_Encryption
{
/// <summary>
/// Класс, реализующий шифрование
/// </summary>
public class TextEncryptor
{
/// <summary>
/// приватные поля класса
/// </summary>
private AesManaged algorithm = new AesManaged();
private byte[] rgbKey;
private byte[] rgbSalt;
private MemoryStream buffer = new MemoryStream();
/// <summary>
/// Конструктор по умолчанию
/// </summary>
public TextEncryptor()
{
string password = "Pa$$w0rd";
string salt = "s@lT";
var rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));
rgbKey = rgb.GetBytes(algorithm.KeySize / 8);
rgbSalt = rgb.GetBytes(algorithm.BlockSize / 8);
}
/// <summary>
/// Конструктр с параметрами
/// </summary>
/// <param name="password"></param>
/// <param name="salt"></param>
public TextEncryptor(string password, string salt)
{
var rgb = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));
rgbKey = rgb.GetBytes(algorithm.KeySize / 8);
rgbSalt = rgb.GetBytes(algorithm.BlockSize / 8);
}
/// <summary>
/// Метод шифрования строки
/// </summary>
/// <param name="decryptedText"></param>
/// <returns></returns>
public string TextEncryption(string decryptedText)
{
var bytesToTransform = Encoding.Unicode.GetBytes(decryptedText);
var algorithmEncryptor = algorithm.CreateEncryptor(rgbKey, rgbSalt);
var cryptoStream = new CryptoStream(buffer, algorithmEncryptor, CryptoStreamMode.Write);
cryptoStream.Write(bytesToTransform, 0, bytesToTransform.Length);
cryptoStream.FlushFinalBlock();
buffer.Position = 0;
StreamReader sr = new StreamReader(buffer);
string encryptedString = sr.ReadToEnd();
cryptoStream.Close();
buffer.Close();
return encryptedString;
}
/// <summary>
/// Метод дешифрвания строки
/// </summary>
/// <param name="encryptedText"></param>
/// <returns></returns>
public string TextDecryption(string encryptedText)
{
var bytesToTransform = Encoding.Unicode.GetBytes(encryptedText);
var algorithmDecryptor = algorithm.CreateDecryptor(rgbKey, rgbSalt);
var cryptoStream = new CryptoStream(buffer, algorithmDecryptor, CryptoStreamMode.Write);
cryptoStream.Write(bytesToTransform, 0, bytesToTransform.Length);
cryptoStream.FlushFinalBlock();
buffer.Position = 0;
StreamReader sr = new StreamReader(buffer);
string decryptedString = sr.ReadToEnd();
cryptoStream.Close();
buffer.Close();
return decryptedString;
}
}
}Вызывающий код:
using System;
namespace AES_Symmetric_Encryption
{
class Program
{
static void Main(string[] args)
{
string originalString = "Top Secret Information!";
TextEncryptor textEncryptor = new TextEncryptor();
string encryptedText = textEncryptor.TextEncryption(originalString);
string decryptedText = textEncryptor.TextDecryption(encryptedText);
Console.WriteLine("Original string {0}\nEncrypted string: {1}\nDecrypted string: {2}",
originalString ,encryptedText, decryptedText);
}
}
}Решение задачи: «Шифрование строк - не получается реализовать расшифровку»
textual
Листинг программы
using System;
using System.Text;
namespace AES_Symmetric_Encryption
{
class Program
{
static void Main(string[] args)
{
string originalString = "Top Secret Information!";
byte[] originalBytes = Encoding.Unicode.GetBytes(originalString);
TextEncryptor textEncryptor = new TextEncryptor();
byte[] encryptedBytes = textEncryptor.TextEncryption(originalBytes);
byte[] decryptedBytes = textEncryptor.TextDecryption(encryptedBytes);
String encryptedString = Encoding.Unicode.GetString(encryptedBytes);
String decryptedString = Encoding.Unicode.GetString(decryptedBytes);
Console.WriteLine("Original string {0}\nEncrypted string: {1}\nDecrypted string: {2}",
originalString ,encryptedString, decryptedString);
Console.ReadLine();
}
}
}