Cryptografie en het Vernam Cipher.

Nog een voorbeeld van het Vernam Cipher. Dat is een crypto algoritme waarmee je tekst kunt versleutel en ontsleutelen (encryption en decryption) d.m.v. een geheime Key/Sleutel. Dat kan met de code die hieronder staat.
Je hoeft geen tekst of Key in te voeren want die staat al in de code. Mag jezelf veranderen. Je moet wel opletten dat de tekst en de Key dezelfde lengte hebben. Hier een voorbeeld. In de code staat trouwens een andere tekst en Key.

Kopieer de onderstaande code middels Ctrl + C
Druk op de toetscombinatie ALT + F11 om de Visual Basic Editor te openen
Druk op de toetscombinatie ALT + N om het menu Invoegen te openen
Druk op M om een standaard module in te voegen
Daar waar de cursor knippert voeg je de code in middels Ctrl + V
Druk op de toetscombinatie ALT + Q om de Editor af te sluiten en terug te keren naar Excel
Druk op de toetscombinatie ALT + F8 om de Macro Dialoog te tonen. Dubbelklik op de macro naam XorUsage om te starten.

Option Explicit
    ' This Vernam Cipher uses the bitwise XOR operation
    ' Purpose: Encrypt and decrypt a message using the Vernam cipher with given plaintext and key, preserving spaces.
    ' Plaintext and Key(Pwd) have to be the same length
    ' Input: Plaintext and Key(Pwd) are already hardcoded in code below. Adjust if you want
    ' Output: Ciphertext in cell A2, Decrypted text in cell A3, TRUE or FALSE in cell A4.

Sub XorUsage()
    ' This Vernam Cipher uses the bitwise XOR operation
    Dim Pwd As String
    
    ' Put into A1 the text to be encrypted /decrypted
    [A1:A5].ClearContents
    
    'Plaintext and Key(Pwd) are already hardcoded in code below. Adjust if you want
    [A1].Value = UCase("DE QUERULANT BEKLAAGDE ZICH OPNIEUW OVER MIJN XYLOFOONSPEL") ' Convert to uppercase
    ' Set the password
    Pwd = UCase("UNCOPYRIGHTABLEUNCOPYRIGHTABLEUNCOPYRIGHTABLEUNCOPYRIGHTAB")   ' Convert to uppercase
    [A2].Value = Pwd
    
    If Len(Pwd) = 0 Then Exit Sub
    
    ' Put encrtypded A1 to A2
    [A4].Value = StrXor([A1].Value, Pwd)
    
    ' Put Decrypted A2 to A3
    [A5].Value = StrXor([A4].Value, Pwd)
    
    ' Compare Decrypted A3 with Original A1
    [A6].Formula = "=A1=A5"
End Sub
 
 
Function StrXor(Txt As String, Pwd As String) As String
    Dim a As Integer, b As Integer, c As Integer, i As Long, j As Long
    For i = 1 To Len(Txt)
        j = j + 1
        If j > Len(Pwd) Then j = 1
            a = Asc(Mid(Txt, i))
            If a <> 32 Then
                b = Asc(Mid(Pwd, j))
                c = a Xor b   ' <-- Encription/Decription
                c = c Xor 255 ' <-- This excludes Chr(0)
            Else
                c = 32
            End If
        StrXor = StrXor & Chr(c)
    Next
End Function

Leave a Reply

Your email address will not be published. Required fields are marked *