Playfair cipher: Difference between revisions
m
→{{header|Wren}}: Minor tidy
m (→{{header|J}}: spaces between character pairs are not meaningful for decrypt) |
m (→{{header|Wren}}: Minor tidy) |
||
(4 intermediate revisions by 4 users not shown) | |||
Line 19:
{{trans|Python}}
<
[Char] seen
L(x) seq
Line 78:
V enc = playfair.encode(orig)
print(‘Encoded: ’enc)
print(‘Decoded: ’playfair.decode(enc))</
{{out}}
Line 85:
Encoded: BM OD ZB XD NA BE KU DM UI XM MO UV IF
Decoded: HI DE TH EG OL DI NT HE TR EX ES TU MP
</pre>
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">⍝⍝⍝⍝ Utility functions
⍝ convert to uppercase
UpCase ← { 1 ⎕C ⍵ }
⍝ remove non-letters
JustLetters ← { ⍵ /⍨ ⍵∊⎕A }
⍝ replace 'J's with 'I's
ReplaceJ ← { ('J' ⎕R 'I') ⍵ }
⍝ Insert an 'X' between repeated letters
SplitDouble ← { (' '⎕R'X') ⍵ \⍨ 1,~⍵=1⌽⍵ }
⍝ Append an 'X' if the message is not of even length
PadEven ← { ⍵,(2|≢⍵) ⍴ 'X' }
⍝ Split text up into letter pairs
Pairs ← { (1=2|⍳≢⍵) ⊂ ∊ ⍵ }
⍝ Group text into chunks of five letters
Groups ← { (1=5|⍳≢⍵) ⊂ ∊ ⍵ }
⍝ Shift within 1-5 based on left arg (0 for +1,1 for -1)
Shift ← { ⍺ ← 0 ⋄ 1+5|(⍺+1)⌷⍵,3+⍵ }
⍝⍝⍝⍝ Playfair implementation
⍝ All the things we have to do to the plaintext, chained together
PreparePlaintext ← { PadEven SplitDouble ReplaceJ JustLetters UpCase ∊ ⍵ }
⍝ Ditto for ciphertext
PrepareCiphertext ← { JustLetters UpCase ∊ ⍵ }
⍝ Create the grid from the key
PrepareKey ← { 5 5⍴ ∪ ReplaceJ (JustLetters UpCase ⍵),⎕A }
⍝ Encode or decode a single pair of letters
∇resultPair ← grid TransformPair args;mode;inPair;l;r;i1;j1;i2;j2
mode inPair ← args
l r ← inPair
i1 j1 ← ⊃⍸grid=l
i2 j2 ← ⊃⍸grid=r
:If i1=i2
j1 ← mode Shift j1
j2 ← mode Shift j2
:Else
:If j1=j2
i1 ← mode Shift i1
i2 ← mode Shift i2
:Else
j1 j2 ← j2 j1
:EndIf
:EndIf
resultPair ← grid[(i1 j1)(i2 j2)]
∇
⍝ Encode or decode an entire message
∇resultText ← grid TransformText args; mode; inText
mode inText ← args
resultText ← Groups ∊ { grid TransformPair mode ⍵ } ¨ Pairs inText
∇
⍝ Specific transforms for each direction including key and text preparation
∇cipher ← key EncodeText plain
cipher ← (PrepareKey key) TransformText 0 (PreparePlaintext plain)
∇
∇plain ← key DecodeText cipher
plain ← (PrepareKey key) TransformText 1 (PrepareCiphertext cipher)
∇
⍝ Demo
key ← 'Playfair example'
plain ← 'Hide the gold in the tree stump.'
⎕ ← cipher ← key EncodeText plain
⎕ ← key DecodeText cipher</syntaxhighlight>
{{Out}}<pre> ⎕ ← cipher ← key EncodeText plain
┌─────┬─────┬─────┬─────┬─────┬─┐
│BMODZ│BXDNA│BEKUD│MUIXM│MOUVI│F│
└─────┴─────┴─────┴─────┴─────┴─┘
</pre>
<pre> ⎕ ← key DecodeText cipher
┌─────┬─────┬─────┬─────┬─────┬─┐
│HIDET│HEGOL│DINTH│ETREX│ESTUM│P│
└─────┴─────┴─────┴─────┴─────┴─┘
</pre>
=={{header|C++}}==
<
#include <string>
Line 197 ⟶ 288:
cout << "Enter the text: "; getline( cin, txt );
playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
}</
{{out}}<pre>
(E)ncode or (D)ecode? e
Line 221 ⟶ 312:
=={{header|D}}==
{{trans|Python}}
<
std.conv, std.string, std.regex, std.typecons;
Line 291 ⟶ 382:
writeln(" Encoded: ", enc);
writeln(" Decoded: ", pf.decode(enc));
}</
{{out}}
<pre>Original: Hide the gold in...the TREESTUMP!!!
Line 298 ⟶ 389:
=={{header|FreeBASIC}}==
<
Enum PlayFairOption
Line 453 ⟶ 544:
Print
Print "Press any key to quit"
Sleep</
Sample input/output:
{{out}}
Line 475 ⟶ 566:
=={{header|Go}}==
{{trans|Kotlin}}
<
import (
Line 682 ⟶ 773:
decodedText := pf.decode(encodedText)
fmt.Println("Deccoded text is :", decodedText)
}</
{{out}}
Line 706 ⟶ 797:
{{incorrect|Haskell|TREESTUMP -> TREXSTUMPX, should be TREXESTUMP}}
(My guess is that map (\[x, y] -> if x == y then [x, 'x'] else [x, y]).chunksOf 2 is simply discarding the y. [[User:Petelomax|Pete Lomax]] ([[User talk:Petelomax|talk]]) 05:54, 13 October 2018 (UTC))
<
import Control.Monad (guard)
import Data.Array (Array, assocs, elems, listArray, (!))
Line 808 ⟶ 899:
| odd (length str) = str ++ "x"
| otherwise = str
</syntaxhighlight>
<pre>
Line 822 ⟶ 913:
'''Implementation:'''
<
sel=. 'Q' e. y
alph=: (sel { 'JQ') -.~ a. {~ 65 + i.26
Line 857 ⟶ 948:
decrypt=: verb define
, ref{~alt i. pairs y
)</
'''Example use:'''
<
setkey 'playfair example'
Line 866 ⟶ 957:
BM OD ZB XD NA BE KU DM UI XM MO UV IF
decrypt 'BM OD ZB XD NA BE KU DM UI XM MO UV IF'
HIDETHEGOLDINTHETREXESTUMP</
=={{header|Java}}==
<
import java.util.Scanner;
Line 972 ⟶ 1,063:
return text.toString();
}
}</
=== alternative version ===
<
public class PlayfairCipherEncryption
Line 1,180 ⟶ 1,271:
sc.close();
}
}</
=={{header|Julia}}==
<
to = (to == "" && from == "J") ? "I" : to
Line 1,243 ⟶ 1,334:
println("Decoded: ", playfair("Playfair example", encoded, false))
</
<pre>
Original: Hide the gold in...the TREESTUMP!!!
Line 1,252 ⟶ 1,343:
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<
enum class PlayfairOption {
Line 1,384 ⟶ 1,475:
val decodedText = playfair.decode(encodedText)
println("Decoded text is : $decodedText")
}</
{{out}}
Line 1,405 ⟶ 1,496:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
MakeTranslationTable[tt_List] := Module[{poss, in, out},
poss = Tuples[Tuples[Range[5], 2], 2];
Line 1,476 ⟶ 1,567:
]
PlayfairCipher["Hide the gold in...the TREESTUMP!!!", "Playfair example"]
PlayfairDecipher[%, "Playfair example"]</
{{out}}
<pre>BM OD ZB XD NA BE KU DM UI XM MO UV IF
Line 1,483 ⟶ 1,574:
=={{header|Nim}}==
{{trans|Java}}
<
type
Line 1,581 ⟶ 1,672:
echo "Encoded message: ", enc
echo "Decoded message: ", dec</
{{out}}
Line 1,591 ⟶ 1,682:
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 1,756 ⟶ 1,847:
return
</syntaxhighlight>
{{out}}
<pre>
Line 1,779 ⟶ 1,870:
=={{header|ooRexx}}==
<
* REXX program implements a PLAYFAIR cipher (encryption & decryption).
* 11.11.2013 Walter Pachl revamped, for ooRexx, the REXX program
Line 1,976 ⟶ 2,067:
d=d||substr(x,j,2)' '
End
Return strip(d)</
Output (sample):
<pre>old cipher key: this is my little key
Line 1,999 ⟶ 2,090:
=={{header|Perl}}==
{{trans|Raku}}
<
# Pregenerate all forward and reverse translations
Line 2,070 ⟶ 2,161:
print " orig:\t$orig\n";
print "black:\t$black\n";
print " red:\t$red\n";</
{{out}}
<pre> orig: Hide the gold in...the TREESTUMP!!!
Line 2,079 ⟶ 2,170:
=={{header|Phix}}==
Originally translated from Kotlin, now uses a combined routine (playfair) for encoding and decoding, and direct char lookups, and x removal.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">keyword</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Playfair example"</span><span style="color: #0000FF;">,</span>
Line 2,193 ⟶ 2,284:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Encoded text is : %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">encoded</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Decoded text is : %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">decoded</span><span style="color: #0000FF;">})</span>
<!--</
{{out}}
<pre>
Line 2,215 ⟶ 2,306:
=={{header|Python}}==
{{trans|Raku}}
<
from itertools import product
from re import findall
Line 2,276 ⟶ 2,367:
enc = encode(orig)
print "Encoded:", enc
print "Decoded:", decode(enc)</
{{out}}
<pre>Original: Hide the gold in...the TREESTUMP!!!
Line 2,284 ⟶ 2,375:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
sub playfair( $key,
Line 2,346 ⟶ 2,437:
my $red = decode $black;
say " red:\t$red";</
{{out}}
<pre> orig: Hide the gold in...the TREESTUMP!!!
Line 2,362 ⟶ 2,453:
A fair amount of code was added to massage the decrypted encryption to remove doubled '''X'''es so as to match the original text
<br>(this is the ''possible text'' part of the REXX code).
<
@abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU= @abc /*literals for lower and upper ABC's.*/
parse arg omit key '(' text /*TEXT is the phrase to be used. */
Line 2,449 ⟶ 2,540:
if datatype(_, 'M') then $= $ || _ /*only use Latin letters. */
end /*j*/
return $</
Some older REXXes don't have a '''changestr''' bif, so one is included here ──► [[CHANGESTR.REX]].
<br><br>
Line 2,502 ⟶ 2,593:
Printing the cipher in pairs just advertises the mechanism of encoding; I've gone with the traditional grouping into sequences of five letters instead.
<
Size = 5
def initialize(key, missing)
Line 2,555 ⟶ 2,646:
end.join.split('').each_slice(5).map{|s|s.join}.join(' ')
end
end</
{{Out}}
Line 2,565 ⟶ 2,656:
=={{header|Sidef}}==
{{trans|Raku}}
<
func canon(str) {
Line 2,623 ⟶ 2,714:
var red = decode(black)
say " red:\t#{red}"</
{{out}}
<pre>
Line 2,632 ⟶ 2,723:
=={{header|SQL}}==
<
--Clean up previous run
IF EXISTS (SELECT *
Line 2,946 ⟶ 3,037:
WHERE NAME = 'FairPlayTable')
DROP TYPE FAIRPLAYTABLE
</syntaxhighlight>
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<
oo::class create Playfair {
Line 3,036 ⟶ 3,127:
return $result
}
}</
Demonstrating:
<
set plaintext "Hide the gold in...the TREESTUMP!!!"
set encoded [cypher encode $plaintext]
Line 3,044 ⟶ 3,135:
puts "Original: $plaintext"
puts "Encoded: $encoded"
puts "Decoded: $decoded"</
{{out}}
<pre>
Line 3,053 ⟶ 3,144:
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 3,260 ⟶ 3,351:
SwapPairsDecoding = myTable(resD1.Row, resD1.Column) & myTable(resD2.Row, resD2.Column)
End Select
End Function</
{{out}}
<pre>Enter your keyword : Playfair example
Line 3,284 ⟶ 3,375:
Decoded text is : HI DE TH EG OL DI NT HE TR EE ST UM PX</pre>
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import os
import strings
type PlayfairOption = int
Line 3,474 ⟶ 3,565:
decoded_text := pf.decode(encoded_text)
println("Deccoded text is : $decoded_text")
}</
{{out}}
Line 3,499 ⟶ 3,590:
{{libheader|Wren-dynamic}}
{{libheader|Wren-str}}
{{libheader|Wren-
{{libheader|Wren-ioutil}}
<
import "./str" for Str, Char
import "./
import "./ioutil" for Input
var PlayfairOption = Enum.create("PlayfairOption", ["NO_Q", "I_EQUALS_J"])
Line 3,635 ⟶ 3,726:
System.print("\nEncoded text is : %(encodedText)")
var decodedText = playfair.decode(encodedText)
System.print("Decoded text is : %(decodedText)")</
{{out}}
Line 3,656 ⟶ 3,747:
=={{header|zkl}}==
<
deadChr=deadChr.toUpper();
key=key.toUpper().unique() - " " - deadChr;
return(key + (["A".."Z"].pump(String) - deadChr - key), deadChr);
}</
<
keyTable,deadChr:=keytable;
text=text.toUpper();
Line 3,684 ⟶ 3,775:
})
.pump(String,Void.Read,"".create.fp(" ")).strip(); // insert blanks
}</
<
keyTable,_=keyTable;
text-=" ";
Line 3,701 ⟶ 3,792:
.pump(String,Void.Read,"".create.fp(" ")).strip(); // insert blanks
}
</syntaxhighlight>
<
keyTable:=genKeyTable("playfair example");
msg.println();
e:=playfair(msg,keyTable); e.println();
decodePF(e,keyTable).println();
playfair("XX",keyTable).println() : decodePF(_,keyTable).println();</
{{out}}
<pre>
|