' 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 TestAsymmetric
        ' encrypt: Byte() plain + Byte() keys -> Byte() cipher
        ' decrypt: Byte() cipher + Byte() keys -> Byte() plain
        Public Shared Function Encrypt(plain As Byte(), keyblob As Byte()) As Byte()
            Dim alg As New RSACryptoServiceProvider()
            alg.ImportCspBlob(keyblob)
            Return alg.Encrypt(plain, False)
        End Function
        Public Shared Function Decrypt(cipher As Byte(), keyblob As Byte()) As Byte()
            Dim alg As New RSACryptoServiceProvider()
            alg.ImportCspBlob(keyblob)
            Return alg.Decrypt(cipher, False)
        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
        ' encrypt: String plain + Byte() keys -> Base64 String cipher
        ' decrypt: Base64 String cipher + Byte() keys -> String plain
        Public Shared Function Encrypt(plain As String, keyblob As Byte()) As String
            Return Encode(Encrypt(Encoding.UTF8.GetBytes(plain), keyblob))
        End Function
        Public Shared Function Decrypt(cipher As String, keyblob As Byte()) As String
            Return Encoding.UTF8.GetString(Decrypt(Decode(cipher), keyblob))
        End Function
        Private Const TEXT As String = "This is some random text to be used to test encryption."
        Private Shared Sub Test(label As String, bits As Integer)
            Console.WriteLine(label & ":")
            ' generate keys
            Dim alg As New RSACryptoServiceProvider() With { _
                .KeySize = bits _
            }
            Dim keyblob As Byte() = alg.ExportCspBlob(True)
            ' real test
            Console.WriteLine("  " & TEXT)
            Dim cipher As String = Encrypt(TEXT, keyblob)
            Console.WriteLine("  " & cipher)
            Dim plain As String = Decrypt(cipher, keyblob)
            Console.WriteLine("  " & plain)
        End Sub
        Public Shared Sub Main(args As String())
            ' CAPI implementations
            Test("RSA 2048 bit (CAPI)", 2048)
            Test("RSA 3072 bit (CAPI)", 3072)
        End Sub
    End Class
End Namespace
