Bifid cipher: Difference between revisions

m
m (Correcting mistake in formatting.)
 
(28 intermediate revisions by 12 users not shown)
Line 204:
A 6 x 6 square allows all 36 letters & digits to be encoded:
The invasion will start on the 1st of January --> TTFAEWUAU9WTE3WP1S5KDF0B8M9AH7KHHVLAV --> THEINVASIONWILLSTARTONTHE1STOFJANUARY"</syntaxhighlight>
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="basic"> 100 A$ = "ATTACKATDAWN": GOSUB 160"REPORT
110 K$ = "BGWKZQPNDSIOAXEFCLUMTHYVR"
120 A$ = "FLEEATONCE": GOSUB 160"REPORT
130 K$ = " .'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123"
140 A$ = "THE INVASION WILL START ON THE FIRST OF JANUARY 2023.": GOSUB 160"REPORT
150 END
 
REM REPORT
160 GOSUB 200"ENCRYPT
165 PRINT M$M$"FOR "W" X "W" POLYBIUS:":M$ = CHR$ (13): FOR I = 1 TO W: PRINT , MID$ (K$,(I - 1) * W + 1,W): NEXT
170 PRINT "ENCRYPTED: "E$
180 GOSUB 300"DECRYPT
190 PRINT "DECRYPTED: "U$;: RETURN
 
REM ENCRYPT A$ RETURNS E$
200 GOSUB 400:L = LEN (A$):E$ = "":U$ = "": IF NOT L THEN RETURN
210 FOR I = 1 TO L
220 C = ASC ( MID$ (A$,I,1)): IF X(C) AND Y(C) THEN U$ = U$ + CHR$ (C)
230 NEXT I
240 L = LEN (U$): IF NOT L THEN RETURN
250 FOR I = 1 TO L:C = ASC ( MID$ (U$,I,1)):A(I) = X(C):A(I + L) = Y(C): NEXT I
260 FOR I = 1 TO L * 2 STEP 2:E$ = E$ + MID$ (K$,(A(I) - 1) * W + A(I + 1),1): NEXT I
270 RETURN
 
REM DECRYPT E$ RETURNS U$
300 GOSUB 400:L = LEN (E$):U$ = "": IF NOT L THEN RETURN
310 FOR I = 1 TO L:C = ASC ( MID$ (E$,I)):B(I * 2 - 1) = X(C):B(I * 2) = Y(C): NEXT I
320 FOR I = 1 TO L:U$ = U$ + MID$ (K$,(B(I) - 1) * W + B(L + I),1): NEXT I
330 RETURN
 
REM POLYBIUS K$ RETURNS X(255),Y(255)
400 IF K$ = P$ AND LEN (K$) THEN RETURN
410 IF XY THEN FOR I = 0 TO 255:X(I) = 0:Y(I) = 0: NEXT I
420 IF NOT XY THEN DIM X(255),Y(255),A(512),B(512):XY = 1
430 IF K$ = "" THEN FOR I = 1 TO 25:K$ = K$ + CHR$ (I + 64 + (I > 9)): NEXT I
440 L = LEN (K$):W = INT ( SQR (L - 1) + 1):I = 1:N = 1:K = ASC ("0")
450 FOR X = 1 TO W
460 FOR Y = 1 TO W
470 C$ = MID$ (K$,I,1): IF C$ = "" THEN FOR C = K TO 255: IF X(C) THEN NEXT C: STOP
480 IF C$ = "" THEN C$ = CHR$ (C):K$ = K$ + C$:K = C + 1
490 C = ASC (C$):Y(C) = Y:X(C) = X:I = I + 1: IF C$ = "J" THEN N = 0
500 NEXT Y,X
510 IF N THEN Y( ASC ("J")) = Y( ASC ("I")):X( ASC ("J")) = X( ASC ("I"))
520 P$ = K$
530 RETURN</syntaxhighlight>
{{out}}
<pre>FOR 5 X 5 POLYBIUS:
ABCDE
FGHIK
LMNOP
QRSTU
VWXYZ
ENCRYPTED: DQBDAXDQPDQH
DECRYPTED: ATTACKATDAWN
 
FOR 5 X 5 POLYBIUS:
BGWKZ
QPNDS
IOAXE
FCLUM
THYVR
ENCRYPTED: UAEOLWRINS
DECRYPTED: FLEEATONCE
 
FOR 6 X 6 POLYBIUS:
.'ABC
DEFGHI
JKLMNO
PQRSTU
VWXYZ0
123456
ENCRYPTED: QDFVQLBFJSAPLAE.GS'DJMAV56BWCVS6VILAYNCVZDOMV3 T4M.2K
DECRYPTED: THE INVASION WILL START ON THE FIRST OF JANUARY 2023.
</pre>
 
=={{header|C#}}==
{{trans|Java}}
<syntaxhighlight lang="C#">
using System;
using System.Collections.Generic;
using System.Drawing;
 
public class BifidCipher
{
public static void Main(string[] args)
{
string message1 = "ATTACKATDAWN";
string message2 = "FLEEATONCE";
string message3 = "The invasion will start on the first of January".ToUpper().Replace(" ", "");
 
Bifid bifid1 = new Bifid(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ");
Bifid bifid2 = new Bifid(5, "BGWKZQPNDSIOAXEFCLUMTHYVR");
 
RunTest(bifid1, message1);
RunTest(bifid2, message2);
RunTest(bifid2, message1);
RunTest(bifid1, message2);
 
Bifid bifid3 = new Bifid(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
RunTest(bifid3, message3);
}
 
private static void RunTest(Bifid bifid, string message)
{
Console.WriteLine("Using Polybius square:");
bifid.Display();
Console.WriteLine("Message: " + message);
string encrypted = bifid.Encrypt(message);
Console.WriteLine("Encrypted: " + encrypted);
string decrypted = bifid.Decrypt(encrypted);
Console.WriteLine("Decrypted: " + decrypted);
Console.WriteLine();
}
}
 
public class Bifid
{
private char[,] grid;
private Dictionary<char, Point> coordinates = new Dictionary<char, Point>();
 
public Bifid(int n, string text)
{
if (text.Length != n * n)
{
throw new ArgumentException("Incorrect length of text");
}
 
grid = new char[n, n];
int row = 0;
int col = 0;
 
foreach (char ch in text)
{
grid[row, col] = ch;
coordinates[ch] = new Point(row, col);
col += 1;
if (col == n)
{
col = 0;
row += 1;
}
}
 
if (n == 5)
{
coordinates['J'] = coordinates['I'];
}
}
 
public string Encrypt(string text)
{
List<int> rowOne = new List<int>();
List<int> rowTwo = new List<int>();
 
foreach (char ch in text)
{
Point coordinate = coordinates[ch];
rowOne.Add(coordinate.X);
rowTwo.Add(coordinate.Y);
}
 
rowOne.AddRange(rowTwo);
var result = new System.Text.StringBuilder();
 
for (int i = 0; i < rowOne.Count - 1; i += 2)
{
result.Append(grid[rowOne[i], rowOne[i + 1]]);
}
 
return result.ToString();
}
 
public string Decrypt(string text)
{
List<int> row = new List<int>();
 
foreach (char ch in text)
{
Point coordinate = coordinates[ch];
row.Add(coordinate.X);
row.Add(coordinate.Y);
}
 
int middle = row.Count / 2;
List<int> rowOne = row.GetRange(0, middle);
List<int> rowTwo = row.GetRange(middle, row.Count - middle);
var result = new System.Text.StringBuilder();
 
for (int i = 0; i < middle; i++)
{
result.Append(grid[rowOne[i], rowTwo[i]]);
}
 
return result.ToString();
}
 
public void Display()
{
for (int i = 0; i < grid.GetLength(0); i++)
{
for (int j = 0; j < grid.GetLength(1); j++)
{
Console.Write(grid[i, j] + " ");
}
Console.WriteLine();
}
}
}
</syntaxhighlight>
{{out}}
<pre>
Using Polybius square:
A B C D E
F G H I K
L M N O P
Q R S T U
V W X Y Z
Message: ATTACKATDAWN
Encrypted: DQBDAXDQPDQH
Decrypted: ATTACKATDAWN
 
Using Polybius square:
B G W K Z
Q P N D S
I O A X E
F C L U M
T H Y V R
Message: FLEEATONCE
Encrypted: UAEOLWRINS
Decrypted: FLEEATONCE
 
Using Polybius square:
B G W K Z
Q P N D S
I O A X E
F C L U M
T H Y V R
Message: ATTACKATDAWN
Encrypted: EYFENGIWDILA
Decrypted: ATTACKATDAWN
 
Using Polybius square:
A B C D E
F G H I K
L M N O P
Q R S T U
V W X Y Z
Message: FLEEATONCE
Encrypted: HADNAAZDSP
Decrypted: FLEEATONCE
 
Using Polybius square:
A B C D E F
G H I J K L
M N O P Q R
S T U V W X
Y Z 0 1 2 3
4 5 6 7 8 9
Message: THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY
Encrypted: TBPDIPHJSPOTAIVMGPCZKNSCN09BFIHK64I7BM4
Decrypted: THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY
 
 
</pre>
 
=={{header|C++}}==
<syntaxhighlight landlang="javac++">
 
#include <cstdint>
#include <iostream>
#include <stdexcept>
#include <stringstring_view>
#include <unordered_map>
#include <vector>
Line 218 ⟶ 485:
class Bifid {
public:
Bifid(const int32_t& n, const std::string&string_view text) {
if ( text.length() != n * n ) {
throw new std::invalid_argument("Incorrect length of text");
}
 
Line 230 ⟶ 497:
int32_t row = 0;
int32_t col = 0;
for ( const char& ch : text ) {
grid[row][col] = ch;
coordinates[ch] = point(row, col);
Line 245 ⟶ 512:
}
 
std::string encrypt(const std::string&string_view text) {
std::vector<int32_t> row_one, row_two;
for ( const char& ch : text ) {
point coordinate = coordinates[ch];
row_one.push_back(coordinate.first);
Line 261 ⟶ 528:
}
 
std::string decrypt(const std::string&string_view text) {
std::vector<int32_t> row;
for ( const char& ch : text ) {
point coordinate = coordinates[ch];
row.push_back(coordinate.first);
Line 280 ⟶ 547:
 
void display() const {
for ( const std::vector<char>& row : grid ) {
for ( const char& ch : row ) {
std::cout << ch << " ";
}
Line 292 ⟶ 559:
};
 
void runTest(Bifid& bifid, std::stringstring_view message) {
std::cout << "Using Polybius square:" << std::endl;
bifid.display();
Line 304 ⟶ 571:
 
int main() {
const std::stringstring_view message1 = "ATTACKATDAWN";
const std::stringstring_view message2 = "FLEEATONCE";
const std::stringstring_view message3 = "THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY";
 
Bifid bifid1(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ");
Line 372 ⟶ 639:
Encrypted: TBPDIPHJSPOTAIVMGPCZKNSCN09BFIHK64I7BM4
Decrypted: THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY
</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func$ crypt enc msg$ key$ .
n = len msg$
for i to len msg$
c$ = substr msg$ i 1
j = strpos key$ c$ - 1
h[] &= j div 5
h[] &= j mod 5
.
if enc = 1
for i = 1 step 4 to 2 * n - 3
j = h[i] * 5 + h[i + 2] + 1
r$ &= substr key$ j 1
.
for i = 2 step 4 to 2 * n - 2
j = h[i] * 5 + h[i + 2] + 1
r$ &= substr key$ j 1
.
else
for i = 1 to n
j = h[i] * 5 + h[i + n] + 1
r$ &= substr key$ j 1
.
.
return r$
.
func$ conv s$ .
for e$ in strchars s$
h = strcode e$
if h >= 97
h -= 32
.
if h >= 65 and h <= 91
if h = 74
h = 73
.
r$ &= strchar h
.
.
return r$
.
func$ encr msg$ key$ .
return crypt 1 conv msg$ key$
.
func$ decr msg$ key$ .
return crypt 0 msg$ key$
.
key$ = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
h$ = encr "ATTACKATDAWN" key$
print h$
print decr h$ key$
print ""
#
key$ = "BGWKZQPNDSIOAXEFCLUMTHYVR"
h$ = encr "FLEEATONCE" key$
print h$
print decr h$ key$
print ""
h$ = encr "ATTACKATDAWN" key$
print h$
print decr h$ key$
print ""
#
h$ = encr "The invasion will start on the first of January" key$
print h$
print decr h$ key$
</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
clear local fn recode( t as CFStringRef, code as CFStringRef ) as CFStringRef
CFStringRef s = @""
Short i, k, w = sqr( len( code ) )
for i = 0 to len( t ) - 1 step 2
k = intval( mid( t, i, 2 ) ) // Get ‘coordinates’ of char in code string
k = w * ( k / 10 ) + k mod 10
s = fn StringByAppendingString( s, mid( code, k, 1 ) )
next
end fn = s
 
//
 
clear local fn encode( s as CFStringRef, code as CFStringRef ) as CFStringRef
CFStringRef a = @"", b = @"", c
Short i, k, w = sqr( len( code ) )
if w == 5 then s = fn StringByReplacingOccurrencesOfString( s, @"J", @"I" )
print s
for i = 0 to len( s ) - 1
c = mid( s, i, 1 )
k = instr( 0, code, c ) // Put row in one string, column in the other
a = fn StringByAppendingString( a, fn StringWithFormat( @"%d", k / w ) )
b = fn StringByAppendingString( b, fn StringWithFormat( @"%d", k mod w ) )
next
a = fn StringByAppendingString( a, b ) // Combine the two strings, and recode
end fn = fn recode( a, code )
 
//
 
clear local fn decode( s as CFStringRef, code as CFStringRef ) as CFStringRef
CFStringRef a = @"", b = @"", c
Short i, k, w = sqr( len( code ) )
for i = 0 to ( len( s ) - 1 )
c = mid( s, i, 1 )
k = instr( 0, code, c ) // Put row and columm in one long string
a = fn StringByAppendingString( a, fn StringWithFormat( @"%d%d", k / w, k mod w ) )
next
for i = 0 to len( a ) / 2 - 1 // Take row from first half of string, column from second
c = fn StringByAppendingString( mid( a, i, 1 ), mid( a, i + len( a ) / 2 , 1 ) )
b = fn StringByAppendingString( b , c ) // Combine, and recode
next
end fn = fn recode( b, code )
 
//
 
print fn encode( @"ATTACKATDAWN", @"ABCDEFGHIKLMNOPQRSTUVWXYZ" )
print fn decode( @"DQBDAXDQPDQH", @"ABCDEFGHIKLMNOPQRSTUVWXYZ" )
print
print fn encode( @"FLEEATONCE", @"BGWKZQPDNSIOAXEFCLUMTHYVR" )
print fn decode( @"UAEOLWRINS", @"BGWKZQPDNSIOAXEFCLUMTHYVR" )
print
print fn encode( @"HAPPY40THDAD", @"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" )
print fn decode( @"GO31GAGVANJD", @"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" )
 
handleevents
</syntaxhighlight>
{{ out }}
<pre>
ATTACKATDAWN
DQBDAXDQPDQH
ATTACKATDAWN
 
FLEEATONCE
UAEOLWRINS
FLEEATONCE
 
HAPPY40THDAD
GO31GAGVANJD
HAPPY40THDAD
</pre>
 
Line 573 ⟶ 989:
Decrypted: THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY
</pre>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq.'''
 
'''Preliminaries'''
<syntaxhighlight lang="jq">
# _nwise is for gojq
def _nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
 
# Input: a string
# Output: a stream of strings
def chars: explode[] | [.] | implode;
</syntaxhighlight>
'''Bifid'''
<syntaxhighlight lang="jq">
# Input: the message to be encrypted
def encrypt($polybius):
(ascii_upcase | gsub("J"; "I") ) as $m
| {rows: [], cols : [] }
| reduce ($m|chars) as $c (.;
($polybius|index($c)) as $ix
| if $ix
then .rows += [($ix/5)|floor + 1]
| .cols += [($ix%5) + 1]
else .
end )
| reduce (.rows + .cols | _nwise(2)) as $pair ("";
(($pair[0] - 1) * 5 + $pair[1] - 1) as $ix
| . + $polybius[$ix:$ix+1] ) ;
 
# Input: the message to be decrypted
def decrypt($polybius):
reduce chars as $c ( {rows: [], cols : [] };
($polybius|index($c)) as $ix
| .rows += [($ix/5)|floor + 1]
| .cols += [($ix%5) + 1] )
| ([.rows, .cols] | transpose | flatten) as $lines
| ($lines|length/2) as $count
| $lines[:$count] as $rows
| $lines[$count:] as $cols
| [$rows, $cols] as $d
| reduce range(0; $count) as $i ("";
(($rows[$i] - 1) * 5 + $cols[$i] - 1) as $ix
| . + $polybius[$ix:$ix+1] ) ;
 
def polys:
def p1: "ABCDEFGHIKLMNOPQRSTUVWXYZ";
def p2: "BGWKZQPNDSIOAXEFCLUMTHYVR";
def p3: "PLAYFIREXMBCDGHKNOQSTUVWZ";
[p1, p2, p2, p3];
 
def messages: [
"ATTACKATDAWN",
"FLEEATONCE",
"ATTACKATDAWN",
"The invasion will start on the first of January"
];
 
def task:
range(0; messages|length) as $i
| messages[$i]
| encrypt(polys[$i]) as $encrypted
| ($encrypted | decrypt(polys[$i] )) as $decrypted
| "Message : \(.)",
"Encrypted : \($encrypted)",
"Decrypted : \($decrypted)"
"" ;
 
task
</syntaxhighlight>
{{output}}
Same as for [[#Wren]].
 
=={{header|Julia}}==
Line 645 ⟶ 1,137:
 
</pre>
 
=={{header|Kotlin}}==
 
<syntaxhighlight lang="kotlin">
import kotlin.math.sqrt
 
data class Square(private val square: String) {
private val dim: Int =
sqrt(square.length.toDouble()).toInt()
fun encode(ch: Char): Pair<Int, Int> =
square.indexOf(ch).let { idx -> Pair(idx / dim, idx.mod(dim)) }
fun decode(pair: List<Int>): Char =
square[pair[0] * dim + pair[1]]
fun decode(row: Int, col: Int): Char =
square[row * dim + col]
}
 
class Bifid(private val square: Square) {
fun encrypt(str: String): String {
fun expandAndScatter(str: String): IntArray {
val buffer = IntArray(str.length * 2)
str.forEachIndexed { i, ch ->
with(square.encode(ch)) {
buffer[i] = first
buffer[str.length + i] = second
}
}
return buffer
}
 
val buffer = expandAndScatter(str)
 
val characters: List<Char> = buffer.asIterable()
.windowed(size = 2, step = 2)
.map { square.decode(it) }
 
return String(characters.toCharArray())
}
 
fun decrypt(str: String): String {
fun expand(str: String): IntArray {
val buffer = IntArray(str.length * 2)
for (i in buffer.indices step 2) {
with(square.encode(str[i / 2])) {
buffer[i] = first
buffer[1 + i] = second
}
}
return buffer
}
 
val buffer = expand(str)
 
val characters = str.toCharArray()
for (i in characters.indices) {
characters[i] = square.decode(buffer[i], buffer[characters.size + i])
}
return String(characters)
}
}
 
fun main() {
with (Bifid(Square("ABCDEFGHIKLMNOPQRSTUVWXYZ"))) {
println("\n### ABC... 5x5")
encrypt("ATTACKATDAWN").also { println("ATTACKATDAWN -> $it") }
decrypt("DQBDAXDQPDQH").also { println("DQBDAXDQPDQH -> $it") }
}
with(Bifid(Square("BGWKZQPNDSIOAXEFCLUMTHYVR"))) {
println("\n### BGW... 5x5")
encrypt("FLEEATONCE").also { println("FLEEATONCE -> $it") }
decrypt("UAEOLWRINS").also { println("UAEOLWRINS -> $it") }
 
encrypt("ATTACKATDAWN").also { println("ATTACKATDAWN -> $it") }
decrypt("EYFENGIWDILA").also { println("EYFENGIWDILA -> $it") }
}
with(Bifid(Square("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"))) {
println("\n### ABC... 6x6")
encrypt("THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY").also { println("$it") }
decrypt("TBPDIPHJSPOTAIVMGPCZKNSCN09BFIHK64I7BM4").also { println("$it") }
}
}
</syntaxhighlight>
 
{{out}}
<pre>
### ABC... 5x5
ATTACKATDAWN -> DQBDAXDQPDQH
DQBDAXDQPDQH -> ATTACKATDAWN
 
### BGW... 5x5
FLEEATONCE -> UAEOLWRINS
UAEOLWRINS -> FLEEATONCE
ATTACKATDAWN -> EYFENGIWDILA
EYFENGIWDILA -> ATTACKATDAWN
 
### ABC... 6x6
TBPDIPHJSPOTAIVMGPCZKNSCN09BFIHK64I7BM4
THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY
</pre>
 
=={{header|Lua}}==
<p>The "In addition" task and the bonus task are both solved using a 6x6 Polybius square containing every captial letter and all ten digits.</p>
<p>I refer to this combined solution as 'Task 4'.</p>
<syntaxhighlight lang="lua">function transcipher (cipher, message, decipher)
local message = message:gsub("%s+", ""):upper()
local xStr, yStr, s, char = "", "", ""
for pos = 1, #message do
char = message:sub(pos, pos)
for x = 1, #cipher do
for y = 1, #cipher[x] do
if cipher[x][y] == char then
s = s .. x .. y
xStr = xStr .. x
yStr = yStr .. y
end
end
end
end
if decipher then
xStr, yStr = s:sub(1, #s/2), s:sub(#s/2 + 1, #s)
else
s = xStr .. yStr
end
local result, x, y = ""
local limit = decipher and #s/2 or #s
local step = decipher and 1 or 2
for pos = 1, limit, step do
x = tonumber(s:sub(pos, pos))
y = decipher and
tonumber(s:sub(pos + #s/2, pos + #s/2)) or
tonumber(s:sub(pos + 1, pos + 1))
result = result .. cipher[x][y]
end
return result
end
 
local RCbifid = {
{"A", "B", "C", "D", "E"},
{"F", "G", "H", "I", "K"},
{"L", "M", "N", "O", "P"},
{"Q", "R", "S", "T", "U"},
{"V", "W", "X", "Y", "Z"}
}
 
local wikibifid = {
{"B", "G", "W", "K", "Z"},
{"Q", "P", "N", "D", "S"},
{"I", "O", "A", "X", "E"},
{"F", "C", "L", "U", "M"},
{"T", "H", "Y", "V", "R"}
}
 
local mybifid = {
{"A", "B", "C", "D", "E", "F"},
{"G", "H", "I", "J", "K", "L"},
{"M", "N", "O", "P", "Q", "R"},
{"S", "T", "U", "V", "W", "X"},
{"Y", "Z", "1", "2", "3", "4"},
{"5", "6", "7", "8", "9", "0"}
}
 
local testCases = {
{RCbifid, "ATTACKATDAWN"},
{wikibifid, "FLEEATONCE"},
{wikibifid, "ATTACKATDAWN",},
{mybifid, "The invasion will start on the first of January"}
}
 
local msg
for task, case in pairs(testCases) do
print("\nTask " .. task)
msg = transcipher(case[1], case[2])
print("Encoded message: " .. msg)
msg = transcipher(case[1], msg, true)
print("Decoded message: " .. msg)
end</syntaxhighlight>
{{out}}
<pre>
Task 1
Encoded message: DQBDAXDQPDQH
Decoded message: ATTACKATDAWN
 
Task 2
Encoded message: UAEOLWRINS
Decoded message: FLEEATONCE
 
Task 3
Encoded message: EYFENGIWDILA
Decoded message: ATTACKATDAWN
 
Task 4
Encoded message: TBPDIPHJSPOTAIVMGPCZKNSCN10BFIHK75I8BM5
Decoded message: THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY</pre>
 
=={{header|Nim}}==
Line 1,114 ⟶ 1,799:
Decrypted: THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY
</pre>
 
=={{header|Quackery}}==
 
<code>transpose</code> is defined at [[Matrix transposition#Quackery]].
 
<syntaxhighlight lang="Quackery"> [ $ "" swap
witheach
[ upper
dup char I > if [ 1 - ]
dup char A char Z
within iff
[ char A - join ]
else drop ] ] is ->0..24 ( $ --> [ )
 
[ $ "" swap
witheach
[ char A +
dup char I > if 1+
join ] ] is ->A..Z ( [ --> $ )
 
[ [] 5 times
[ dip ->0..24 join ] ] is makesquare ( $ $ $ $ $ --> [ )
 
[ dup witheach
[ i^ unrot poke ] ] is makeindex ( [ --> [ )
 
[ dup temp put
makeindex temp put
->0..24
[] swap witheach
[ temp share swap peek
5 /mod join
nested join ]
temp release
transpose
unpack join
[] swap
dup size 2 / times
[ 2 split dip
[ nested join ] ]
drop
$ "" swap
witheach
[ unpack swap 5 * +
temp share swap peek
join ]
->A..Z
temp release ] is encrypt ( $ [ --> $ )
 
[ dup temp put
makeindex temp put
->0..24
[] swap witheach
[ temp share swap peek
5 /mod join join ]
temp release
dup size 2 / split
2 pack
transpose
[] swap witheach
[ unpack swap 5 * +
temp share swap peek
join ]
->A..Z
temp release ] is decrypt ( $ [ --> $ )
 
[ $ "ABCDE"
$ "FGHIK"
$ "LMNOP"
$ "QRSTU"
$ "VWXYZ"
makesquare ] constant is tasksquare ( --> [ )
 
[ $ "BGWKZ"
$ "QPNDS"
$ "IOAXE"
$ "FCLUM"
$ "THYVR"
makesquare ] constant is wikisquare ( --> [ )
 
[ $ "QUACK"
$ "DEPTH"
$ "LYING"
$ "FORMS"
$ "BVWXZ"
makesquare ] constant is ducksquare ( --> [ )
 
 
say "Using tasksquare:" cr
$ "Attack at dawn." dup echo$ say " -> "
tasksquare encrypt dup echo$ say " -> "
tasksquare decrypt echo$
cr cr
say "Using wikisquare:" cr
$ "Flee at once." dup echo$ say " -> "
wikisquare encrypt dup echo$ say " -> "
wikisquare decrypt echo$
cr cr
say "Using ducksquare:" cr
$ "The invasion will start on the first of January." dup echo$ cr say " -> "
ducksquare encrypt dup echo$ cr say " -> "
ducksquare decrypt echo$
</syntaxhighlight>
 
{{out}}
 
<pre>Using tasksquare:
Attack at dawn. -> DQBDAXDQPDQH -> ATTACKATDAWN
 
Using wikisquare:
Flee at once. -> UAEOLWRINS -> FLEEATONCE
 
Using ducksquare:
The invasion will start on the first of January.
-> EPGCNGINDORETNOMLLCNVNPWTIQXIOMVAGOANPY
-> THEINVASIONWILLSTARTONTHEFIRSTOFIANUARY
</pre>
 
=={{header|Raku}}==
Technically incorrect as the third part doesn't "Convert ... to upper case and ignore spaces".
Line 1,177 ⟶ 1,980:
Encrypted : NGiw3okfXj4XoVE_NjWcLK4Sy28EivKo3aeNiti3N3z6HCHno6Fkf
Decrypted : The_invasion_will_start_on_the_first_of_January_2023.</pre>
=={{header|RPL}}==
« DUP SIZE √ "" → in key n out
« { } DUP
1 in SIZE '''FOR''' j
key in j DUP SUB
POS 1 - n MOD LASTARG / IP
SWAP ROT SWAP + ROT ROT + SWAP
'''NEXT'''
+ 'in' STO
1 in SIZE '''FOR''' j
'out' key
in j DUP 1 + SUB
OBJ→ DROP SWAP n * + 1 +
DUP SUB STO+
2 '''STEP'''
out
» » '<span style="color:blue">→BIFCOD</span>' STO
« DUP SIZE √ "" → in key n out
« { }
1 in SIZE '''FOR''' j
key in j DUP SUB POS
1 - n MOD LASTARG / IP
ROT SWAP + SWAP +
'''NEXT'''
DUP 'in' STO SIZE 2 /
1 OVER '''FOR''' j
'out' key
in j GET n * in 5 PICK j + GET + 1 +
DUP SUB STO+
'''NEXT'''
DROP out
» » '<span style="color:blue">→BIFDEC</span>' STO
« { "ATTACKATDAWN" "ABCDEFGHIKLMNOPQRSTUVWXYZ"
"FLEEATONCE" "BGWKZQPNDSIOAXEFCLUMTHYVR"
"ATTACKATDAWN" "BGWKZQPNDSIOAXEFCLUMTHYVR"
"THE INVASION WILL START ON THE FIRST OF JANUARY" "ABCDEFGHIJKLMNOPQRSTUVWXYZ 123456789" }
→ examples
« 1 examples SIZE '''FOR''' j
examples j GETI ROT ROT GET
<span style="color:blue">→BIFCOD</span> DUP examples j 1 + GET
<span style="color:blue">→BIFDEC</span> 2 →LIST
2 '''STEP'''
» » '<span style="color:blue">TASK</span>' STO
 
{{out}}
<pre>
4: { "DQBDAXDQPDQH" "ATTACKATDAWN" }
3: { "UAEOLWRINS" "FLEEATONCE" }
2: { "EYFENGIWDILA" "ATTACKATDAWN" }
1: { "TEISTO1HKVCWO1GYIV EGPCZKOJAOI 9MG5OIH 64IRPBM4" "THE INVASION WILL START ON THE FIRST OF JANUARY" }
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby" line>
def cleanMsg(msg, square)
msg.upcase!
msg.delete!(' ')
msg.delete!('J') if square.index('J') == nil
end
 
def encrypt(msg, square)
cleanMsg msg, square
sq_size = (square.length ** 0.5).to_i
rows = [0] * msg.length
cols = [0] * msg.length
(0...msg.length).each do |i|
p = square.index(msg[i])
rows[i], cols[i] = p / sq_size, p % sq_size
end
result = ""
rows.concat(cols).each_slice(2) do |coord|
result += square[coord[0]*sq_size + coord[1]]
end
return result
end
 
def decrypt(msg, square)
msg.upcase!; square.upcase!
sq_size = (square.length ** 0.5).to_i
coords = []
result = ""
(0...msg.length).each do |i|
p = square.index(msg[i])
coords << p / sq_size
coords << p % sq_size
end
for i in (0...coords.length/2) do
row, col = coords[i], coords[i+coords.length/2]
result += square[row*sq_size + col]
end
return result
end
 
def printSquare(square)
sq_size = (square.length ** 0.5).to_i
(0..square.length).step(sq_size).each do |i|
print square[i...(i+sq_size)], "\n"
end
end
 
tests = [["ATTACKATDAWN" , "ABCDEFGHIKLMNOPQRSTUVWXYZ"],
["FLEEATONCE" , "BGWKZQPNDSIOAXEFCLUMTHYVR"],
["ATTACKATDAWN" , "ABCDEFGHIKLMNOPQRSTUVWXYZ"],
["the invasion will start on the first of january", "BGWKZQPNDSIOAXEFCLUMTHYVR"],
["THIS MESSAGE HAS NUMBERS 2023", "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"],
]
 
for test in tests
message = test[0]; square = test[1];
encrypted = encrypt(message, square)
decrypted = decrypt(encrypted, square)
 
puts "using the polybius:"
printSquare(square)
puts "the plain message:", message
puts "encrypted:", encrypted
puts "decrypted:", decrypted
puts "===================================================="
end</syntaxhighlight>
{{out}}
<pre>using the polybius:
ABCDE
FGHIK
LMNOP
QRSTU
VWXYZ
 
the plain message:
ATTACKATDAWN
encrypted:
DQBDAXDQPDQH
decrypted:
ATTACKATDAWN
====================================================
using the polybius:
BGWKZ
QPNDS
IOAXE
FCLUM
THYVR
 
the plain message:
FLEEATONCE
encrypted:
UAEOLWRINS
decrypted:
FLEEATONCE
====================================================
using the polybius:
ABCDE
FGHIK
LMNOP
QRSTU
VWXYZ
 
the plain message:
ATTACKATDAWN
encrypted:
DQBDAXDQPDQH
decrypted:
ATTACKATDAWN
====================================================
using the polybius:
BGWKZ
QPNDS
IOAXE
FCLUM
THYVR
 
the plain message:
THEINVASIONWILLSTARTONTHEFIRSTOFANUARY
encrypted:
RASOAQXCYRORXESXOLRGTXEGAWEWTNGTZTQALY
decrypted:
THEINVASIONWILLSTARTONTHEFIRSTOFANUARY
====================================================
using the polybius:
ABCDEF
GHIJKL
MNOPQR
STUVWX
YZ1234
567890
 
the plain message:
THISMESSAGEHASNUMBERS2023
encrypted:
TJMVBBDPMCW9ZIAYAEGBMK5XW
decrypted:
THISMESSAGEHASNUMBERS2023
====================================================
</pre>
 
=={{header|Wren}}==
One way of enabling all 26 letters to be encrypted uniquely would be to use a 6 x 6 Polybius square including the 10 digits. We could then encrypt text using numerals as well.
 
However, the following just uses the standard version of the cipher.
<syntaxhighlight lang="ecmascriptwren">import "./str" for Str
import "./seq" for Lst
 
1,983

edits