Substitution cipher: Difference between revisions

m
no edit summary
mNo edit summary
 
(35 intermediate revisions by 22 users not shown)
Line 6:
 
;Task:
Encrypt aan input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
 
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Line 21:
<br><br>
 
=={{header|11l}}==
{{trans|Kotlin}}
 
<syntaxhighlight lang="11l">V key = ‘]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\C1yxJ’
 
F encode(s)
V r = ‘’
L(c) s
r ‘’= :key[c.code - 32]
R r
 
F decode(s)
V r = ‘’
L(c) s
r ‘’= Char(code' :key.index(c) + 32)
R r
 
V s = ‘The quick brown fox jumps over the lazy dog, who barks VERY loudly!’
V enc = encode(s)
print(‘Encoded: ’enc)
print(‘Decoded: ’decode(enc))</syntaxhighlight>
 
{{out}}
<pre>
Encoded: 2bu]E,KHm].Tdc|]4d\]),8M>]dQuT]<bu]U31C]Idf_]cbd].3Tm>]+ZzL]Ud,IUCk
Decoded: The quick brown fox jumps over the lazy dog, who barks VERY loudly!
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program subscipher64.s */
 
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFSIZE, 50000 // buffer size
.equ O_RDWR, 0x0002 // open for reading and writing
 
/************************************/
/* Initialized data */
/************************************/
.data
szMessInst: .asciz "use : subscipher inputfile outpufile E (encryt) or D (decript).\n"
szMessCode: .asciz "Code operation not = E or D !!\n"
szMessErrorOpen: .asciz "Error open input file .\n"
szMessErrorCreate: .asciz "Error create output file.\n"
szMessErrorClose: .asciz "Error close file.\n"
szMessErrorRead: .asciz "Error read file.\n"
szMessErrorWrite: .asciz "Write error to output file.\n"
szMessTrtOK: .asciz "Encoding/decoding OK.\n"
szCarriageReturn: .asciz "\n"
// ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^ _`abcdefghijklmnopqrstuvwxyz
szBufferKey: .asciz "VsciBjedgrzyHalvXZKtUPumGf[\]^ _`IwJxqOCFRApnDhQWobLkESYMTN"
.equ LGBUFFERKEY, . - szBufferKey
/************************************/
/* UnInitialized data */
/************************************/
.bss
.align 4
qAdrFicInput: .skip 8
qAdrFicOutput: .skip 8
sBufferRead: .skip BUFFSIZE
sBufferWrite: .skip BUFFSIZE
/************************************/
/* code section */
/************************************/
.text
.global main
main:
mov fp,sp // fp <- start address
ldr x4,[fp] // number of Command line arguments
cmp x4,#4 // test if number is ok
beq 1f
ldr x0,qAdrszMessInst // no -> display error
bl affichageMess
b 100f
1:
ldr x6,[fp,#16] // address input file name
ldr x20,[fp,#24] // address output file name
ldr x5,[fp,#32] // address code operation
ldrb w21,[x5] // loaf first code character
cmp x21,#'E' // control if code is OK
beq 2f
cmp x21,#'D'
beq 2f
ldr x0,qAdrszMessCode // no -> display error
bl affichageMess
b 100f
2:
mov x0,AT_FDCWD
mov x1,x6 // file name
mov x2,#O_RDWR // flags
mov x3,#0 // mode
mov x8,#OPEN // call system OPEN
svc #0
cmp x0,#0 // open error ?
ble 99f
mov x19,x0 // save FD
// file read
ldr x1,qAdrsBufferRead // buffer address
mov x2,#BUFFSIZE // buffer size
mov x8,READ
svc 0
cmp x0,#0 // read error ?
ble 98f
mov x22,x0 // length read characters
mov x0,x19 // Fd
mov x8,CLOSE
svc 0
cmp x0,#0 // close error ?
blt 97f
ldr x0,qAdrsBufferRead
mov x1,x22 // length read characters
ldr x2,qAdrszBufferKey
mov x3,#LGBUFFERKEY
ldr x4,qAdrsBufferWrite
mov x5,x21 // and x5 contains E or D
bl traitement
// write output file
mov x0,AT_FDCWD
mov x1,x20 // file output name
mov x2,O_CREAT|O_RDWR // flags
ldr x3,qFicMask1
mov x8, #OPEN // call system open file
svc 0
cmp x0,#0 // create error ?
ble 96f
mov x19,x0 // file descriptor
ldr x1,qAdrsBufferWrite
mov x2,x22 // length read characters
mov x8, #WRITE // select system call 'write'
svc #0 // perform the system call
cmp x0,#0 // error write ?
blt 95f
mov x0,x19 // Fd output file
mov x8,CLOSE
svc 0
cmp x0,#0 // close error ?
blt 97f
ldr x0,qAdrszMessTrtOK // end message
bl affichageMess
b 100f
95: // errors
ldr x0,qAdrszMessErrorWrite
bl affichageMess
b 100f
96:
ldr x0,qAdrszMessErrorCreate
bl affichageMess
b 100f
97:
ldr x0,qAdrszMessErrorClose
bl affichageMess
b 100f
98:
ldr x0,qAdrszMessErrorRead
bl affichageMess
b 100f
99:
ldr x0,qAdrszMessErrorOpen
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc 0 // perform the system call
 
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessInst: .quad szMessInst
qAdrszMessCode: .quad szMessCode
qAdrsBufferRead: .quad sBufferRead
qAdrsBufferWrite: .quad sBufferWrite
qAdrszBufferKey: .quad szBufferKey
qAdrszMessErrorOpen: .quad szMessErrorOpen
qAdrszMessErrorRead: .quad szMessErrorRead
qAdrszMessErrorClose: .quad szMessErrorClose
qAdrszMessErrorWrite: .quad szMessErrorWrite
qAdrszMessErrorCreate: .quad szMessErrorCreate
qAdrszMessTrtOK: .quad szMessTrtOK
qFicMask1: .quad 0644
/******************************************************************/
/* encoding or decoding buffer */
/******************************************************************/
/* x0 contains input file address */
/* x1 contains length buffer */
/* x2 contanis key buffer address */
/* x3 contains key buffer length */
/* x4 contains output file address */
/* x5 contains code E or D */
traitement:
stp x5,lr,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
cmp x5,#'D' // code ?
beq decoding
mov x5,#0 // init indice
1: // loop read characters buffer
ldrb w6,[x0,x5] // load une character
sub x6,x6,#0x41 // conv ascii -> numeric
cmp x6,#0 // < A
blt 2f
cmp x6,#0x3A // > z
bgt 2f
ldrb w7,[x2,x6] // load key character at index
b 3f
2:
add x7,x6,#0x41 // conv numeric -> ascii
3:
strb w7,[x4,x5] // store encoded character in output buffer
add x5,x5,#1 // increment indice
cmp x5,x1 // end ?
ble 1b
b 100f
decoding:
mov x5,#0 // init indice
4:
ldrb w6,[x0,x5] // load one character
cmp x6,#0x41 // < A
blt 6f
cmp x6,#0x7A // > z
bgt 6f
mov x8,#0 // init key indice
5:
ldrb w7,[x2,x8] // load key character
cmp x7,x6 // compare character
add x9,x8,#0x41 // if equal convert indice to ascii
csel x7,x9,x7,eq
beq 7f
add x8,x8,#1 // else increment key indice
cmp x8,x3 // end key ?
ble 5b // no -> loop
6:
mov x7,x6 // move input character in output
7:
strb w7,[x4,x5] // store decoded character in output buffer
add x5,x5,#1 // increment indice
cmp x5,x1 // end buffer ?
ble 4b
100:
ldp x8,x9,[sp],16 // restaur registers
ldp x6,x7,[sp],16 // restaur registers
ldp x5,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
 
</syntaxhighlight>
{{Out}}
<pre>
~/.../rosetta/asm4 $ subscipher64 input.txt output.txt E
Encoding/decoding OK.
~/.../rosetta/asm4 $ more input.txt
The quick brown fox jumps over the lazy dog, who barks VERY loudly!
~/.../rosetta/asm4 $ more output.txt
tFq oERJp wbQYh OQM AEDWL QSqb kFq nINT xQC, YFQ wIbpL PBZG nQExnT!
~/.../rosetta/asm4 $ subscipher64 output.txt outputdec.txt D
Encoding/decoding OK.
~/.../rosetta/asm4 $ more outputdec.txt
The quick brown fox jumps over the lazy dog, who barks VERY loudly!
</pre>
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Sequential_IO;
Line 69 ⟶ 334:
end if;
end Cipher;
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68">
BEGIN # subsitiution cipher #
# abcdefghijklmnopqrstuvwxyz #
STRING substitute lower = "dthnxkmqrwzseglyoaubjpcfiv";
STRING substitute upper = "TKXMGVUPOIRFDEJZNYWCAQSLBH";
# ABCDEFGHIJKLMNOPQRSTUVWXYZ #
 
PROC encrypt = ( STRING plain text )STRING:
BEGIN
PROC encode = ( CHAR c, base, STRING code )CHAR:
code[ ( ABS c - ABS base ) + LWB code ];
STRING result := plain text;
FOR pos FROM LWB result TO UPB result DO
CHAR c = result[ pos ];
IF c >= "A" AND c <= "Z" THEN
result[ pos ] := encode( c, "A", substitute upper )
ELIF c >= "a" AND c <= "z" THEN
result[ pos ] := encode( c, "a", substitute lower )
FI
OD;
result
END # encrypt # ;
 
PROC decrypt = ( STRING cipher text )STRING:
BEGIN
PROC decode = ( CHAR c, base, STRING code )CHAR:
BEGIN
INT c pos := 0;
char in string( c, c pos, code );
REPR ( ABS base + ( c pos - 1 ) )
END # decode # ;
STRING result := cipher text;
FOR pos FROM LWB result TO UPB result DO
CHAR c = result[ pos ];
IF c >= "A" AND c <= "Z" THEN
result[ pos ] := decode( c, "A", substitute upper )
ELIF c >= "a" AND c <= "z" THEN
result[ pos ] := decode( c, "a", substitute lower )
FI
OD;
result
END # decrypt # ;
 
PROC test cipher = ( STRING plain text )VOID:
IF STRING encoded = encrypt( plain text );
STRING decoded = decrypt( encoded );
print( ( plain text, " -> ", encoded, newline ) );
print( ( encoded, " -> ", decoded, newline ) );
decoded /= plain text
THEN
print( ( "**** encode/decode problem", newline ) )
FI # test cipher # ;
 
test cipher( "Sphinx of Black Quartz, judge my vow" );
test cipher( "ABCDEFGHIJKLMNOPQRSTUVWXYZzyxwvutsrqponmlkjihgfedcba" )
 
END
</syntaxhighlight>
{{out}}
<pre>
Sphinx of Black Quartz, judge my vow -> Wyqrgf lk Ksdhz Njdabv, wjnmx ei plc
Wyqrgf lk Ksdhz Njdabv, wjnmx ei plc -> Sphinx of Black Quartz, judge my vow
ABCDEFGHIJKLMNOPQRSTUVWXYZzyxwvutsrqponmlkjihgfedcba -> TKXMGVUPOIRFDEJZNYWCAQSLBHvifcpjbuaoylgeszwrqmkxnhtd
TKXMGVUPOIRFDEJZNYWCAQSLBHvifcpjbuaoylgeszwrqmkxnhtd -> ABCDEFGHIJKLMNOPQRSTUVWXYZzyxwvutsrqponmlkjihgfedcba
</pre>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program subscipher.s */
 
/************************************/
/* Constantes */
/************************************/
/* for constantes see task include a file in arm assembly */
.include "../constantes.inc"
.equ BUFFSIZE, 50000 @ buffer size
.equ READ, 3
.equ OPEN, 5
.equ CLOSE, 6
.equ CREATE, 8
.equ O_RDWR, 0x0002 @ open for reading and writing
 
/************************************/
/* Initialized data */
/************************************/
.data
szMessInst: .asciz "use : subscipher inputfile outpufile E (encryt) or D (decript).\n"
szMessCode: .asciz "Code operation not = E or D !!\n"
szMessErrorOpen: .asciz "Error open input file .\n"
szMessErrorCreate: .asciz "Error create output file.\n"
szMessErrorClose: .asciz "Error close file.\n"
szMessErrorRead: .asciz "Error read file.\n"
szMessErrorWrite: .asciz "Write error to output file.\n"
szMessTrtOK: .asciz "Encoding/decoding OK.\n"
szCarriageReturn: .asciz "\n"
// ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^ _`abcdefghijklmnopqrstuvwxyz
szBufferKey: .asciz "VsciBjedgrzyHalvXZKtUPumGf[\]^ _`IwJxqOCFRApnDhQWobLkESYMTN"
.equ LGBUFFERKEY, . - szBufferKey
/************************************/
/* UnInitialized data */
/************************************/
.bss
.align 4
iAdrFicInput: .skip 4
iAdrFicOutput: .skip 4
sBufferRead: .skip BUFFSIZE
sBufferWrite: .skip BUFFSIZE
/************************************/
/* code section */
/************************************/
.text
.global main
main:
mov fp,sp @ fp <- start address
ldr r4,[fp] @ number of Command line arguments
cmp r4,#4 @ test if number is ok
beq 1f
ldr r0,iAdrszMessInst @ no -> display error
bl affichageMess
b 100f
1:
ldr r6,[fp,#8] @ address input file name
ldr r10,[fp,#12] @ address output file name
ldr r5,[fp,#16] @ address code operation
ldrb r5,[r5] @ loaf first code character
cmp r5,#'E' @ control if code is OK
beq 2f
cmp r5,#'D'
beq 2f
ldr r0,iAdrszMessCode @ no -> display error
bl affichageMess
b 100f
2:
mov r0,r6 @ file name
mov r1,#O_RDWR @ flags
mov r2,#0 @ mode
mov r7,#OPEN @ call system OPEN
svc #0
cmp r0,#0 @ open error ?
ble 99f
mov r8,r0 @ save FD
// file read
ldr r1,iAdrsBufferRead @ buffer address
mov r2,#BUFFSIZE @ buffer size
mov r7, #READ @ call system READ
svc 0
cmp r0,#0 @ read error ?
ble 98f
mov r9,r0 @ length read characters
mov r0,r8 @ Fd
mov r7,#CLOSE @ call system CLOSE
svc 0
cmp r0,#0 @ close error ?
blt 97f
ldr r0,iAdrsBufferRead
mov r1,r9 @ length read characters
ldr r2,iAdrszBufferKey
mov r3,#LGBUFFERKEY
ldr r4,iAdrsBufferWrite
@ and r5 contains E or D
bl traitement
@ write output file
mov r0,r10 @ file output name
ldr r1,iFicMask1 @ flags
mov r7, #CREATE @ call system create file
svc 0
cmp r0,#0 @ create error ?
ble 96f
mov r8,r0 @ file descriptor
ldr r1,iAdrsBufferWrite
mov r2,r9 @ length read characters
mov r7, #WRITE @ select system call 'write'
svc #0 @ perform the system call
cmp r0,#0 @ error write ?
blt 95f
mov r0,r8 @ Fd output file
mov r7,#CLOSE @ call system CLOSE
svc 0
cmp r0,#0 @ close error ?
blt 97f
ldr r0,iAdrszMessTrtOK @ end message
bl affichageMess
b 100f
95: @ errors
ldr r0,iAdrszMessErrorWrite
bl affichageMess
b 100f
96:
ldr r0,iAdrszMessErrorCreate
bl affichageMess
b 100f
97:
ldr r0,iAdrszMessErrorClose
bl affichageMess
b 100f
98:
ldr r0,iAdrszMessErrorRead
bl affichageMess
b 100f
99:
ldr r0,iAdrszMessErrorOpen
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform the system call
 
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessInst: .int szMessInst
iAdrszMessCode: .int szMessCode
iAdrsBufferRead: .int sBufferRead
iAdrsBufferWrite: .int sBufferWrite
iAdrszBufferKey: .int szBufferKey
iAdrszMessErrorOpen: .int szMessErrorOpen
iAdrszMessErrorRead: .int szMessErrorRead
iAdrszMessErrorClose: .int szMessErrorClose
iAdrszMessErrorWrite: .int szMessErrorWrite
iAdrszMessErrorCreate: .int szMessErrorCreate
iAdrszMessTrtOK: .int szMessTrtOK
iFicMask1: .octa 0644
/******************************************************************/
/* encoding or decoding buffer */
/******************************************************************/
/* r0 contains input file address */
/* r1 contains length buffer */
/* r2 contanis key buffer address */
/* r3 contains key buffer length */
/* r4 contains output file address */
/* r5 contains code E or D */
traitement:
push {r6-r8,lr} @ save registres
cmp r5,#'D' @ code ?
beq decoding
mov r5,#0 @ init indice
1: @ loop read characters buffer
ldrb r6,[r0,r5] @ load une character
sub r6,#0x41 @ conv ascii -> numeric
cmp r6,#0 @ < A
blt 2f
cmp r6,#0x3A @ > z
bgt 2f
ldrb r7,[r2,r6] @ load key character at index
b 3f
2:
add r7,r6,#0x41 @ conv numeric -> ascii
3:
strb r7,[r4,r5] @ store encoded character in output buffer
add r5,r5,#1 @ increment indice
cmp r5,r1 @ end ?
ble 1b
b 100f
decoding:
mov r5,#0 @ init indice
4:
ldrb r6,[r0,r5] @ load one character
cmp r6,#0x41 @ < A
blt 6f
cmp r6,#0x7A @ > z
bgt 6f
mov r8,#0 @ init key indice
5:
ldrb r7,[r2,r8] @ load key character
cmp r7,r6 @ compare character
addeq r7,r8,#0x41 @ if equal convert indice to ascii
beq 7f
add r8,r8,#1 @ else increment key indice
cmp r8,r3 @ end key ?
ble 5b @ no -> loop
6:
mov r7,r6 @ move input character in output
7:
strb r7,[r4,r5] @ store decoded character in output buffer
add r5,r5,#1 @ increment indice
cmp r5,r1 @ end buffer ?
ble 4b
100:
pop {r6-r8,pc} @ restaur 2 registres
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../affichage.inc"
 
 
</syntaxhighlight>
{{Out}}
<pre>
~/.../rosetta/asm4 $ subscipher input.txt output.txt E
Encoding/decoding OK.
~/.../rosetta/asm4 $ more input.txt
test phrase AZ 1234 az
~/.../rosetta/asm4 $ more output.txt
kqLk WFbILq Vf 1234 IN
~/.../rosetta/asm4 $ subscipher output.txt outputdec.txt D
Encoding/decoding OK.
~/.../rosetta/asm4 $ more outputdec.txt
test phrase AZ 1234 az
</pre>
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">key: ---{:]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\C1yxJ---:}
encode: function [str][
bs: new []
loop split str 'ch ->
'bs ++ to :string key \ [(to :integer to :char ch)-32]
return join bs
]
Line 92 ⟶ 658:
enc: encode s
print ["encoded:" enc]
print ["decoded:" decode enc]</langsyntaxhighlight>
 
{{out}}
Line 98 ⟶ 664:
<pre>encoded: 2bu]E,KHm].Tdc|]4d\]),8M>]dQuT]<bu]U31C]Idf_]cbd].3Tm>]+ZzL]Ud,IUCk
decoded: The quick brown fox jumps over the lazy dog, who barks VERY loudly!</pre>
 
=={{Header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">
alfabeto := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
codebeto := "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
textToEncode := "Encrypt an input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file. This type of Encryption/Decryption scheme is often called a Substitution Cipher."
 
loop,parse,textToEncode
{
posit := InStr(alfabeto,a_loopfield,1)
if posit
textEncoded .= substr(codebeto,posit,1)
else
textEncoded .= A_LoopField
}
msgbox % "ENCODED TEXT: " . textEncoded
 
loop,parse,textEncoded
{
posit := InStr(codebeto,a_loopfield,1)
if posit
textDecoded .= substr(alfabeto,posit,1)
else
textDecoded .= A_LoopField
}
msgbox % "DECODED TEXT: " . textDecoded
ExitApp
 
~Esc::
ExitApp
</syntaxhighlight>
{{Out}}
<pre>
Substitution Cipher.ahk
---------------------------
ENCODED TEXT: BhJbTWk Ih RhWEk/LQEbJq ORnq wT bqWnIJRhC qSqbT EWWqb/nQYqb JILq InWFIwqkL QO kFq LQEbJq ORnq YRkF IhQkFqb WbqxqkqbDRhqx EWWqb/nQYqb JILq InWFIwqkL Qb LTDwQnL Ihx LISq Rk RhkQ IhQkFqb QEkWEk/qhJbTWkqx ORnq Ihx kFqh ICIRh JQhSqbk kFIk QEkWEk/qhJbTWkqx ORnq RhkQ QbRCRhIn/xqJbTWkqx ORnq. tFRL kTWq QO BhJbTWkRQh/iqJbTWkRQh LJFqDq RL QOkqh JInnqx I KEwLkRkEkRQh cRWFqb.
---------------------------
DECODED TEXT: Encrypt an input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file. This type of Encryption/Decryption scheme is often called a Substitution Cipher.
---------------------------
</pre>
 
=={{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">
<lang C>
#include<stdlib.h>
#include<stdio.h>
Line 166 ⟶ 772:
return 0;
}
</syntaxhighlight>
</lang>
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 254 ⟶ 860:
=={{header|C sharp}}==
 
<langsyntaxhighlight lang="csharp">using System;
using System.IO;
using System.Collections.Generic;
Line 397 ⟶ 1,003:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
The key file should look something like this: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789SWoVR0kJLXQ8zbCd1OagTH5ie3nvYU2wfrM9yI4sKm6c7hNjtADqFPxpEZlBuG
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <string>
Line 472 ⟶ 1,078:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight Dlang="d">import std.stdio;
import std.string;
import std.traits;
Line 504 ⟶ 1,110:
auto decode(string input) {
return tr(input, REVERSE, FORWARD);
}</langsyntaxhighlight>
{{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 516 ⟶ 1,122:
type of Encryption/Decryption scheme is often called a
Substitution Cipher.</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
alpha$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
key$ = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
#
proc subst in$ . out$ a$ b$ .
out$ = ""
for c$ in strchars in$
p = strpos a$ c$
if p > 0
c$ = substr b$ p 1
.
out$ &= c$
.
.
func$ enc s$ .
subst s$ r$ alpha$ key$
return r$
.
func$ dec s$ .
subst s$ r$ key$ alpha$
return r$
.
c$ = enc "Hello world"
print c$
print dec c$
</syntaxhighlight>
 
{{out}}
<pre>
dqnnQ YQbnx
Hello world
</pre>
 
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">
(setq alphabet "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
(setq code "odrmqbjnwzvueghlacyfpktisxODRMQBJNWZVUEGHLACYFPKTISX")
 
(defun encode (text)
"Encode TEXT with simple substitution code.
Each letter is replaced with the a random letter.
A specific letter in the original will always be replaced
by the same coded letter."
(let* ((case-fold-search nil)
(text-length (length text))
(encoded-text "")
(current-letter "")
(coded-letter "")
(alphabet-position))
(dotimes (i text-length)
(setq current-letter (substring text i (+ 1 i))) ; find the next letter in TEXT
(if (not (string-match-p "[a-zA-Z]" current-letter)) ; IF it's not a letter
(setq coded-letter current-letter) ; pass the non-letter without change
(setq alphabet-position (string-match current-letter alphabet)) ; ELSE find where the letter is in ALPHABET
(setq coded-letter (substring code alphabet-position (+ 1 alphabet-position)))) ; AND pass the coded letter
(setq encoded-text (concat encoded-text coded-letter))) ; IN ANY CASE, add new letter to ENCODED-TEXT
encoded-text))
 
(defun decode (text)
"Decode TEXT encoded with simple substitution code.
Each coded letter is replaced with the corresponding
uncoded letter."
(let* ((case-fold-search nil)
(text-length (length text))
(uncoded-text "")
(current-letter "")
(uncoded-letter "")
(code-position))
(dotimes (i text-length)
(setq current-letter (substring text i (+ 1 i))) ; find the next letter in TEXT
(if (not (string-match-p "[a-zA-Z]" current-letter)) ; IF it's not a letter
(setq uncoded-letter current-letter) ; pass the non-letter without change
(setq code-position (string-match current-letter code)) ; ELSE find where the letter is in CODE
(setq uncoded-letter (substring alphabet code-position (+ 1 code-position)))) ; AND pass the uncoded letter
(setq uncoded-text (concat uncoded-text uncoded-letter))) ; IN ANY CASE, add new letter to UNCODED-TEXT
uncoded-text))
 
</syntaxhighlight>
 
{{out}}
(encode "Call me Ishmael. Some years ago—never mind how long precisely—having
little or no money in my purse, and nothing particular to interest me
on shore, I thought I would sail about a little and see the watery part
of the world. ")
<pre>
"Rouu eq Wyneoqu. Yheq sqocy ojh—gqkqc ewgm nht uhgj lcqrwyqus—nokwgj
uwffuq hc gh ehgqs wg es lpcyq, ogm ghfnwgj locfwrpuoc fh wgfqcqyf eq
hg ynhcq, W fnhpjnf W thpum yowu odhpf o uwffuq ogm yqq fnq tofqcs locf
hb fnq thcum. "
</pre>
(decode "Rouu eq Wyneoqu. Yheq sqocy ojh—gqkqc ewgm nht uhgj lcqrwyqus—nokwgj
uwffuq hc gh ehgqs wg es lpcyq, ogm ghfnwgj locfwrpuoc fh wgfqcqyf eq
hg ynhcq, W fnhpjnf W thpum yowu odhpf o uwffuq ogm yqq fnq tofqcs locf
hb fnq thcum. ")
<pre>
"Call me Ishmael. Some years ago—never mind how long precisely—having
little or no money in my purse, and nothing particular to interest me
on shore, I thought I would sail about a little and see the watery part
of the world. "
</pre>
 
 
=={{header|Factor}}==
This program optionally allows the user to specify a file to use as a key. Otherwise, it uses a default.
<langsyntaxhighlight lang="factor">USING: assocs combinators combinators.short-circuit command-line
hashtables io io.encodings.utf8 io.files kernel math.order
multiline namespaces qw sequences ;
Line 569 ⟶ 1,279:
command-line get dup check-args [ substitute ] [ drop ] if ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
Contents of key.txt:
Line 614 ⟶ 1,324:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program substitution
implicit none
 
Line 707 ⟶ 1,417:
end subroutine
 
end program </langsyntaxhighlight>
{{out}}
<pre>
Line 728 ⟶ 1,438:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' uses same alphabet and key as Ada language example
Line 767 ⟶ 1,477:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 802 ⟶ 1,512:
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 832 ⟶ 1,542:
fmt.Println("Encoded: ", enc)
fmt.Println("Decoded: ", decode(enc))
}</langsyntaxhighlight>
 
{{out}}
Line 841 ⟶ 1,551:
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "SuChiper.bas"
110 STRING ST$(1 TO 2)*52,K$*1
120 LET ST$(1)="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 893 ⟶ 1,603:
600 PRINT EXSTRING$(EXTYPE)
610 END
620 END HANDLER</langsyntaxhighlight>
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Char (chr)
import Data.Maybe (fromMaybe)
import Data.Tuple (swap)
Line 930 ⟶ 1,640:
 
main :: IO ()
main = parseArgs <$> getArgs >>= putStrLn . runCommand</langsyntaxhighlight>
{{out}}
<pre>$ simplecipher c "The quick brown fox jumped over the lazy dogs."
Line 942 ⟶ 1,652:
Example implementation:
 
<langsyntaxhighlight Jlang="j">keysubst=: [`(a.i.])`(a."_)}
key=: 'Taehist' keysubst '!@#$%^&'
enc=: a. {~ key i. ]
Line 950 ⟶ 1,660:
!$%^ %^ @ &#^&.
dec '!$%^ %^ @ &#^&.'
This is a test.</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang="java">public class SubstitutionCipher {
 
final static String key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"
Line 992 ⟶ 1,702:
return sb.toString();
}
}</langsyntaxhighlight>
 
<pre>Encoded: "uTu]cu]b3Qu]<d]Id]...><K<,<Kd|]6KMbuTi
Decoded: Here we have to do is... Substitution Cipher.</pre>
 
=={{header|jq}}==
{{trans|Wren}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<syntaxhighlight lang="jq">def key:
"]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";
 
def encode:
(key|explode) as $key
| explode as $exploded
| reduce range(0;length) as $i ([];
. + [$key[ $exploded[$i] - 32]] )
| implode;
def decode:
(key|explode) as $key
| explode as $exploded
| reduce range(0;length) as $i ([];
$exploded[$i] as $c
| . + [ $key | index($c) + 32] )
| implode ;
 
def task:
"The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
| encode as $encoded
|"Encoded: \($encoded)",
"Decoded: \($encoded|decode)" ;
 
task</syntaxhighlight>
{{out}}
<pre>
Encoded: 2bu]E,KHm].Tdc|]4d\]),8M>]dQuT]<bu]U31C]Idf_]cbd].3Tm>]+ZzL]Ud,IUCk
Decoded: The quick brown fox jumps over the lazy dog, who barks VERY loudly!
</pre>
 
 
=={{header|Julia}}==
Line 1,002 ⟶ 1,748:
 
'''Module''':
<langsyntaxhighlight lang="julia">module SubstitutionCiphers
 
using Compat
Line 1,024 ⟶ 1,770:
end
 
end # module SubstitutionCiphers</langsyntaxhighlight>
 
'''Main''':
<langsyntaxhighlight lang="julia">let s = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
enc = SubstitutionCiphers.encode(s)
dec = SubstitutionCiphers.decode(enc)
println("Original: ", s, "\n -> Encoded: ", enc, "\n -> Decoded: ", dec)
end</langsyntaxhighlight>
 
{{out}}
Line 1,039 ⟶ 1,785:
 
=={{header|Klingphix}}==
<syntaxhighlight lang="text">include ..\Utilitys.tlhy
 
" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 1,062 ⟶ 1,808:
false Encode ?
 
" " input</langsyntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.0.6
 
object SubstitutionCipher {
Line 1,089 ⟶ 1,835:
println("Encoded: $enc")
println("Decoded: ${SubstitutionCipher.decode(enc)}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,100 ⟶ 1,846:
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.
 
<langsyntaxhighlight lang="scheme">
 
{def small_ascii {S.map fromCharCode {S.serie 33 122}}}
Line 1,155 ⟶ 1,901:
Pharnaces II of Pontus at the Battle of Zela.
 
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Generate a random substitution cipher for ASCII characters 65 to 122
function randomCipher ()
local cipher, rnd = {plain = {}, encoded = {}}
Line 1,208 ⟶ 1,954:
print("\t" .. encoded)
print("\nAbove text deciphers to: ")
print("\t" .. encode(encoded, subCipher, true))</langsyntaxhighlight>
{{out}}
<pre>Cipher generated:
Line 1,229 ⟶ 1,975:
crypted file into original/decrypted file. This type of Encryption/Decryption sc
heme is often called a Substitution Cipher.</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">SeedRandom[1234];
a=Characters@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
map=Thread[a->RandomSample[a]];
ClearAll[SubstitutionCipherEncode,SubstitutionCipherDecode]
SubstitutionCipherEncode[input_String,map_]:=StringReplace[input,map]
SubstitutionCipherDecode[input_String,map_]:=StringReplace[input,Reverse/@map]
 
str="The quick brown fox jumps over the lazy dog,who barks VERY loudly!";
encoded=SubstitutionCipherEncode[str,map]
decoded=SubstitutionCipherDecode[encoded,map]
str===decoded</syntaxhighlight>
{{out}}
<pre>"DebTyUsLNTg2H01TWHSTfUt5qTHZb2T7ebTl4 8TQHc,0eHTg42NqTuK6CTlHUQl8!"
"The quick brown fox jumps over the lazy dog,who barks VERY loudly!"
True</pre>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">alphabet = "abcdefghijklmnopqrstuvwxyz".split("")
cipher = alphabet[0:]
cipher.shuffle
Line 1,254 ⟶ 2,017:
secretCode = apply(encode, msg)
print secretCode
print apply(decode, secretCode)</langsyntaxhighlight>
{{out}}
<pre>Rzs ho wft whxt bzv ykk nzzg xtr (yrg szxtr) wz jzxt wzntwftv.
Now is the time for all good men (and women) to come together.</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import sequtils, strutils
 
proc encrypt(key: seq[char]; msg: string): string =
result.setLen(msg.len)
for i, c in msg:
result[i] = key[ord(c) - 32]
 
proc decrypt(key: seq[char]; msg: string): string =
result.setLen(msg.len)
for i, c in msg:
result[i] = chr(key.find(c) + 32)
 
when isMainModule:
 
import random
randomize()
 
# Build a random key.
var key = toSeq(32..126).mapIt(chr(it)) # All printable characters.
key.shuffle()
 
const Message = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
let encrypted = key.encrypt(Message)
let decrypted = key.decrypt(encrypted)
 
echo "Key = “$#”" % key.join()
echo "Message = “$#”" % Message
echo "Encrypted = “$#”" % encrypted
echo "Decrypted = “$#”" % decrypted</syntaxhighlight>
 
{{out}}
<pre>Key = “5`:S<UqJ& aCwQ?lA_bp"dEv*,'@c$;=FG}o8x\.s-MPrTu~L>[i1N(9Z^h/e#4Hjn]WBXYy7Dg3O+26fKIm|)zkt{R%!0V”
Message = “The quick brown fox jumps over the lazy dog, who barks VERY loudly!”
Encrypted = “17X5K)DW35]I6k25Y6t5g)+fm56zXI5|7X5OnR{5B6yw5k765]nI3m5(x[^5O6)BO{`”
Decrypted = “The quick brown fox jumps over the lazy dog, who barks VERY loudly!”</pre>
 
=={{header|Perl}}==
{{trans|Java}}
<langsyntaxhighlight lang="perl">sub encode {
my $source = shift;
my $key = shift;
Line 1,303 ⟶ 2,103:
 
my $pt = decode($ct, $key);
print "Decoded: $pt\n";</langsyntaxhighlight>
{{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,309 ⟶ 2,109:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant plain = tagset('Z','A')&tagset('z','a'),
<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>
key = shuffle(plain)
<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>
 
function encode(string s, integer decrypt=false)
sequence {p,k} = iff(decrypt?{plain,key}:{key,plain})
for i=1 to length(s) do
integer ki = find(s[i],p)
if ki then s[i] = k[ki] end if
end for
return s
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">encode</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">decrypt</span><span style="color: #0000FF;">=</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
string original = "A simple example.",
<span style="color: #004080;">sequence</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">decrypt</span><span style="color: #0000FF;">?{</span><span style="color: #000000;">plain</span><span style="color: #0000FF;">,</span><span style="color: #000000;">key</span><span style="color: #0000FF;">}:{</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">plain</span><span style="color: #0000FF;">})</span>
encoded = encode(original),
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
decoded = encode(encoded, true)
<span style="color: #004080;">integer</span> <span style="color: #000000;">ki</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">if</span> <span style="color: #000000;">ki</span> <span style="color: #008080;">then</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ki</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
printf(1,"original: %s\nencoded: %s\ndecoded: %s\n",{original,encoded,decoded})</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">original</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"A simple example."</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">encoded</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">encode</span><span style="color: #0000FF;">(</span><span style="color: #000000;">original</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">decoded</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">encode</span><span style="color: #0000FF;">(</span><span style="color: #000000;">encoded</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">true</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;">"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>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 1,334 ⟶ 2,136:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 1,355 ⟶ 2,157:
dup ?
true Encode dup ?
false Encode ?</langsyntaxhighlight>
{{out}}
<pre>A simple example
Line 1,365 ⟶ 2,167:
=={{header|PHP}}==
 
<langsyntaxhighlight PHPlang="php"><?php
 
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
Line 1,383 ⟶ 2,185:
$encoded, PHP_EOL, PHP_EOL,
'== DECODED ==', PHP_EOL,
$decoded, PHP_EOL, PHP_EOL;</langsyntaxhighlight>
 
{{out}}
Line 1,418 ⟶ 2,220:
 
This type of Encryption/Decryption scheme is often called a Substitution Cipher.</pre>
 
=={{header|Picat}}==
{{trans|Prolog}}
<syntaxhighlight lang="picat">main =>
S = "The quick brown fox jumped over the lazy dog",
cypher(S,E), % encrypt
println(E),
 
cypher(D, E), % decrypt
println(D),
 
S == D,
println(ok).
 
cypher(O, S) :-
nonvar(O),
var(S),
sub_chars(O,S).
cypher(O, S) :-
nonvar(S),
var(O),
sub_chars(O,S).
 
base("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ").
subs("VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWob LkESYMTN").
sub_chars(Original,Subbed) :-
base(Base),
subs(Subs),
maplist($sub_char(Base,Subs),Original,Subbed).
 
sub_char([Co|_],[Cs|_],Co,Cs) :- !.
sub_char([_|To],[_|Ts], Co, Cs) :- sub_char(To,Ts,Co,Cs).
 
maplist(Goal, List1, List2) :-
maplist_(List1, List2, Goal).
 
maplist_([], X, _) :- X = [].
maplist_([Elem1|Tail1],
[Elem2|Tail2],
Goal) :-
call(Goal, Elem1, Elem2),
maplist_(Tail1, Tail2, Goal).</syntaxhighlight>
 
{{out}}
<pre>tFqNokRJpNwbQShNOQYNAkDWqxNQEqbNLFqNnITMNxQC
The quick brown fox jumped over the lazy dog
ok</pre>
 
===Using maps===
<syntaxhighlight lang="picat">main =>
S = "The quick brown fox jumped over the lazy dog!!!",
E = encrypt(S),
println(E),
D = decrypt(E),
println(D),
 
D == S,
println(ok),
nl.
 
encrypt(L) = [EncryptMap.get(C,C) : C in L] =>
base(Base),
subs(Subs),
EncryptMap = new_map([B=S : {B,S} in zip(Base,Subs)]).
 
decrypt(L) = [DecryptMap.get(C,C) : C in L] =>
base(Base),
subs(Subs),
DecryptMap = new_map([S=B : {B,S} in zip(Base,Subs)]).
 
base("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ").
subs("VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWob LkESYMTN").</syntaxhighlight>
 
{{out}}
<pre>tFqNokRJpNwbQShNOQYNAkDWqxNQEqbNLFqNnITMNxQC!!!
The quick brown fox jumped over the lazy dog!!!
ok</pre>
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(setq *A (chop "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"))
(setq *K (chop "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"))
 
Line 1,438 ⟶ 2,319:
(and
(println 'encode (cipher "The quick brown fox jumped over the lazy dog's back"))
(println 'decode (cipher @ T)) )</langsyntaxhighlight>
{{out}}
<pre>encode "tFq oERJp wbQYh OQM AEDWqx QSqb kFq nINT xQC'L wIJp"
decode "The quick brown fox jumped over the lazy dog's back"</pre>
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string key = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN";
mapping key_mapping = mkmapping(alphabet/1, key/1);
object c = Crypto.Substitution()->set_key(key_mapping);
 
string msg = "The quick brown fox jumped over the lazy dogs";
string msg_enc = c->encrypt(msg);
string msg_dec = c->decrypt(msg_enc);
 
write("Encrypted: %s\n", msg_enc);
write("Decrypted: %s\n", msg_dec);</syntaxhighlight>
 
{{out}}
<pre>
Encrypted: tFq oERJp wbQYh OQM AEDWqx QSqb kFq nINT xQCL
Decrypted: The quick brown fox jumped over the lazy dogs
</pre>
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">cypher(O, S) :-
nonvar(O),
var(S),
Line 1,467 ⟶ 2,367:
sub_char([Co|_],[Cs|_],Co,Cs) :- !.
sub_char([_|To],[_|Ts], Co, Cs) :- sub_char(To,Ts,Co,Cs).</langsyntaxhighlight>
{{out}}
<pre>
Line 1,479 ⟶ 2,379:
 
=={{header|Python}}==
<syntaxhighlight lang="python">
<lang Python>
from string import printable
import random
Line 1,498 ⟶ 2,398:
Gives: {}
Decoding it by the same key gives: {}""".format(
original, EXAMPLE_KEY, encoded, decoded))</langsyntaxhighlight>
 
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,508 ⟶ 2,408:
Gives:
iPMhX\YiYmJhX\Y5
Decoding it by the same key gives: A simple example.</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ stack ] is encryption ( --> s )
[ stack ] is decryption ( --> s )
 
[ [] 95 times [ i^ join ]
shuffle encryption put ] is makeencrypt ( --> )
 
[ encryption share
0 95 of swap
witheach
[ i^ unrot poke ]
decryption put ] is makedecrypt ( --> )
 
[ makeencrypt makedecrypt ] is makekeys ( --> )
 
[ witheach [ char ! + emit ] ] is echokey ( s --> )
[ encryption release
decryption release ] is releasekeys ( --> )
 
[ [] swap witheach
[ dup char ! char ~ 1+
within if
[ char ! -
encryption share
swap peek char ! + ]
join ] ] is encrypt ( $ --> $ )
 
[ [] swap witheach
[ dup char ! char ~ 1+
within if
[ char ! -
decryption share
swap peek char ! + ]
join ] ] is decrypt ( $ --> $ )
 
randomise
makekeys
say "Encryption key is: " encryption share echokey cr
say "Decryption key is: " decryption share echokey cr
cr
$ "Encryption matters, and it is not just for spies and philanderers."
say "Plaintext: " dup echo$ cr
say "Encrypted: " encrypt dup echo$ cr
say "Decrypted: " decrypt echo$ cr
releasekeys</syntaxhighlight>
 
{{out}}
 
<pre>Encryption key is: [;s]_O*FmypB&\5Ro:/Xzi9gau6qrdV@-.0EI|8K(lZwjh31=v2+,P$e{f'#"!NTGx?kCb~<Mt%cHY}UJ7>W`SA)D^n4?LQ
Decryption key is: ^]\Wk-[Ix'TUAB3CPSO|/;rG72"hQsc@w,eyD(amEqH~i_&V?0v`p?t4nK!.$z%u9fl>XZ8N6MdJ){1+<=#j:RLb*5YFog}
 
Plaintext: Encryption matters, and it is not just for spies and philanderers.
Encrypted: IY?7DUWM}Y HGWWC7>B GYk MW M> Y}W t`>W b}7 >UMC> GYk U<McGYkC7C7>\
Decrypted: Encryption matters, and it is not just for spies and philanderers.</pre>
 
=={{header|Racket}}==
Line 1,517 ⟶ 2,474:
so I don't display the plaintext in the output.
 
<langsyntaxhighlight lang="racket">#lang racket/base
(require racket/list racket/function racket/file)
 
Line 1,571 ⟶ 2,528:
(displayln (file->string "data/substitution.crypt.txt"))
(check-equal? (file->string "data/substitution.in.txt")
(file->string "data/substitution.plain.txt")))</langsyntaxhighlight>
 
{{out}}
Line 1,595 ⟶ 2,552:
{{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" perl6line>my $chr = (' ' .. '}').join('');
my $key = $chr.comb.pick(*).join('');
 
Line 1,630 ⟶ 2,587:
sub encode ($text) { $text.trans($chr => $key) }
 
sub decode ($text) { $text.trans($key => $chr) }</langsyntaxhighlight>
{{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,660 ⟶ 2,617:
::* &nbsp; the two records should be equal in the number of characters.
::* &nbsp; the N<sup>th</sup> character of record &nbsp; '''1''' &nbsp; will be encrypted to the N<sup>th</sup> character of record &nbsp; '''2'''.
<langsyntaxhighlight lang="rexx">/*REXX program implements & demonstrates a substitution cipher for the records in a file*/
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,700 ⟶ 2,657:
say @in ' records processed: ' j /*show the number of records processed.*/
call closer /*close all the files to be neat & safe*/
return</langsyntaxhighlight>
'''output''' &nbsp; when using the default input files:
<pre>
Line 1,753 ⟶ 2,710:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Substitution Cipher
 
Line 1,802 ⟶ 2,759:
next
return str
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,810 ⟶ 2,767:
Encoded : SIAA ZQ LKBA. VA ZOA RFPBLUAOAR!
Decoded : flee at once. we are discovered!
</pre>
 
=={{header|RISC-V Assembly}}==
<syntaxhighlight lang="risc-v">
# gnu assembler syntax
substitution_cipher: # char* str (a0), uint len (a1), const char lowerkey[26] (a2), const char upperkey[26] (a3)
# set up temporary registers t0, t1, t2, t3
li t0, 'a
li t1, 'z
li t2, 'A
li t3, 'Z
# char tmp (t4)
# char* cipher (t5)
 
.dcB: # begin loop
beqz a1, .dcE # break condition
lb t4, 0(a0) # load one character from a0
blt t4, t0, .dcU # lowercase check
bgt t4, t1, .dcI
addi t4, t4, -'a
mv t5, a2
j .dcA
.dcU: # uppercase check
blt t4, t2, .dcI
bgt t4, t3, .dcI
addi t4, t4, -'A
mv t5, a3
.dcA: # convert and save ciphertext character
add t5, t5, t4
lb t5, 0(t5)
sb t5, 0(a0)
.dcI: # increment registers
addi a1, a1, -1
addi a0, a0, 1
j .dcB
.dcE: ret # end loop
 
# You can use the following cipher keys, which correspond to the Atbash cipher,
# to test the substitution. These keys are self-inverse, which means that
# applying them twice to a given plaintext yields the original plaintext again.
latbash: .ascii "zyxwvutsrqponmlkjihgfedcba"
uatbash: .ascii "ZYXWVUTSRQPONMLKJIHGFEDCBA"
 
# For keys that are non-self-inverse, you will need to keep a separate set of
# encryption and decryption keys.
lzebras: .ascii "zebrascdfghijklmnopqtuvwxy"
uzebras: .ascii "ZEBRASCDFGHIJKLMNOPQTUVWXY"
ldzebras: .ascii "ecghbijklmnopqrstdfuvwxyza"
udzebras: .ascii "ECGHBIJKLMNOPQRSTDFUVWXYZA"
</syntaxhighlight>
 
=={{header|RPL}}==
"]kYV}(!7P\$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\πv*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"
'CipherKey' STO
« ""
1 3 PICK SIZE '''FOR''' j
OVER j DUP SUB NUM 31 -
CipherKey SWAP DUP SUB +
'''NEXT''' SWAP DROP
» '<span style="color:blue">→CIPHER</span>' STO
« ""
1 3 PICK SIZE '''FOR''' j
OVER j DUP SUB
CipherKey SWAP POS 31 + CHR +
'''NEXT''' SWAP DROP
» '<span style="color:blue">CIPHER→</span>' STO
« "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
<span style="color:blue">→CIPHER</span> DUP <span style="color:blue">CIPHER→</span>
» '<span style="color:blue">TASK</span>' STO
{{out}}
<pre>
2: "2bu]E,KHm].Tdc|]4d\]),8M>]dQuT]<bu]U31C]Idf_]cbd].3Tm>]+ZzL]Ud,IUCk"
1: "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
</pre>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Key = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
 
def encrypt(str) = str.tr(Alphabet, Key)
def decrypt(str) = str.tr(Key, Alphabet)
str = 'All is lost, he thought. Everything is ruined. It’s ten past three.'
p encrypted = encrypt(str)
p decrypt(encrypted)
</syntaxhighlight>
{{out}}
<pre>"Vnn RL nQLk, Fq kFQECFk. BSqbTkFRhC RL bERhqx. gk’L kqh WILk kFbqq."
"All is lost, he thought. Everything is ruined. It’s ten past three."
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object SubstitutionCipher extends App {
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 1,842 ⟶ 2,891:
sb.toString
}
}</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="ruby">module SubstitutionCipher {
 
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 1,873 ⟶ 2,922:
var dec = SubstitutionCipher::decode(enc)
say("Original: ", s, "\n -> Encoded: ", enc, "\n -> Decoded: ", dec)
}</langsyntaxhighlight>
{{out}}
<pre>Original: The quick brown fox jumps over the lazy dog, who barks VERY loudly!
Line 1,889 ⟶ 2,938:
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.
 
<langsyntaxhighlight Tcllang="tcl">oo::class create SubCipher {
variable Alphabet
variable Key
Line 1,947 ⟶ 2,996:
string map $DecMap $s
}
}</langsyntaxhighlight>
 
Testing looks like this:
 
<langsyntaxhighlight Tcllang="tcl">SubCipher create sc
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"</langsyntaxhighlight>
 
{{out}}
Line 1,995 ⟶ 3,044:
GuLFvXQVKRNjwnhyozmZDOlcJBTbfCWdMkxqprtgIasUHeAiESYP
----
</pre>
 
=={{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
dim key(94)
 
a="I'm working on modernizing Rosetta Code's infrastructure. Starting with communications."&_
" Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)"
 
sub gen 'swaps items not previusly affected by a swap
dim i,m,t
for i=0 to ubound(key)
key(i)=i+32
next
for i=0 to ubound(key)-1
if key(i)=i+32 then
m=i+int(rnd*(maxk-i))
if key(m)=m+32 then
t=key(m):key(m)=key(i):key(i)=t
end if
end if
next
end sub
 
function viewkey
dim i,b
b=""
for i=1 to ubound(key)
b=b&chr(key(i))
next
viewkey=b
end function
 
function iif(a,b,c) if a then iif=b else iif =c end if: end function
 
function docode(a)
dim b,i,ch,n
n=maxk+32
b=""
for i=1 to len(a)
ch=asc(mid(a,i,1))
'wscript.echo ch
b=b&chr(key(iif (ch>n or ch<32,0,ch-32)))
next
docode=b
end function
 
randomize timer
dim a,b,c
gen
wscript.echo "Key: " & viewkey & vbcrlf
wscript.echo "Original: " & a & Vbcrlf
b=docode(a)
wscript.echo "Encoded: "& b & Vbcrlf
c=docode(b)
wscript.echo "Decoded: " & c & Vbcrlf
wscript.quit(0)
</syntaxhighlight>
{{out}}
<pre>
Key: %Fh.!\Zc)9Q[4$vaJ2W-65=`*:p<7>I@RBC Y"]H?1XLlnOP+AxVUT3KE',&G|_80t(dgfe#kjiMmNo;qwybu/rSsz{^}~
 
Original: I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)
 
Encoded: ?ZmDrowikNeDoNDmodgwNkzkNeDAoygbb0DCodgZyDkNfw0ybwu(buwg$Dxb0wbkNeDrkb#D(ommuNk(0bkoNy$DPMg0ygD0((g;bDb#kyDbkmg4MkmkbgdDo;gNDkN/kbgDboDACZyDxM0(i$$D44lk(#0gMDloMDcb0Mi)D2a:6*[DWaDl0sD2a2aDcUVC)
 
Decoded: I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Kotlin}}
<syntaxhighlight lang="v (vlang)">
const
(
key = "]kYV}(!7P\$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"
text = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
)
 
fn main() {
encoded := encode(text)
println(encoded)
println(decode(encoded))
}
 
fn encode(str string) string {
mut chr_arr := []u8{}
for chr in str {
chr_arr << key[u8(chr - 32)]
}
return chr_arr.bytestr()
}
 
fn decode(str string) string {
mut chr_arr := []u8{}
for chr in str {
chr_arr << u8(key.index_u8(chr) + 32)
}
return chr_arr.bytestr()
}
</syntaxhighlight>
 
{{out}}
<pre>
2bu]E,KHm].Tdc|]4d\]),8M>]dQuT]<bu]U31C]Idf_]cbd].3Tm>]+ZzL]Ud,IUCk
The quick brown fox jumps over the lazy dog, who barks VERY loudly!
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">var key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6\%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"
 
var encode = Fn.new { |s|
Line 2,016 ⟶ 3,173:
var enc = encode.call(s)
System.print("Encoded: %(enc)")
System.print("Decoded: %(decode.call(enc))")</langsyntaxhighlight>
 
{{out}}
Line 2,025 ⟶ 3,182:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">class SubstitutionCipher{
// 92 characters: " !"#$%&" ... "xyz{|}", doesn't include "~"
const KEY="]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"
Line 2,031 ⟶ 3,188:
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 } }) }
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">text:="Here we have to do is there will be a input/source "
"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,042 ⟶ 3,199:
encoded:=SubstitutionCipher.encode(text);
println( "Encoded: ",encoded);
println("\nDecoded: ",SubstitutionCipher.decode(encoded));</langsyntaxhighlight>
{{out}}
<pre>
26

edits