VB.Net Encryption Class
-
After many hours of battling with others sample code and sifting through countless message board posts I believe I have managed to come up with a fairly functional and stable encryption and decryption class that utilises multiple encryption methods. The code is shown below and a sample call would look something like Dim Crypto As New Crypto(Crypto.Providers.DES) Dim Encrypted as string = Crypto.Encrypt("Test String", "Keystring") Dim Decrypted as string = Crypto.Decrypt(Encrypted , "Keystring") ‘Crypto class Imports System.Security.Cryptography Imports System.IO Imports System.Text 'SymmCrypto is a wrapper of System.Security.Cryptography.SymmetricAlgorithm classes 'and simplifies the interface. It supports customized SymmetricAlgorithm as well. 'Original Code from Frank Fang 'Revised by Jerome Howard to remove Bad Data errors, create seperate CryptoIV and 'use the maximum legal keysize for each encryption algorithm Public Class Crypto '256 Bit IV Key that is truncated when a smaller keys are required Private bytIV() As Byte = _ {12, 241, 10, 21, 90, 74, 11, 39, 9, 91, 45, 78, 189, 211, 133, 62, 121, 22, 101, 34, 90, 74, 121, 39, 93, 9, 45, 78, 1, 211, 33, 162} 'Supported .Net intrinsic SymmetricAlgorithm classes. Public Enum Providers DES RC2 Rijndael End Enum Private _CryptoService As SymmetricAlgorithm 'Constructor for using an intrinsic .Net SymmetricAlgorithm class. Public Sub New(ByVal NetSelected As Providers) Select Case NetSelected Case Providers.DES _CryptoService = New DESCryptoServiceProvider() Case Providers.RC2 _CryptoService = New RC2CryptoServiceProvider() Case Providers.Rijndael _CryptoService = New RijndaelManaged() End Select End Sub 'Constructor for using a customized SymmetricAlgorithm class. Public Sub New(ByVal ServiceProvider As SymmetricAlgorithm) _CryptoService = ServiceProvider End Sub 'Depending on the legal key size limitations of a specific CryptoService provider 'and length of the private key provided, padding the secret key with a character 'or triming it to meet the legal size of the algorithm. Private Function GetLegalKey(ByVal Key As String) As Byte() 'key sizes are in bits Dim sTemp As String If (_CryptoService.LegalKeySizes.Length > 0) Then Dim maxSize As Integer = _CryptoService