caesar.bas

Attribute VB_Name = "caesar_main"
Option Explicit


Dim s_ascii() As Variant
Dim b_ascii() As Variant

Sub main()

s_ascii = Array(97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122)
b_ascii = Array(65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90)

Call caesar_crypt("plain_text.txt", "encoded_text.txt", 3)
Call caesar_decrypt("encoded_text.txt", "new_plain_text.txt", 3)

End Sub
Function caesar_crypt(source As String, target As String, k As Integer)
    Dim ff As Integer, i As Integer
    Dim tmp1 As String, tmp2 As String
    ff = FreeFile
    Open source For Input As #ff
    Do While Not EOF(ff)
        Line Input #ff, tmp1
        For i = 1 To Len(tmp1)
            tmp2 = tmp2 + caesar_char_crypt(Mid(tmp1, i, 1), k)
        Next i
        tmp2 = tmp2 & vbCrLf
    Loop
    Close #ff
    
    ff = FreeFile
    
    Open target For Output As #ff
    Print #ff, tmp2
    Close #ff
End Function
Function caesar_decrypt(source As String, target As String, k As Integer)
    Dim ff As Integer, i As Integer
    Dim tmp1 As String, tmp2 As String
    Dim x As Integer
    ff = FreeFile
    Open source For Input As #ff
    Do While Not EOF(ff)
        Line Input #ff, tmp1
        For i = 1 To Len(tmp1)
            tmp2 = tmp2 + caesar_char_decrypt(Mid(tmp1, i, 1), k)
        Next i
        tmp2 = tmp2 & vbCrLf
    Loop
    Close #ff
    
    ff = FreeFile
    
    Open target For Output As #ff
    Print #ff, tmp2
    Close #ff
End Function
Function caesar_char_crypt(char, k) As String
    Dim i As Integer
    Dim temp As String
    
    For i = 0 To 25
        If s_ascii(i) = Asc(char) Then temp = s_ascii(n_mod((i + k), 25)): Exit For
        If b_ascii(i) = Asc(char) Then temp = b_ascii(n_mod((i + k), 25)): Exit For
    Next i
    
    If Not temp = "" Then
        caesar_char_crypt = Chr(temp)
    Else
        caesar_char_crypt = char
    End If
End Function
Function caesar_char_decrypt(char, k) As String
    Dim i As Integer
    Dim temp As String
    
    For i = 0 To 25
        If s_ascii(i) = Asc(char) Then temp = s_ascii(n_mod((i - k), 25)): Exit For
        If b_ascii(i) = Asc(char) Then temp = b_ascii(n_mod((i - k), 25)): Exit For
    Next i
       
    If Not temp = "" Then
        caesar_char_decrypt = Chr(temp)
    Else
        caesar_char_decrypt = char
    End If
End Function
Function n_mod(p1 As Integer, p2 As Integer) As Integer
    Dim tmp As Integer
    tmp = p1 Mod p2
    If tmp < 0 Then
        n_mod = p2 + tmp
    Else
        n_mod = tmp
    End If
End Function