-
ตัวอย่างโค้ดการถอดรหัส(Decrypt) แบบ Columnar
Transposition Cipher
Function Decrypt(ByVal
CipherText As String, ByVal Key As String) As String
'หาจำนวนคอลัมน์
Dim
ColumnNum As Byte = Key.Length 'หาจำนวน
cell ว่าง
Dim EmptyNum As Byte
Dim CharTotal As Byte
= CipherText.Length
Dim Fraction As Byte =
CharTotal Mod ColumnNum
EmptyNum = IIf(Fraction
= 0, 0, ColumnNum - Fraction)
'หาจำนวนแถว
Dim RowNum As Byte = CipherText.Length
\ Key.Length
If (CipherText.Length
Mod Key.Length) > 0 Then RowNum += 1
Dim
CharMatrix(RowNum - 1, ColumnNum - 1) As Char
Dim CharArray(CharMatrix.Length
- 1) As Char
'นำตัวอักษรใน
CipherText มาเรียงในเมตริกซ์ (Array 2 มิติ)
'เรียงจากบนลงล่าง ทีละคอลัมน์
Dim Count As Byte = 0
For
CountCol As Byte = 1 To Key.Length
'หา
column index ตามลำดับก่อนหลัง เก็บไว้ที่ตัวแปร ColumnOrder
Dim
ColumnOrder As Byte
For
ColumnOrder = 0 To Key.Length - 1
Dim
Num As Byte = CByte(Key(ColumnOrder).ToString)
If
CountCol = Num Then Exit For
Next
ColumnOrder
'คอมลัมน์ที่ไม่มีช่องว่าง
If ColumnOrder <= (Key.Length
- 1 - EmptyNum) Then
For CountRow As Byte =
0 To RowNum - 1
CharMatrix(CountRow,
ColumnOrder) = CipherText(Count)
Count
+= 1
Next CountRow
Else 'คอมลัมน์ที่มีช่องว่าง
(Nothing)
For CountRow As Byte =
0 To RowNum - 2
CharMatrix(CountRow,
ColumnOrder) = CipherText(Count)
Count
+= 1
Next CountRow
End If
Next
CountCol
'อ่านตัวอักษรในเมตริกซ์
จากซ้ายไปขวา ทีละแถว
'มาเรียงเป็นข้อความแถวเดียว
Count = 0
For CountRow As Byte =
0 To RowNum - 1
For
CountCol As Byte = 0 To ColumnNum - 1
If
Count <= CipherText.Length - 1 Then
CharArray(Count)
= CharMatrix(CountRow, CountCol)
Count
+= 1
End
If
Next
CountCol
Next CountRow
'ส่งค่าตัวอักษรที่เป็น
array กลับเป็น string
Return CharArray
End Function
|