' Collection of code snippets by Arne Vajhøj 
' (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
﻿Imports System
Imports System.Security.Cryptography
Imports System.Text

Namespace Encrypt
    Public Class TestSymmetric
        ' generate random IV
        Private Shared rng As RandomNumberGenerator = RandomNumberGenerator.Create()
        Private Shared Function GenIV(size As Integer) As Byte()
            Dim res As Byte() = New Byte(size - 1) {}
            rng.GetBytes(res)
            Return res
        End Function
        ' encrypt: Byte() plain + Byte() key -> Byte() cipher
        ' decrypt: Byte() cipher + Byte() key -> Byte() plain
        Public Shared Function Encrypt(alg As SymmetricAlgorithm, blksize As Integer, plain As Byte(), key As Byte()) As Byte()
            Dim iv As Byte() = GenIV(blksize)
            Dim encrypt__1 As ICryptoTransform = alg.CreateEncryptor(key, iv)
            Dim temp As Byte() = encrypt__1.TransformFinalBlock(plain, 0, plain.Length)
            Dim res As Byte() = New Byte(iv.Length + (temp.Length - 1)) {}
            Array.Copy(iv, 0, res, 0, iv.Length)
            Array.Copy(temp, 0, res, iv.Length, temp.Length)
            Return res
        End Function
        Public Shared Function Decrypt(alg As SymmetricAlgorithm, blksize As Integer, cipher As Byte(), key As Byte()) As Byte()
            Dim iv As Byte() = New Byte(blksize - 1) {}
            Array.Copy(cipher, 0, iv, 0, iv.Length)
            Dim temp As Byte() = New Byte(cipher.Length - iv.Length - 1) {}
            Array.Copy(cipher, iv.Length, temp, 0, temp.Length)
            Dim decrypt__1 As ICryptoTransform = alg.CreateDecryptor(key, iv)
            Return decrypt__1.TransformFinalBlock(temp, 0, temp.Length)
        End Function
        ' Base64 encode: Byte() -> String
        ' Base64 decode: String -> Byte()
        Private Shared Function Encode(b As Byte()) As String
            Return Convert.ToBase64String(b)
        End Function
        Private Shared Function Decode(s As String) As Byte()
            Return Convert.FromBase64String(s)
        End Function
        ' convert String key to Byte() key
        Private Shared Function GenKey(key As String, keysize As Integer) As Byte()
            Dim ha As HashAlgorithm = New SHA256Managed()
            Dim hash As Byte() = ha.ComputeHash(Encoding.UTF8.GetBytes(key))
            Dim res As Byte() = New [Byte](keysize - 1) {}
            Array.Copy(hash, 0, res, 0, keysize)
            Return res
        End Function
        ' encrypt: String plain + String key -> Base64 String cipher
        ' decrypt: Base64 String cipher + String key -> String plain
        Public Shared Function Encrypt(alg As SymmetricAlgorithm, blksize As Integer, plain As String, key As String, keysize As Integer) As String
            Return Encode(Encrypt(alg, blksize, Encoding.UTF8.GetBytes(plain), GenKey(key, keysize)))
        End Function
        Public Shared Function Decrypt(alg As SymmetricAlgorithm, blksize As Integer, cipher As String, key As String, keysize As Integer) As String
            Return Encoding.UTF8.GetString(Decrypt(alg, blksize, Decode(cipher), GenKey(key, keysize)))
        End Function
        ' test
        Private Const TEXT As String = "This is some random text to be used to test encryption."
        Private Const KEY As String = "This is a very long and super secret key that should really be like 4 times as long as keysize"
        Private Shared Sub Test(label As String, alg As SymmetricAlgorithm, keysize As Integer, blksize As Integer)
            Console.WriteLine(label & ":")
            Console.WriteLine("  " & TEXT)
            Dim cipher As String = Encrypt(alg, blksize, TEXT, KEY, keysize)
            Console.WriteLine("  " & cipher)
            Dim plain As String = Decrypt(alg, blksize, cipher, KEY, keysize)
            Console.WriteLine("  " & plain)
        End Sub
        Private Shared Sub Test2()
            If Decrypt(New AesManaged() With { _
                .Mode = CipherMode.CBC, _
                .Padding = PaddingMode.PKCS7 _
            }, 16, "Xc252As4sZuj12tLJtDk2l60tHxu1hk4FTB0l9IK/q96cWd+Uop4lXcId1hGEmm0SN1Xjua4YqVlr3rvT+Mw4hStrnz3h8TEfdENfUMqLMY=", KEY, 16) <> TEXT Then
                Throw New Exception("Ooops")
            End If
        End Sub
        Public Shared Sub Main(args As String())
            ' managed implementations
            Test("AES 128 bit (managed)", New AesManaged() With { _
                .Mode = CipherMode.CBC, _
                .Padding = PaddingMode.PKCS7 _
            }, 16, 16)
            Test("AES 192 bit (managed)", New AesManaged() With { _
                .Mode = CipherMode.CBC, _
                .Padding = PaddingMode.PKCS7 _
            }, 24, 16)
            Test("AES 256 bit (managed)", New AesManaged() With { _
                .Mode = CipherMode.CBC, _
                .Padding = PaddingMode.PKCS7 _
            }, 32, 16)
            ' CAPI implementations
            Test("AES 128 bit (CAPI)", New AesCryptoServiceProvider() With { _
                .Mode = CipherMode.CBC, _
                .Padding = PaddingMode.PKCS7 _
            }, 16, 16)
            Test("AES 192 bit (CAPI)", New AesCryptoServiceProvider() With { _
                .Mode = CipherMode.CBC, _
                .Padding = PaddingMode.PKCS7 _
            }, 24, 16)
            Test("AES 256 bit (CAPI)", New AesCryptoServiceProvider() With { _
                .Mode = CipherMode.CBC, _
                .Padding = PaddingMode.PKCS7 _
            }, 32, 16)
            Test("3DES 168 bit (CAPI)", New TripleDESCryptoServiceProvider() With { _
                .Mode = CipherMode.CBC, _
                .Padding = PaddingMode.PKCS7 _
            }, 24, 8)
            '
            Test2()
        End Sub
    End Class
End Namespace
