Advertisement
ZeekoSec

Rijndael & AES Combi encrytion

Mar 27th, 2015
478
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.83 KB | None | 0 0
  1. Public Class SimpleAes
  2.     Implements IDisposable
  3.     ''' <summary>
  4.     ''' Initialization vector length in bytes.
  5.     ''' </summary>
  6.     Private Const IvBytes As Integer = 16
  7.  
  8.     ''' <summary>
  9.     ''' Must be exactly 16, 24 or 32 characters long.
  10.     ''' </summary>
  11.     Private Shared ReadOnly Key As Byte() = Convert.FromBase64String("FILL ME WITH 16, 24 OR 32 CHARS")
  12.  
  13.     Private ReadOnly _encoder As UTF8Encoding
  14.     Private ReadOnly _encryptor As ICryptoTransform
  15.     Private ReadOnly _rijndael As RijndaelManaged
  16.  
  17.     Public Sub New()
  18.         _rijndael = New RijndaelManaged() With { _
  19.             Key .Key = Key _
  20.         }
  21.         _rijndael.GenerateIV()
  22.         _encryptor = _rijndael.CreateEncryptor()
  23.         _encoder = New UTF8Encoding()
  24.     End Sub
  25.  
  26.     Public Function Decrypt(encrypted As String) As String
  27.         Return _encoder.GetString(Decrypt(Convert.FromBase64String(encrypted)))
  28.     End Function
  29.  
  30.     Public Sub Dispose()
  31.         _rijndael.Dispose()
  32.         _encryptor.Dispose()
  33.     End Sub
  34.  
  35.     Public Function Encrypt(unencrypted As String) As String
  36.         Return Convert.ToBase64String(Encrypt(_encoder.GetBytes(unencrypted)))
  37.     End Function
  38.  
  39.     Private Function Decrypt(buffer As Byte()) As Byte()
  40.         ' IV is prepended to cryptotext
  41.         Dim iv As Byte() = buffer.Take(IvBytes).ToArray()
  42.         Using decryptor As ICryptoTransform = _rijndael.CreateDecryptor(_rijndael.Key, iv)
  43.             Return decryptor.TransformFinalBlock(buffer, IvBytes, buffer.Length - IvBytes)
  44.         End Using
  45.     End Function
  46.  
  47.     Private Function Encrypt(buffer As Byte()) As Byte()
  48.         ' Prepend cryptotext with IV
  49.         Dim inputBuffer As Byte() = _rijndael.IV.Concat(buffer).ToArray()
  50.         Return _encryptor.TransformFinalBlock(inputBuffer, IvBytes, buffer.Length)
  51.     End Function
  52. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement