Substitution cipher: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 24:
{{trans|Kotlin}}
<
F encode(s)
Line 41:
V enc = encode(s)
print(‘Encoded: ’enc)
print(‘Decoded: ’decode(enc))</
{{out}}
Line 50:
=={{header|Ada}}==
<
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Sequential_IO;
Line 97:
end if;
end Cipher;
</syntaxhighlight>
=={{header|Arturo}}==
<
encode: function [str][
Line 120:
enc: encode s
print ["encoded:" enc]
print ["decoded:" decode enc]</
{{out}}
Line 129:
=={{header|C}}==
Takes input file name, plain and cipher keys and the action ( Encrypt or Decrypt) as inputs. Only the first character of the action string is checked, so if you are feeling really [https://www.nsa.gov/ NSA like], use whatever string you want as long as it has a d/D or e/E in front.
<syntaxhighlight lang="c">
#include<stdlib.h>
#include<stdio.h>
Line 194:
return 0;
}
</syntaxhighlight>
A long, long time ago ( yes, [http://www.rosettacode.org/wiki/N-body_problem#C I have said it before] ), I read Digital Fortress by Dan Brown. One thing which struck me was Ensei Tankado using the same algorithm to encrypt itself ( or it's human readable Unicode version, if you are a purist). I remembered the name : Bigelman's Safe, but I got the spelling wrong so I had to [https://archive.org/stream/LostSymbol/Dan%20Brown/Digital%20Fortress#page/n29/mode/2up/search/bigel read the copy on archive.org], it's there on the last line of page 30/31, Biggleman's Safe.
Line 282:
=={{header|C sharp}}==
<
using System.IO;
using System.Collections.Generic;
Line 425:
}
}
}</
=={{header|C++}}==
The key file should look something like this: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789SWoVR0kJLXQ8zbCd1OagTH5ie3nvYU2wfrM9yI4sKm6c7hNjtADqFPxpEZlBuG
<
#include <iostream>
#include <string>
Line 500:
return 0;
}
</syntaxhighlight>
=={{header|D}}==
<
import std.string;
import std.traits;
Line 532:
auto decode(string input) {
return tr(input, REVERSE, FORWARD);
}</
{{out}}
<pre>Encoded: aQSQn!Qn([MQnY%n=%no#nY(QSQn!o&&n+Qn[nokE@Y,#%@ShQLn)o&Qnokn!(oh(n!Qn[SQnW%okWnY%ngkhS~EYnY(Qn)o&Qn+~nSQE&[hokWnQMQS~Ln@EEQS,&%!QSnh[#Qn[&E([+QY#n%)nY(Qn#%@ShQn)o&Qn!oY(n[k%Y(QSLnESQ=QYQS^okQ=n@EEQS,&%!QSnh[#Qn[&E([+QY#n%Sn#~^+%&#n[k=n#[MQLnoYnokY%n[k%Y(QSn%@YE@Y,QkhS~EYQ=n)o&Qn[k=nY(Qkn[W[oknh%kMQSYLnY([Yn%@YE@Y,QkhS~EYQ=n)o&QnokY%n%SoWok[&,=QhS~EYQ=n)o&QAnq(o#LnY~EQn%)ngkhS~EYo%k,eQhS~EYo%kn#h(Q^Qno#n%)YQknh[&&Q=n[Lnx@+#YoY@Yo%knBoE(QSA
Line 547:
=={{header|Factor}}==
This program optionally allows the user to specify a file to use as a key. Otherwise, it uses a default.
<
hashtables io io.encodings.utf8 io.files kernel math.order
multiline namespaces qw sequences ;
Line 597:
command-line get dup check-args [ substitute ] [ drop ] if ;
MAIN: main</
{{out}}
Contents of key.txt:
Line 642:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 735:
end subroutine
end program </
{{out}}
<pre>
Line 756:
=={{header|FreeBASIC}}==
<
' uses same alphabet and key as Ada language example
Line 795:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 830:
=={{header|Go}}==
{{trans|Kotlin}}
<
import (
Line 860:
fmt.Println("Encoded: ", enc)
fmt.Println("Decoded: ", decode(enc))
}</
{{out}}
Line 869:
=={{header|IS-BASIC}}==
<
110 STRING ST$(1 TO 2)*52,K$*1
120 LET ST$(1)="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 921:
600 PRINT EXSTRING$(EXTYPE)
610 END
620 END HANDLER</
=={{header|Haskell}}==
<
import Data.Maybe (fromMaybe)
import Data.Tuple (swap)
Line 958:
main :: IO ()
main = parseArgs <$> getArgs >>= putStrLn . runCommand</
{{out}}
<pre>$ simplecipher c "The quick brown fox jumped over the lazy dogs."
Line 970:
Example implementation:
<
key=: 'Taehist' keysubst '!@#$%^&'
enc=: a. {~ key i. ]
Line 978:
!$%^ %^ @ &#^&.
dec '!$%^ %^ @ &#^&.'
This is a test.</
Note that this particular implementation bakes the key itself into the implementations of <code>enc</code> and <code>dec</code>. Also note that this particular key is rather limited - letters not mentioned in the key encrypt as another identical character. That seems to be sufficient, given the current task description. But of course other approaches are also possible...
=={{header|Java}}==
<
final static String key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"
Line 1,020:
return sb.toString();
}
}</
<pre>Encoded: "uTu]cu]b3Qu]<d]Id]...><K<,<Kd|]6KMbuTi
Line 1,029:
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<
"]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";
Line 1,053:
"Decoded: \($encoded|decode)" ;
task</
{{out}}
<pre>
Line 1,066:
'''Module''':
<
using Compat
Line 1,088:
end
end # module SubstitutionCiphers</
'''Main''':
<
enc = SubstitutionCiphers.encode(s)
dec = SubstitutionCiphers.decode(enc)
println("Original: ", s, "\n -> Encoded: ", enc, "\n -> Decoded: ", dec)
end</
{{out}}
Line 1,103:
=={{header|Klingphix}}==
<syntaxhighlight lang="text">include ..\Utilitys.tlhy
" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 1,126:
false Encode ?
" " input</
=={{header|Kotlin}}==
{{trans|Java}}
<
object SubstitutionCipher {
Line 1,153:
println("Encoded: $enc")
println("Decoded: ${SubstitutionCipher.decode(enc)}")
}</
{{out}}
Line 1,164:
The {substitution shift text} function accepts any text containing characters in the set [! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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 [ \ ] ^ _ ` 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], except the ` character. These characters have charCodes in the range [33..122], (length = 90). The ` character is used to catch and prevent spaces and must not be used. The shift argument can be in the range [0...90] except 5 10 15 29 30 50 53 70 74 which are in conflict with the lambdatalk evaluator.
<
{def small_ascii {S.map fromCharCode {S.serie 33 122}}}
Line 1,219:
Pharnaces II of Pontus at the Battle of Zela.
</syntaxhighlight>
=={{header|Lua}}==
<
function randomCipher ()
local cipher, rnd = {plain = {}, encoded = {}}
Line 1,272:
print("\t" .. encoded)
print("\nAbove text deciphers to: ")
print("\t" .. encode(encoded, subCipher, true))</
{{out}}
<pre>Cipher generated:
Line 1,295:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
a=Characters@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
map=Thread[a->RandomSample[a]];
Line 1,305:
encoded=SubstitutionCipherEncode[str,map]
decoded=SubstitutionCipherDecode[encoded,map]
str===decoded</
{{out}}
<pre>"DebTyUsLNTg2H01TWHSTfUt5qTHZb2T7ebTl4 8TQHc,0eHTg42NqTuK6CTlHUQl8!"
Line 1,312:
=={{header|MiniScript}}==
<
cipher = alphabet[0:]
cipher.shuffle
Line 1,335:
secretCode = apply(encode, msg)
print secretCode
print apply(decode, secretCode)</
{{out}}
<pre>Rzs ho wft whxt bzv ykk nzzg xtr (yrg szxtr) wz jzxt wzntwftv.
Line 1,341:
=={{header|Nim}}==
<
proc encrypt(key: seq[char]; msg: string): string =
Line 1,369:
echo "Message = “$#”" % Message
echo "Encrypted = “$#”" % encrypted
echo "Decrypted = “$#”" % decrypted</
{{out}}
Line 1,379:
=={{header|Perl}}==
{{trans|Java}}
<
my $source = shift;
my $key = shift;
Line 1,421:
my $pt = decode($ct, $key);
print "Decoded: $pt\n";</
{{out}}
<pre>Encoded: "uTu]cu]b3Qu]<d]Id]K>]<buTu]cKUU].u]3]K|M,< >d,THu]4KUu]K|]cbKHb]cu]3Tu]fdK|f]<d]Z|HTCM<]<bu]4KUu].C]TuMU3HK|f]uQuTC],MMuT UdcuT]H3>u]3UMb3.u<>]d4]<bu]>d,THu]4KUu]cK<b]3|d<buT]MTuIu<uT8K|uI],MMuT UdcuT]H3>u]3UMb3.u<>]dT]>C8.dU>]3|I]>3Qu]K<]K|<d]3|d<buT]d,<M,< u|HTCM<uI]4KUu]3|I]<bu|]3f3K|]Hd|QuT<]<b3<]d,<M,< u|HTCM<uI]4KUu]K|<d]dTKfK|3U IuHTCM<uI]4KUui]2bK>]<CMu]d4]Z|HTCM<Kd| %uHTCM<Kd|]>Hbu8u]K>]d4<u|]H3UUuI]3]q,.><K<,<Kd|]6KMbuTi
Line 1,427:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">constant</span> <span style="color: #000000;">plain</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'Z'</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">)&</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'z'</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'a'</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">key</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">plain</span><span style="color: #0000FF;">)</span>
Line 1,445:
<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;">"original: %s\nencoded: %s\ndecoded: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">original</span><span style="color: #0000FF;">,</span><span style="color: #000000;">encoded</span><span style="color: #0000FF;">,</span><span style="color: #000000;">decoded</span><span style="color: #0000FF;">})</span>
<!--</
{{Out}}
<pre>
Line 1,454:
=={{header|Phixmonti}}==
<
" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 1,475:
dup ?
true Encode dup ?
false Encode ?</
{{out}}
<pre>A simple example
Line 1,485:
=={{header|PHP}}==
<
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
Line 1,503:
$encoded, PHP_EOL, PHP_EOL,
'== DECODED ==', PHP_EOL,
$decoded, PHP_EOL, PHP_EOL;</
{{out}}
Line 1,541:
=={{header|Picat}}==
{{trans|Prolog}}
<
S = "The quick brown fox jumped over the lazy dog",
cypher(S,E), % encrypt
Line 1,580:
Goal) :-
call(Goal, Elem1, Elem2),
maplist_(Tail1, Tail2, Goal).</
{{out}}
Line 1,588:
===Using maps===
<
S = "The quick brown fox jumped over the lazy dog!!!",
E = encrypt(S),
Line 1,610:
base("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ").
subs("VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWob LkESYMTN").</
{{out}}
Line 1,619:
=={{header|PicoLisp}}==
<
(setq *K (chop "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"))
Line 1,637:
(and
(println 'encode (cipher "The quick brown fox jumped over the lazy dog's back"))
(println 'decode (cipher @ T)) )</
{{out}}
<pre>encode "tFq oERJp wbQYh OQM AEDWqx QSqb kFq nINT xQC'L wIJp"
Line 1,643:
=={{header|Pike}}==
<
string key = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN";
mapping key_mapping = mkmapping(alphabet/1, key/1);
Line 1,653:
write("Encrypted: %s\n", msg_enc);
write("Decrypted: %s\n", msg_dec);</
{{out}}
Line 1,662:
=={{header|Prolog}}==
<
nonvar(O),
var(S),
Line 1,685:
sub_char([Co|_],[Cs|_],Co,Cs) :- !.
sub_char([_|To],[_|Ts], Co, Cs) :- sub_char(To,Ts,Co,Cs).</
{{out}}
<pre>
Line 1,697:
=={{header|Python}}==
<syntaxhighlight lang="python">
from string import printable
import random
Line 1,716:
Gives: {}
Decoding it by the same key gives: {}""".format(
original, EXAMPLE_KEY, encoded, decoded))</
A straightforward implementation. The output is:
<syntaxhighlight lang="text">The original is: A simple example.
Encoding it with the key: dV1>r7:TLlJa�uY o]MjH\hI^X cPN#!fmv[
<e=04|O'~{y$bAq@}U.WtF*)x/K?
Line 1,726:
Gives:
iPMhX\YiYmJhX\Y5
Decoding it by the same key gives: A simple example.</
=={{header|Quackery}}==
<
[ stack ] is decryption ( --> s )
Line 1,774:
say "Encrypted: " encrypt dup echo$ cr
say "Decrypted: " decrypt echo$ cr
releasekeys</
{{out}}
Line 1,792:
so I don't display the plaintext in the output.
<
(require racket/list racket/function racket/file)
Line 1,846:
(displayln (file->string "data/substitution.crypt.txt"))
(check-equal? (file->string "data/substitution.in.txt")
(file->string "data/substitution.plain.txt")))</
{{out}}
Line 1,870:
{{works with|Rakudo|2015-11-20}}
Feed it an action (encode, decode) and a file name at the command line and it will spit out the (en|de)coded file to STDOUT. Redirect into a file to save it. If no parameters are passed in, does the demo encode/decode.
<syntaxhighlight lang="raku"
my $key = $chr.comb.pick(*).join('');
Line 1,905:
sub encode ($text) { $text.trans($chr => $key) }
sub decode ($text) { $text.trans($key => $chr) }</
{{out}} with no passed parameters:
<pre>Key = 3#}^",dLs*>tPMcZR!fmC rEKhlw1v4AOgj7Q]YI+|pDB82a&XFV9yzuH<WT%N;iS.0e:`G\n['6@_{bk)=-5qx(/?$JoU
Line 1,935:
::* the two records should be equal in the number of characters.
::* the N<sup>th</sup> character of record '''1''' will be encrypted to the N<sup>th</sup> character of record '''2'''.
<
parse arg fid.1 fid.2 fid.3 fid.4 . /*obtain optional arguments from the CL*/
if fid.1=='' then fid.1= "CIPHER.IN" /*Not specified? Then use the default.*/
Line 1,975:
say @in ' records processed: ' j /*show the number of records processed.*/
call closer /*close all the files to be neat & safe*/
return</
'''output''' when using the default input files:
<pre>
Line 2,028:
=={{header|Ring}}==
<
# Project : Substitution Cipher
Line 2,077:
next
return str
</syntaxhighlight>
Output:
<pre>
Line 2,088:
=={{header|Ruby}}==
<
Key = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
Line 2,097:
p encrypted = encrypt(str)
p decrypt(encrypted)
</syntaxhighlight>
{{out}}
<pre>"Vnn RL nQLk, Fq kFQECFk. BSqbTkFRhC RL bERhqx. gk’L kqh WILk kFbqq."
Line 2,104:
=={{header|Scala}}==
<
private val key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N" + "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"
private val text =
Line 2,133:
sb.toString
}
}</
{{Out}}See it running in your browser by [https://scalafiddle.io/sf/f9yNWk7/0 ScalaFiddle (JavaScript, non JVM)] or by [https://scastie.scala-lang.org/8CyCsxnnRZyn0JH0yegndA Scastie (JVM)].
=={{header|Sidef}}==
{{trans|Julia}}
<
const key = %c"]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"
Line 2,164:
var dec = SubstitutionCipher::decode(enc)
say("Original: ", s, "\n -> Encoded: ", enc, "\n -> Decoded: ", dec)
}</
{{out}}
<pre>Original: The quick brown fox jumps over the lazy dog, who barks VERY loudly!
Line 2,180:
The default alphabet is <tt>a-zA-Z</tt>, but can be overridden by providing an argument to the constructor. A random initial key will be generated at construction time, unless that is also provided as an argument.
<
variable Alphabet
variable Key
Line 2,238:
string map $DecMap $s
}
}</
Testing looks like this:
<
set text [read [open /etc/motd]]
puts "Original:\n$text\n----\n"
puts "Ciphered:\n[set cipher [sc enc $text]]\n----\n"
puts "Decrypted:\n[sc dec $cipher]\n----\n"
puts "Key:\n[sc key]\n----\n"</
{{out}}
Line 2,290:
=={{header|VBScript}}==
Not too efficient. It generates the key string as an array of ASCII codes. Uses the same routine to encode and to decode.
<syntaxhighlight lang="vb">
option explicit
const maxk=94
Line 2,346:
wscript.echo "Decoded: " & c & Vbcrlf
wscript.quit(0)
</syntaxhighlight>
{{out}}
<pre>
Line 2,360:
=={{header|Wren}}==
{{trans|Kotlin}}
<
var encode = Fn.new { |s|
Line 2,377:
var enc = encode.call(s)
System.print("Encoded: %(enc)")
System.print("Decoded: %(decode.call(enc))")</
{{out}}
Line 2,386:
=={{header|zkl}}==
<
// 92 characters: " !"#$%&" ... "xyz{|}", doesn't include "~"
const KEY="]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"
Line 2,392:
fcn encode(s){ s.apply(fcn(c){ try{ KEY[c.toAsc()-32] }catch{ c } }) }
fcn decode(s){ s.apply(fcn(c){ try{ (KEY.index(c)+32).toChar() }catch{ c } }) }
}</
<
"file in which we are going to Encrypt the file by replacing every "
"upper/lower case alphabets of the source file with another "
Line 2,403:
encoded:=SubstitutionCipher.encode(text);
println( "Encoded: ",encoded);
println("\nDecoded: ",SubstitutionCipher.decode(encoded));</
{{out}}
<pre>
|