Вывести строку в зашифрованном виде - C#
Формулировка задачи:
Доброго дня.
Есть код AES шифрования, реализованный в C#, нужно вывести слово которое мы шифруем, то есть его в вид в зашифрованном виде
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Security.Cryptography;
- using System.Text;
- using System.Threading.Tasks;
- namespace shifr
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- const string original = "the world is your"; // шифруемая константа
- // Создаем новый экземпляр класса Aes
- // Создаем ключ и вектор инициализации (IV)
- using (var myAes = Aes.Create())
- {
- // Зашифрованную строку переводим в массив байтов
- byte[] encrypted = EncryptStringToBytesAes(original, myAes.Key, myAes.IV);
- // Расшифровываем байты и записываем в строку.
- string roundtrip = DecryptStringFromBytesAes(encrypted, myAes.Key, myAes.IV);
- //Выводим на экран результат
- Console.WriteLine("Original: {0}", original);
- Console.WriteLine("Round Trip: {0}", roundtrip);
- }
- }
- catch (Exception e)
- {
- // Если что-то не так выбрасываем исключение
- Console.WriteLine("Error: {0}", e.Message);
- }
- Console.ReadKey();
- }
- static byte[] EncryptStringToBytesAes(string plainText, byte[] Key, byte[] IV)
- {
- // Проверка аргументов
- if (plainText == null || plainText.Length <= 0)
- throw new ArgumentNullException("plainText");
- if (Key == null || Key.Length <= 0)
- throw new ArgumentNullException("Key");
- if (IV == null || IV.Length <= 0)
- throw new ArgumentNullException("IV");
- byte[] encrypted;
- // Создаем объект класса AES
- // с определенным ключом and IV.
- using (Aes aesAlg = Aes.Create())
- {
- aesAlg.Key = Key;
- aesAlg.IV = IV;
- // Создаем объект, который определяет основные операции преобразований.
- ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
- // Создаем поток для шифрования.
- using (var msEncrypt = new MemoryStream())
- {
- using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
- {
- using (var swEncrypt = new StreamWriter(csEncrypt))
- {
- //Записываем в поток все данные.
- swEncrypt.Write(plainText);
- }
- encrypted = msEncrypt.ToArray();
- }
- }
- }
- //Возвращаем зашифрованные байты из потока памяти.
- return encrypted;
- }
- static string DecryptStringFromBytesAes(byte[] cipherText, byte[] Key, byte[] IV)
- {
- // Проверяем аргументы
- if (cipherText == null || cipherText.Length <= 0)
- throw new ArgumentNullException("cipherText");
- if (Key == null || Key.Length <= 0)
- throw new ArgumentNullException("Key");
- if (IV == null || IV.Length <= 0)
- throw new ArgumentNullException("IV");
- // Строка, для хранения расшифрованного текста
- string plaintext;
- // Создаем объект класса AES,
- // Ключ и IV
- using (Aes aesAlg = Aes.Create())
- {
- aesAlg.Key = Key;
- aesAlg.IV = IV;
- // Создаем объект, который определяет основные операции преобразований.
- ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
- // Создаем поток для расшифрования.
- using (var msDecrypt = new MemoryStream(cipherText))
- {
- using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
- {
- using (var srDecrypt = new StreamReader(csDecrypt))
- {
- // Читаем расшифрованное сообщение и записываем в строку
- plaintext = srDecrypt.ReadToEnd();
- }
- }
- }
- }
- return plaintext;
- }
- }
- }
Решение задачи: «Вывести строку в зашифрованном виде»
textual
Листинг программы
- // Шифруем строку
- byte[] encrypted = EncryptStringToBytesAes(original, myAes.Key, myAes.IV);
- // Выводим на экран в виде hex-строки
- Console.WriteLine(BitConverter.ToString(encrypted));
- // Еще можем вывести в виде base64 строки
- Console.WriteLine(Convert.ToBase64String(encrypted));
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д