RosettaCodeData/Task/Bifid-cipher/FreeBASIC/bifid-cipher.basic

82 lines
2.1 KiB
Plaintext

Dim Shared As String encrypted, decrypted
Sub BifidEncode(Byref polybius As String, Byref mensaje As String)
Dim As String filas, columas
Dim As Integer c, i, j, k, longi
encrypted = Ucase(mensaje)
For i = 1 To Len(encrypted)
If Mid(encrypted, i, 1) = Chr(10) Then Mid(encrypted, i, 1) = Chr(9)
Next i
i = 0 : j = 0
While i < Len(encrypted)
c = Asc(Mid(encrypted, i + 1, 1))
i += 1
k = Instr(polybius, Chr(c)) - 1
If k >= 0 Then
filas &= Chr(k \ 5 + Asc("0"))
columas &= Chr(k Mod 5 + Asc("0"))
j += 1
End If
Wend
longi = j
filas &= columas
encrypted = ""
For i = 0 To longi - 1
k = (Asc(Mid(filas, i * 2 + 1, 1)) - Asc("0")) * 5 + (Asc(Mid(filas, i * 2 + 2, 1)) - Asc("0"))
encrypted &= Mid(polybius, k + 1, 1)
Next i
End Sub
Sub BifidDecode(Byref polybius As String, Byref mensaje As String)
Dim As String filas, columas
Dim As Integer c, k, i, j, longi
i = 0 : j = 0
While i < Len(mensaje)
c = Asc(Mid(mensaje, i + 1, 1))
i += 1
k = Instr(polybius, Chr(c)) - 1
filas &= Chr(k \ 5 + Asc("0"))
filas &= Chr(k Mod 5 + Asc("0"))
j += 2
Wend
longi = i
columas = Right(filas, longi)
filas = Left(filas, longi)
decrypted = ""
For i = 0 To longi - 1
k = (Asc(Mid(filas, i + 1, 1)) - Asc("0")) * 5 + (Asc(Mid(columas, i + 1, 1)) - Asc("0"))
decrypted &= Mid(polybius, k + 1, 1)
Next i
End Sub
Dim As String polys(3), msgs(3)
polys(0) = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
polys(1) = "BGWKZQPNDSIOAXEFCLUMTHYVR"
polys(2) = "BGWKZQPNDSIOAXEFCLUMTHYVR"
polys(3) = "PLAYFIREXMBCDGHKNOQSTUVWZ"
msgs(0) = "ATTACKATDAWN"
msgs(1) = "FLEEATONCE"
msgs(2) = "ATTACKATDAWN"
msgs(3) = "The invasion will start on the first of January"
For i As Integer = 0 To Ubound(msgs)
BifidEncode(polys(i), msgs(i))
BifidDecode(polys(i), encrypted)
Print "Mensaje : "; msgs(i)
Print "Encrypted : "; encrypted
Print "Decrypted : "; decrypted
If i < Ubound(msgs) Then Print
Next i
Sleep