Advertisement
amv1991

AES256 for strings (English explanations)

Apr 19th, 2020
776
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.89 KB | None | 1 0
  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;     //To use the cryptography functions
  4. using System.Text;
  5.  
  6. namespace AES256
  7. {
  8.     class Program
  9.     {
  10.         /*      This is an implementation of the encryption algorithm AES256
  11.          *          for strings, very usefull to encrypt messages you don't
  12.          *          want an unauthorized person to have access.
  13.          *
  14.          *      Created by: Andrew Vargas
  15.          *      Facebook: https://www.facebook.com/andrewvargas1991
  16.          */
  17.  
  18.         static void Main(string[] args)
  19.         {
  20.             Console.Write("Digite alguma coisa: ");
  21.             String originalString = Console.ReadLine();  //Read the string to be encrypted
  22.  
  23.             String encryptedString = Criptografia.Encrypt(originalString);    //Call the encryption method
  24.             String decryptedString = Criptografia.Decrypt(encryptedString);    //Call the decryption method
  25.  
  26.             //Print the original string, the encrypted and the decrypted
  27.             Console.WriteLine("\n\nOriginal: " + originalString);
  28.             Console.WriteLine("Encrypted: " + encryptedString);
  29.             Console.WriteLine("Decrypted: " + decryptedString);
  30.  
  31.             Console.WriteLine("\nPress any key to leave...");
  32.             Console.ReadKey();
  33.         }
  34.  
  35.         public class Criptografia   //Class that contains the necessary variables and functions
  36.         {
  37.             /// Array of bytes utilized by the cryptography (External Key)        
  38.             private static byte[] bIV =
  39.                 { 0x50, 0x08, 0xF1, 0xDD, 0xDE, 0x3C, 0xF2, 0x18,
  40.                     0x44, 0x74, 0x19, 0x2C, 0x53, 0x49, 0xAB, 0xBC };
  41.  
  42.             /*      Important: Case you want to get the key (password) from the keyboard,
  43.                         you have to convert the string to base 64
  44.             */
  45.             private const string cryptoKey = "Q3JpcHRvZ3JhZmlhcyBjb20gUmluamRhZWwgLyBBRVM=";
  46.  
  47.             //Method to encrypt the string
  48.             public static string Encrypt(string text)
  49.             {
  50.                 try
  51.                 {
  52.                     // If the string is not void (empty), execute the encryption
  53.                     if (!string.IsNullOrEmpty(text))
  54.                     {
  55.                         // Instance the array of bytes with the keys                
  56.                         byte[] bKey = Convert.FromBase64String(cryptoKey);  //Return the cryptoKey
  57.  
  58.                         //Print the value of cryptoKey char by char
  59.                         for (int i = 0; i < bKey.Length; i++)
  60.                             Console.Write((char)bKey[i]);
  61.  
  62.                         byte[] bText = new UTF8Encoding().GetBytes(text);
  63.  
  64.                         // Instance the class Rijndael (Rihndael = AES)
  65.                         Rijndael rijndael = new RijndaelManaged();
  66.  
  67.                         // Defines the keysize "256 = 8 * 32"                
  68.                         // There are other possibilities
  69.                         // 128 (16 characters), 192 (24 characters) e 256 (32 characters)                
  70.                         rijndael.KeySize = 256;
  71.  
  72.                         // Separate space in the memory to encrypt the string
  73.                         MemoryStream mStream = new MemoryStream();
  74.                         // Instance the encryptor                
  75.                         CryptoStream encryptor = new CryptoStream(
  76.                             mStream, rijndael.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write);
  77.  
  78.                         // Write the encrypted data in the memory
  79.                         encryptor.Write(bText, 0, bText.Length);
  80.                         // Clean the encryptor                
  81.                         encryptor.FlushFinalBlock();
  82.                         // Return the array of bytes (encrypted string)
  83.                         return Convert.ToBase64String(mStream.ToArray());
  84.                     }
  85.                     else
  86.                     {
  87.                         // If the string is null              
  88.                         return null;
  89.                     }
  90.                 }
  91.                 catch (Exception ex)
  92.                 {
  93.                     // If an error occurs        
  94.                     throw new ApplicationException("Erro ao criptografar", ex);
  95.                 }
  96.             }
  97.  
  98.             //Method to decrypt the string
  99.             public static string Decrypt(string text)
  100.             {
  101.                 /*      Basically it has similar implementations to the Encrypt,
  102.                  *          with few changes, therefore I will not comment
  103.                  */
  104.  
  105.                 try
  106.                 {        
  107.                     if (!string.IsNullOrEmpty(text))
  108.                     {                
  109.                         byte[] bKey = Convert.FromBase64String(cryptoKey);
  110.                         byte[] bText = Convert.FromBase64String(text);
  111.                
  112.                         Rijndael rijndael = new RijndaelManaged();
  113.                
  114.                         rijndael.KeySize = 256;
  115.                
  116.                         MemoryStream mStream = new MemoryStream();
  117.                         CryptoStream decryptor = new CryptoStream(mStream,
  118.                             rijndael.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write);
  119.  
  120.                         decryptor.Write(bText, 0, bText.Length);
  121.                         decryptor.FlushFinalBlock();
  122.                         UTF8Encoding utf8 = new UTF8Encoding();
  123.                         return utf8.GetString(mStream.ToArray());
  124.                     }
  125.                     else
  126.                     {          
  127.                         return null;
  128.                     }
  129.                 }
  130.                 catch (Exception ex)
  131.                 {          
  132.                     throw new ApplicationException("Erro ao descriptografar", ex);
  133.                 }
  134.             }
  135.         }
  136.     }
  137. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement