Substitution cipher

From Rosetta Code
(Redirected from Substitution Cipher)
Task
Substitution cipher
You are encouraged to solve this task according to the task description, using any language you may know.

Substitution Cipher Implementation - File Encryption/Decryption


Task

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.


Related tasks


See also



11l

Translation of: Kotlin
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))
Output:
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!

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
or android 64 bits with application Termux
/* 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"
Output:
~/.../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!

Ada

with Ada.Command_Line; use Ada.Command_Line;
with Ada.Sequential_IO;
with Ada.Strings.Maps; use Ada.Strings.Maps;
with Ada.Text_IO;

procedure Cipher is
   package Char_IO is new Ada.Sequential_IO (Character);
   use Char_IO;
   Alphabet: constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
   Key :     constant String := "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN";
   My_Map : Character_Mapping;
   Input, Output : File_Type;
   Buffer        : Character;
begin
   declare
      use Ada.Text_IO;
   begin
      if Argument_Count /= 1 then
	 Put_Line("Usage: " & Command_Name & " <encode|decode>");
      else
	 if Argument(1) = "encode" then
	    My_Map := To_Mapping(From => Alphabet, To => Key);
	 elsif Argument(1) = "decode" then
	    My_Map := To_Mapping(From => Key, To => Alphabet);
	 else
	    Put_Line("Unrecognised Argument: " & Argument(1));
	    return;
	 end if;
      end if;
   end;
   Open       (File => Input,  Mode => In_File,  Name => "input.txt");
   Create     (File => Output, Mode => Out_File, Name => "output.txt");
   loop
      Read  (File => Input,  Item => Buffer);
      Buffer := Value(Map => My_Map, Element => Buffer);
      Write (File => Output, Item => Buffer);
   end loop;
exception
   when Char_IO.End_Error =>
      if Is_Open(Input) then
         Close (Input);
      end if;
      if Is_Open(Output) then
         Close (Output);
      end if;
end Cipher;

ARM Assembly

Works with: as version Raspberry Pi
or android 32 bits with application Termux
/* 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"
Output:
~/.../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

Arturo

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
]

decode: function [str][
    bs: new []
    loop split str 'ch ->
        'bs ++ to :string to :char (index key ch)+32
    return join bs
]

s: "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"

enc: encode s
print ["encoded:" enc]
print ["decoded:" decode enc]
Output:
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!

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
Output:
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.
---------------------------

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 NSA like, use whatever string you want as long as it has a d/D or e/E in front.

#include<stdlib.h>
#include<stdio.h>
#include<wchar.h>

#define ENCRYPT 0
#define DECRYPT 1
#define ALPHA 33
#define OMEGA 126

int wideStrLen(wchar_t* str){
	int i = 0;
	while(str[i++]!=00);
	
	return i;
}

void processFile(char* fileName,char plainKey, char cipherKey,int flag){
	
	FILE* inpFile = fopen(fileName,"r");
	FILE* outFile;
	
	int i,len, diff = (flag==ENCRYPT)?(int)cipherKey - (int)plainKey:(int)plainKey - (int)cipherKey;
	wchar_t str[1000], *outStr;
	char* outFileName = (char*)malloc((strlen(fileName)+5)*sizeof(char));

	sprintf(outFileName,"%s_%s",fileName,(flag==ENCRYPT)?"ENC":"DEC");
	
	outFile = fopen(outFileName,"w");
	
	while(fgetws(str,1000,inpFile)!=NULL){
		len = wideStrLen(str);
		
		outStr = (wchar_t*)malloc((len + 1)*sizeof(wchar_t));
		
		for(i=0;i<len;i++){
			if((int)str[i]>=ALPHA && (int)str[i]<=OMEGA && flag == ENCRYPT)
				outStr[i] = (wchar_t)((int)str[i]+diff);
			 else if((int)str[i]-diff>=ALPHA && (int)str[i]-diff<=OMEGA && flag == DECRYPT)
				outStr[i] = (wchar_t)((int)str[i]-diff);
			else
				outStr[i] = str[i];
		}
		outStr[i]=str[i];
		
		fputws(outStr,outFile);
		
		free(outStr);
	}
	
	fclose(inpFile);
	fclose(outFile);
}

int main(int argC,char* argV[]){
	if(argC!=5)
		printf("Usage : %s <file name, plain key, cipher key, action (E)ncrypt or (D)ecrypt>",argV[0]);
	else{
		processFile(argV[1],argV[2][0],argV[3][0],(argV[4][0]=='E'||argV[4][0]=='e')?ENCRYPT:DECRYPT);
		
		printf("File %s_%s has been written to the same location as input file.",argV[1],(argV[4][0]=='E'||argV[4][0]=='e')?"ENC":"DEC");
	}
	
	return 0;
}

A long, long time ago ( yes, 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 read the copy on archive.org, it's there on the last line of page 30/31, Biggleman's Safe.


So here it is, a program which encrypts itself, you saw the cleartext file above, now here's the invocation and ciphertext file.

C:\rosettaCode>biggleman.exe substitutionCipher.c a e E
File substitutionCipher.c_ENC has been written to the same location as input file.

And here's what substitutionCipher.c_ENC looks like :

3.Eflmwlio Klswl0 55xl Sgxsfiv 645;.3

'mrgpyhi@wxhpmf2lB
'mrgpyhi@wxhms2lB
'mrgpyhi@{glev2lB

'hijmri IRGV]TX 4
'hijmri HIGV]TX 5
'hijmri EPTLE 77
'hijmri SQIKE 56:

mrx {mhiWxvPir,{glevcx. wxv-�
	mrx m A 4?
	{lmpi,wxv_m//a%A44-?
	
	vixyvr m?
�

zsmh tvsgiwwJmpi,glev. jmpiReqi0glev tpemrOi}0 glev gmtlivOi}0mrx jpek-�
	
	JMPI. mrtJmpi A jstir,jmpiReqi0&v&-?
	JMPI. syxJmpi?
	
	mrx m0pir0 hmjj A ,jpekAAIRGV]TX-C,mrx-gmtlivOi} 1 ,mrx-tpemrOi}>,mrx-tpemrOi} 1 ,mrx-gmtlivOi}?
	{glevcx wxv_5444a0 .syxWxv?
	glev. syxJmpiReqi A ,glev.-qeppsg,,wxvpir,jmpiReqi-/9-.wm~isj,glev--?

	wtvmrxj,syxJmpiReqi0&)wc)w&0jmpiReqi0,jpekAAIRGV]TX-C&IRG&>&HIG&-?
	
	syxJmpi A jstir,syxJmpiReqi0&{&-?
	
	{lmpi,jkix{w,wxv054440mrtJmpi-%ARYPP-�
		pir A {mhiWxvPir,wxv-?
		
		syxWxv A ,{glevcx.-qeppsg,,pir / 5-.wm~isj,{glevcx--?
		
		jsv,mA4?m@pir?m//-�
			mj,,mrx-wxv_maBAEPTLE ** ,mrx-wxv_ma@ASQIKE ** jpek AA IRGV]TX-
				syxWxv_ma A ,{glevcx-,,mrx-wxv_ma/hmjj-?
			 ipwi mj,,mrx-wxv_ma1hmjjBAEPTLE ** ,mrx-wxv_ma1hmjj@ASQIKE ** jpek AA HIGV]TX-
				syxWxv_ma A ,{glevcx-,,mrx-wxv_ma1hmjj-?
			ipwi
				syxWxv_ma A wxv_ma?
		�
		syxWxv_maAwxv_ma?
		
		jtyx{w,syxWxv0syxJmpi-?
		
		jvii,syxWxv-?
	�
	
	jgpswi,mrtJmpi-?
	jgpswi,syxJmpi-?
�

mrx qemr,mrx evkG0glev. evkZ_a-�
	mj,evkG%A9-
		tvmrxj,&Yweki > )w @jmpi reqi0 tpemr oi}0 gmtliv oi}0 egxmsr ,I-rgv}tx sv ,H-igv}txB&0evkZ_4a-?
	ipwi�
		tvsgiwwJmpi,evkZ_5a0evkZ_6a_4a0evkZ_7a_4a0,evkZ_8a_4aAA+I+€€evkZ_8a_4aAA+i+-CIRGV]TX>HIGV]TX-?
		
		tvmrxj,&Jmpi )wc)w lew fiir {vmxxir xs xli weqi psgexmsr ew mrtyx jmpi2&0evkZ_5a0,evkZ_8a_4aAA+I+€€evkZ_8a_4aAA+i+-C&IRG&>&HIG&-?
	�
	
	vixyvr 4?
�

And to decrypt :

C:\rosettaCode>biggleman.exe substitutionCipher.c_ENC e a D
File substitutionCipher.c_ENC_DEC has been written to the same location as input file.

And for the cleartext, just scroll up...btw, did you know that Digital Fortress was Brown's first novel and he wrote it back in 1998 ? Wonder why nobody ever saw Snowden happening ?

C#

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SubstitutionCipherProject
{
    class SubstitutionCipher
    {
        static void Main(string[] args)
        {
            doEncDec("e:\\source.txt", "enc.txt", true);
            doEncDec("enc.txt", "dec.txt", false);
            Console.WriteLine("Done");
            Console.ReadKey();
        }
        static void doEncDec(String source, String target, bool IsEncrypt)
        {
            ITransform trans;

            if (IsEncrypt)
                trans = new Encrypt();
            else
                trans = new Decrypt();

            FileInfo sfi = new FileInfo(source);
            FileStream sstream = sfi.OpenRead();
            StreamReader sr = new StreamReader(sstream);

            FileInfo tfi = new FileInfo(target);
            FileStream tstream = tfi.OpenWrite();
            TransformWriter tw = new TransformWriter(tstream, trans);
            StreamWriter sw = new StreamWriter(tw);

            String line;
            while ((line = sr.ReadLine()) != null)
                sw.WriteLine(line);
            sw.Close();
        }
    }
    public interface ITransform
    {
        byte transform(byte ch);
    }
    public class Encrypt : ITransform
    {
        const String str = "xyfagchbimpourvnqsdewtkjzl";
        byte ITransform.transform(byte ch)
        {
            if (char.IsLower((char)ch))
                ch = (byte)str[ch - (byte)'a'];
            return ch;
        }
    }
    class Decrypt : ITransform
    {
        const String str = "xyfagchbimpourvnqsdewtkjzl";
        byte ITransform.transform(byte ch)
        {
            if (char.IsLower((char)ch))
                ch = (byte)(str.IndexOf((char)ch) + 'a');
            return ch;
        }
    }
    class TransformWriter : Stream, IDisposable
    {
        private Stream outs;
        private ITransform trans;

        public TransformWriter(Stream s, ITransform t)
        {
            this.outs = s;
            this.trans = t;
        }

        public override bool CanRead
        {
            get { return false; }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanWrite
        {
            get { return true; }
        }
        public override void Flush()
        {
            outs.Flush();
        }

        public override long Length
        {
            get { return outs.Length; }
        }
        public override long Position
        {
            get
            {
                return outs.Position;
            }
            set
            {
                outs.Position = value;
            }
        }
        public override long Seek(long offset, SeekOrigin origin)
        {
            return outs.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            outs.SetLength(value);
        }

        public override void Write(byte[] buf, int off, int len)
        {
            for (int i = off; i < off + len; i++)
                buf[i] = trans.transform(buf[i]);
            outs.Write(buf, off, len);
        }

        void IDisposable.Dispose()
        {
            outs.Dispose();
        }

        public override void Close()
        {
            outs.Close();
        }

        public override int Read(byte[] cbuf, int off, int count)
        {
            return outs.Read(cbuf, off, count);
        }
    }
}

C++

The key file should look something like this: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789SWoVR0kJLXQ8zbCd1OagTH5ie3nvYU2wfrM9yI4sKm6c7hNjtADqFPxpEZlBuG

#include <iostream>
#include <string>
#include <fstream>

class cipher {
public:
    bool work( std::string e, std::string f, std::string k ) {
        if( e.length() < 1 ) return false;
        fileBuffer = readFile( f );
        if( "" == fileBuffer ) return false;
        keyBuffer = readFile( k );
        if( "" == keyBuffer ) return false;

        outName = f;
        outName.insert( outName.find_first_of( "." ), "_out" );

        switch( e[0] ) {
            case 'e': return encode();
            case 'd': return decode();
        }
        return false;
    }
private:
    bool encode() {
        size_t idx, len = keyBuffer.length() >> 1;
        for( std::string::iterator i = fileBuffer.begin(); i != fileBuffer.end(); i++ ) {
            idx = keyBuffer.find_first_of( *i );
            if( idx < len ) outBuffer.append( 1, keyBuffer.at( idx + len ) );
            else outBuffer.append( 1, *i );
        }
        return saveOutput();
    }
    bool decode() {
        size_t idx, l = keyBuffer.length(), len = l >> 1;
        for( std::string::iterator i = fileBuffer.begin(); i != fileBuffer.end(); i++ ) {
            idx = keyBuffer.find_last_of( *i );
            if( idx >= len && idx < l ) outBuffer.append( 1, keyBuffer.at( idx - len ) );
            else outBuffer.append( 1, *i );
        }
        return saveOutput();
    }
    bool saveOutput() {
        std::ofstream o( outName.c_str() );
        o.write( outBuffer.c_str(), outBuffer.size() );
        o.close();
        return true;
    }
    std::string readFile( std::string fl ) {
        std::string buffer = "";
        std::ifstream f( fl.c_str(), std::ios_base::in );
        if( f.good() ) {
            buffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );
            f.close();
        }
        return buffer;
    }
    std::string fileBuffer, keyBuffer, outBuffer, outName;
};

int main( int argc, char* argv[] ) {
    if( argc < 4 ) {
        std::cout << "<d or e>\tDecrypt or Encrypt\n<filename>\tInput file, the output file will have"
        "'_out' added to it.\n<key>\t\tfile with the key to encode/decode\n\n";
    } else {
        cipher c;
        if( c.work( argv[1], argv[2], argv[3] ) ) std::cout << "\nFile successfully saved!\n\n";
        else std::cout << "Something went wrong!\n\n";
    }
    return 0;
}

D

import std.stdio;
import std.string;
import std.traits;

string 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
 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.`;

void main() {
    auto enc = encode(text);
    writeln("Encoded: ", enc);
    writeln;
    writeln("Decoded: ", decode(enc));
}

enum FORWARD = "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\tbcdefghijkl\nmnopqrstuvwxyz";
auto encode(string input) {
    return tr(input, FORWARD, REVERSE);
}

enum REVERSE = "VsciBjedgrzy\nHalvXZKtUP um\tGf?I/w>J<x.q,OC:F;R{A]p}n[D+h=Q)W(o*b&L^k%E$S#Y@M!T~N";
auto decode(string input) {
    return tr(input, REVERSE, FORWARD);
}
Output:
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

Decoded: 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
 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.

EasyLang

alpha$[] = strchars "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
key$[] = strchars "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
# 
proc subst in$ . out$ a$[] b$[] .
   out$ = ""
   for c$ in strchars in$
      for i to len a$[]
         if a$[i] = c$
            out$ &= b$[i]
            break 1
         .
      .
      if i > len a$[]
         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$
Output:
dqnnQ YQbnx
Hello world

Factor

This program optionally allows the user to specify a file to use as a key. Otherwise, it uses a default.

USING: assocs combinators combinators.short-circuit command-line
hashtables io io.encodings.utf8 io.files kernel math.order
multiline namespaces qw sequences ;
IN: rosetta-code.substitution-cipher

CONSTANT: alphabet
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

CONSTANT: default-key
    "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"

SYMBOL: key

STRING: usage
Usage:
  substitution
  <encode|decode>
  input-file
  output-file
  [key-file]  (Optional -- for custom alphabet keys.)

Example:
  substitution encode my-poem.txt my-encoded-poem.txt
;

: check-args ( seq -- ? )
    {
        [ length 3 4 between? not ]
        [ first qw{ encode decode } member? not ]
    } 1|| [ usage print f ] [ t ] if ;

: init-key ( seq -- )
    dup length 4 = [ last utf8 file-contents ]
    [ drop default-key ] if key set ;

: >sub-map ( seq -- assoc )
    [ alphabet key get ] dip first "encode" = [ swap ] unless
    zip >hashtable ;

: encipher ( seq assoc -- newseq )
    [ dupd at dup [ nip ] [ drop ] if ] curry { } map-as ;

: substitute ( seq -- )
    { [ init-key ] [ second ] [ >sub-map ] [ third ] } cleave
    [ utf8 file-contents ] [ encipher ]
    [ utf8 set-file-contents ] tri* ;

: main ( -- )
    command-line get dup check-args [ substitute ] [ drop ] if ;

MAIN: main
Output:

Contents of key.txt:

RwfGlELSpqhPeauybIcHDNoKiAnMsvJmFrxQCkUWdtBZVTXOzjgY

Contents of in.txt:

Substitution Cipher Implementation - File Encryption/Decryption

Task - 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 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.

Invoking the program to encode:

substitution.exe encode in.txt out.txt key.txt

Contents of out.txt:

cXMVTxTXTxdW fxtrJZ pUtkJUJWTnTxdW - ExkJ lWsZgtTxdW/GJsZgtTxdW

HnVC - SJZJ zJ rnOJ Td vd xV TrJZJ zxkk MJ n xWtXT/VdXZsJ mxkJ xW zrxsr zJ nZJ
FdxWF Td lWsZgtT TrJ mxkJ Mg ZJtknsxWF JOJZg XttJZ/kdzJZ snVJ nktrnMJTV dm TrJ
VdXZsJ mxkJ zxTr nWdTrJZ tZJvJTJZUxWJv XttJZ/kdzJZ snVJ nktrnMJTV dZ VgUMdkV
nWv VnOJ xT xWTd nWdTrJZ dXTtXT/JWsZgtTJv mxkJ nWv TrJW nFnxW sdWOJZT TrnT
dXTtXT/JWsZgtTJv mxkJ xWTd dZxFxWnk/vJsZgtTJv mxkJ.

HrxV TgtJ dm lWsZgtTxdW/GJsZgtTxdW VsrJUJ xV dmTJW snkkJv n cXMVTxTXTxdW fxtrJZ.

Invoking the program to decode:

substitution.exe decode out.txt decoded.txt key.txt

Contents of decoded.txt:

<same as in.txt>

Fortran

Works with: Fortran version 90 and later
program substitution
  implicit none

  integer, parameter :: len_max = 256
  integer, parameter :: eof = -1
  integer :: in_unit = 9, out_unit = 10, ios
  character(len_max) :: line
  
  open(in_unit, file="plain.txt",  iostat=ios)
  if (ios /= 0) then
    write(*,*) "Error opening plain.txt file"
    stop
  end if
  
  open(out_unit, file="encrypted.txt", iostat=ios)
  if (ios /= 0) then
    write(*,*) "Error opening encrypted.txt file"
    stop
  end if

! Encryption
  do 
    read(in_unit, "(a)", iostat=ios) line
    if (ios > 0) then
      write(*,*) "Error reading plain.txt file"
      stop
    else if (ios == eof) then
      exit
    end if
            
    call cipher(trim(line))
    write(out_unit, "(a)", iostat=ios) trim(line)
    if (ios /= 0) then
      write(*,*) "Error writing encrypted.txt file"
      stop
    end if
  end do

  close(in_unit)
  close(out_unit)

  open(in_unit, file="encrypted.txt",  iostat=ios)
  if (ios /= 0) then
    write(*,*) "Error opening encrypted.txt file"
    stop
  end if
  
  open(out_unit, file="decrypted.txt", iostat=ios)
  if (ios /= 0) then
    write(*,*) "Error opening decrypted.txt file"
    stop
  end if
 
! Decryption 
  do 
    read(in_unit, "(a)", iostat=ios) line
    if (ios > 0) then
      write(*,*) "Error reading encrypted.txt file"
      stop
    else if (ios == eof) then
      exit
    end if
            
    call cipher(trim(line))
    write(out_unit, "(a)", iostat=ios) trim(line)
    if (ios /= 0) then
      write(*,*) "Error writing decrypted.txt file"
      stop
    end if
  end do  

  close(in_unit)
  close(out_unit)
  
contains

subroutine cipher(text)
  character(*), intent(in out) :: text
  integer :: i

! Substitutes A -> Z, B -> Y ... Y -> B, Z -> A and ditto for lower case
! works for both encryption and decryption

  do i = 1, len(text)
    select case(text(i:i))
      case ('A':'Z')
        text(i:i) = achar(155 - iachar(text(i:i)))
      case ('a':'z')
        text(i:i) = achar(219 - iachar(text(i:i)))
    end select
  end do
end subroutine

end program
Output:
Encrypted file:
Sviv dv szev gl wl rh gsviv droo yv z rmkfg/hlfixv urov rm dsrxs dv ziv
tlrmt gl Vmxibkg gsv urov yb ivkozxrmt vevib fkkvi/oldvi xzhv zokszyvgh
lu gsv hlfixv urov drgs zmlgsvi kivwvgvinrmvw fkkvi/oldvi xzhv zokszyvgh
li hbnyloh zmw hzev rg rmgl zmlgsvi lfgkfg/vmxibkgvw urov zmw gsvm ztzrm
xlmevig gszg lfgkfg/vmxibkgvw urov rmgl lirtrmzo/wvxibkgvw urov.
Gsrh gbkv lu Vmxibkgrlm/Wvxibkgrlm hxsvnv rh lugvm xzoovw z Hfyhgrgfgrlm Xrksvi.

Decrypted file:
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 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.

FreeBASIC

' FB 1.05.0 Win64

' uses same alphabet and key as Ada language example
Const string1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Const string2 = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"

Sub process(inputFile As String, outputFile As String, encrypt As Boolean)
   Open inputFile For Input As #1
   If err > 0 Then
     Print "Unable to open input file"
     Sleep
     End
   End If
   Dim As String alpha, key 
   If encrypt Then
     alpha = string1 : key = string2
   Else
     alpha = string2 : key = string1
   End If     
   Open outputFile For Output As #2
   Dim s As String
   Dim p As Integer
   While Not Eof(1)
     Line Input #1, s
     For i As Integer = 0 To Len(s) - 1  
       If (s[i] >= 65 AndAlso s[i] <= 90) OrElse (s[i] >= 97 AndAlso s[i] <= 122) Then
         p =  Instr(alpha, Mid(s, i + 1, 1)) - 1
         s[i] = key[p]         
       End If      
     Next 
     Print #2, s
   Wend
   Close #1 : Close #2
End Sub

process "plain.txt", "encrypted.txt", true
process "encrypted.txt", "decrypted.txt", false
Print
Print "Press any key to quit"
Sleep
Output:

Encrypted.txt :

KEwLkRkEkRQh cRWFqb gDWnqDqhkIkRQh - jRnq BhJbTWkRQh/iqJbTWkRQh

tILp - dqbq Yq FISq kQ xQ RL kFqbq YRnn wq I RhWEk/LQEbJq ORnq Rh YFRJF Yq Ibq
 CQRhC kQ BhJbTWk kFq 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.

cnRJp Fqbq kQ phQY DQbq.

Decrypted.txt = Plain.txt :

Substitution Cipher Implementation - File Encryption/Decryption

Task - 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 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.

Click here to know more.

Go

Translation of: Kotlin
package main

import (    
    "fmt"
    "strings"
)

var key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"

func encode(s string) string {
    bs := []byte(s)
    for i := 0; i < len(bs); i++ {
        bs[i] = key[int(bs[i]) - 32]
    }
    return string(bs)
}

func decode(s string) string {
    bs := []byte(s)
    for i := 0; i < len(bs); i++ {
        bs[i] = byte(strings.IndexByte(key, bs[i]) + 32)
    }
    return string(bs)
}

func main() {
    s := "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
    enc := encode(s)
    fmt.Println("Encoded: ", enc)
    fmt.Println("Decoded: ", decode(enc))
}
Output:
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!

IS-BASIC

100 PROGRAM "SuChiper.bas"
110 STRING ST$(1 TO 2)*52,K$*1
120 LET ST$(1)="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
130 LET ST$(2)="VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
140 CLEAR SCREEN:PRINT "1 - encode, 2 - decode"
150 DO
160   LET K$=INKEY$
170 LOOP UNTIL K$="1" OR K$="2"
180 IF K$="1" THEN
190   INPUT PROMPT "File name: ":NAME$
200   IF OPENFILE(NAME$) THEN CALL CHIPER(1)
210 ELSE
220   IF OPENFILE("Encrypte.txt") THEN CALL CHIPER(2)
230 END IF
240 DEF OPENFILE(N$)
250   LET OPENFILE=0
260   WHEN EXCEPTION USE OPENERROR
270     OPEN #1:N$
280   END WHEN 
290   LET OPENFILE=-1
300 END DEF
310 DEF CHIPER(FUNC)
320   LET EOF=0
330   WHEN EXCEPTION USE OPENERROR
340     IF FUNC=1 THEN
350       OPEN #2:"Encrypte.txt" ACCESS OUTPUT
360       LET OUTP=2
370     ELSE 
380       OPEN #2:"Decrypte.txt" ACCESS OUTPUT
390       LET OUTP=1
400     END IF 
410   END WHEN 
420   WHEN EXCEPTION USE IOERROR
430     DO 
440       GET #1:K$
450       IF UCASE$(K$)>="A" AND UCASE$(K$)<="Z" THEN
460         PRINT #2:ST$(OUTP)(POS(ST$(FUNC),K$));
470       ELSE 
480         PRINT #2:K$;
490       END IF 
500     LOOP UNTIL EOF
510   END WHEN 
520   HANDLER IOERROR
530     IF EXTYPE<>9228 THEN PRINT EXSTRING$(EXTYPE)
540     CLOSE #2
550     CLOSE #1
560     LET EOF=1
570   END HANDLER 
580 END DEF 
590 HANDLER OPENERROR
600   PRINT EXSTRING$(EXTYPE)
610   END
620 END HANDLER

Haskell

import Data.Char          (chr)
import Data.Maybe         (fromMaybe)
import Data.Tuple         (swap)
import System.Environment (getArgs)

data Command = Cipher String | Decipher String | Invalid

alphabet :: String
alphabet = chr <$> [32..126]

cipherMap :: [(Char, Char)]
cipherMap = zip alphabet (shuffle 20 alphabet)

shuffle :: Int -> [a] -> [a]
shuffle n xs = iterate go xs !! n
  where
    go [] = []
    go xs = go (drop 2 xs) <> take 2 xs

convert :: Eq a => [(a, a)] -> [a] -> [a]
convert m = map (\x -> fromMaybe x (lookup x m))

runCommand :: Command -> String
runCommand (Cipher s)   = convert cipherMap s
runCommand (Decipher s) = convert (swap <$> cipherMap) s
runCommand Invalid = "Invalid arguments. Usage: simplecipher c|d <text>"

parseArgs :: [String] -> Command
parseArgs (x:y:xs)
  | x == "c" = Cipher y
  | x == "d" = Decipher y
  | otherwise = Invalid
parseArgs _ = Invalid

main :: IO ()
main = parseArgs <$> getArgs >>= putStrLn . runCommand
Output:
$ simplecipher c "The quick brown fox jumped over the lazy dogs."
@Ty3xt}w~3N^zrZ3Rzd3Vt|\yP3zby^3`Ty3Xufp3Pz{v%

$ simplecipher d '@Ty3xt}w~3N^zrZ3Rzd3Vt|\yP3zby^3`Ty3Xufp3Pz{v%'
The quick brown fox jumped over the lazy dogs.

J

Example implementation:

keysubst=: [`(a.i.])`(a."_)}
key=: 'Taehist' keysubst '!@#$%^&'
enc=: a. {~ key i. ]
dec=: key {~ a. i. ]

   enc 'This is a test.'
!$%^ %^ @ &#^&.
   dec '!$%^ %^ @ &#^&.'
This is a test.

Note that this particular implementation bakes the key itself into the implementations of enc and dec. 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...

Java

public class SubstitutionCipher {

    final static String key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"
            + "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";

    static String 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 "
            + "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.";

    public static void main(String[] args) {
        String enc = encode(text);
        System.out.println("Encoded: " + enc);
        System.out.println("\nDecoded: " + decode(enc));
    }

    static String encode(String s) {
        StringBuilder sb = new StringBuilder(s.length());

        for (char c : s.toCharArray())
            sb.append(key.charAt((int) c - 32));

        return sb.toString();
    }

    static String decode(String s) {
        StringBuilder sb = new StringBuilder(s.length());

        for (char c : s.toCharArray())
            sb.append((char) (key.indexOf((int) c) + 32));

        return sb.toString();
    }
}
Encoded: "uTu]cu]b3Qu]<d]Id]...><K<,<Kd|]6KMbuTi
Decoded: Here we have to do is... Substitution Cipher.

jq

Translation of: Wren
Works with: jq

Works with gojq, the Go implementation of 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
Output:
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!


Julia

Works with: Julia version 0.6
Translation of: Kotlin

Module:

module SubstitutionCiphers

using Compat

const key = "]kYV}(!7P\$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"

function encode(s::AbstractString)
    buf = IOBuffer()
    for c in s
        print(buf, key[Int(c) - 31])
    end
    return String(take!(buf))
end

function decode(s::AbstractString)
    buf = IOBuffer()
    for c in s
        print(buf, Char(findfirst(==(c), key) + 31))
    end
    return String(take!(buf))
end

end  # module SubstitutionCiphers

Main:

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
Output:
Original: The quick brown fox jumps over the lazy dog, who barks VERY loudly!
 -> 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!

Klingphix

include ..\Utilitys.tlhy

" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
" VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
"A simple example"

:Encode %mode !mode
    %i %t
    $mode not [rot rot swap rot] if
    len [
        !i
        $i get swap !t
        rot swap find
        rot swap get
        $t swap $i set
    ] for
    $mode not [rot rot swap rot] if
;

dup ?
true Encode dup ?
false Encode ?

" " input

Kotlin

Translation of: Java
// version 1.0.6

object SubstitutionCipher {
    val key = "]kYV}(!7P\$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"

    fun encode(s: String): String {
        val sb = StringBuilder()
        for (c in s) sb.append(key[c.toInt() - 32])
        return sb.toString()
    }

    fun decode(s: String): String {
        val sb = StringBuilder()
        for (c in s) sb.append((key.indexOf(c) + 32).toChar())
        return sb.toString()
    }
}

fun main(args: Array<String>) {
    val s = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
    val enc = SubstitutionCipher.encode(s)
    println("Encoded:  $enc")
    println("Decoded:  ${SubstitutionCipher.decode(enc)}")
}
Output:
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!

Lambdatalk

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}}} 
-> small_ascii 

{S.length {small_ascii}} = 90

{def substitution

 {def substitution.r
  {lambda {:w :n :s :i}
   {if {> :i :n}
    then 
    else {let { {:s :s} {:c {W.char2code {A.get :i :w}}}
              } {if {and {>= :c 33} {<= :c 122}}
                 then {W.code2char {+ 33 {% {+ :c {- :s 33}} 90}}} 
                 else {if {= :c 248} then :c else}} 
         }{substitution.r :w :n :s {+ :i 1}} }}}

 {lambda {:s :w}
  {let { {:s :s} {:w {S.replace \s by ` in :w}}
       } {S.replace ` 
                 by space 
                 in {substitution.r {A.split :w}
                                    {- {W.length :w} 1}
                                    :s 
                                    0}} }}}
-> substitution

1) intitial text:

{def txt 
Veni, Vidi, Vici is a Latin phrase popularly attributed to Julius Caesar who, according to Appian, used the phrase 
in a letter to the Roman Senate around 47 BC after he had achieved a quick victory in his short war against 
Pharnaces II of Pontus at the Battle of Zela.
} -> txt

2) choose the shift:

{def shift 13}
-> shift // valid in [0...90] except 5 10 15 29 30 50 53 70 74

3) encoding the text

 {substitution {shift} {txt}} 
-> cr!v9mcvqv9mcvpvmv&mnmYn'v!m#u%n&rm#"#(yn%y,mn''%vo('rqm'"mW(yv(&mPnr&n%m*u"9mnpp"%qv!tm'"mN##vn!9m(&rqm'urm#u%n&rmv!mnmyr''r%m'"m'urm_"zn!m r!n'rmn%"
(!qmADmOPmns'r%murmunqmnpuvr)rqmnm$(vpxm)vp'"%,mv!muv&m&u"%'m*n%mntnv!&'m]un%!npr&mVVm"sm]"!'(&mn'm'urmOn''yrm"smgryn;

4) decoding the text

 {substitution {- 90 {shift}} {substitution {shift} {txt}}} 
-> Veni, Vidi, Vici is a Latin phrase popularly attributed to Julius Caesar who, according to Appian, used the phrase 
in a letter to the Roman Senate around 47 BC after he had achieved a quick victory in his short war against 
Pharnaces II of Pontus at the Battle of Zela.

Lua

-- Generate a random substitution cipher for ASCII characters 65 to 122
function randomCipher ()
    local cipher, rnd = {plain = {}, encoded = {}}
    for ascii = 65, 122 do
        table.insert(cipher.plain, string.char(ascii))
        table.insert(cipher.encoded, string.char(ascii))
    end
    for i = 1, #cipher.encoded do
        rnd = math.random(#cipher.encoded)
        cipher.encoded[i], cipher.encoded[rnd] = cipher.encoded[rnd], cipher.encoded[i]
    end
    return cipher
end

-- Encipher text using cipher.  Decipher if decode is true.
function encode (text, cipher, decode)
    local output, letter, found, source, dest = ""
    if decode then
        source, dest = cipher.encoded, cipher.plain
    else
        source, dest = cipher.plain, cipher.encoded
    end
    for pos = 1, #text do
        letter = text:sub(pos, pos)
        found = false
        for k, v in pairs(source) do
            if letter == v then
                output = output .. dest[k]
                found = true
                break
            end
        end
        if not found then output = output .. letter end
    end
    return output
end

-- Main procedure
math.randomseed(os.time())
local subCipher = randomCipher()
print("Cipher generated:")
print("\tPlain:", table.concat(subCipher.plain))
print("\tCoded:", table.concat(subCipher.encoded))
local inFile = io.open("C:\\ulua\\taskDescription.txt", "r")
local input = inFile:read("*all")
inFile:close()
local encoded = encode(input, subCipher)
print("\nEncoded file contents:")
print("\t" .. encoded)
print("\nAbove text deciphers to: ")
print("\t" .. encode(encoded, subCipher, true))
Output:
Cipher generated:
        Plain:  ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz
        Coded:  MwZ\zPaqSTNuLQpgbnG[V_xeJmlWYCI]rhFcv^UHXijR`yfKEktADsdoBO

Encoded file contents:
        qvkv dv Hrsv Af cf Xt AHvkv dXRR hv r XyKDA/tfDkFv ^XRv Xy dHXFH dv rkv
UfXyU Af zyFkBKA AHv ^XRv hB kvKRrFXyU vsvkB DKKvk/Rfdvk Frtv rRKHrhvAt f^ AHv t
fDkFv ^XRv dXAH ryfAHvk KkvcvAvk`Xyvc DKKvk/Rfdvk Frtv rRKHrhvAt fk tB`hfRt ryc
trsv XA XyAf ryfAHvk fDAKDA/vyFkBKAvc ^XRv ryc AHvy rUrXy FfysvkA AHrA fDAKDA/vy
FkBKAvc ^XRv XyAf fkXUXyrR/cvFkBKAvc ^XRv. [HXt ABKv f^ zyFkBKAXfy/\vFkBKAXfy tF
Hv`v Xt f^Avy FrRRvc r GDhtAXADAXfy ZXKHvk.

Above text deciphers to:
        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 s
ource file with another predetermined upper/lower case alphabets or symbols and
save it into another output/encrypted file and then again convert that output/en
crypted file into original/decrypted file. This type of Encryption/Decryption sc
heme is often called a Substitution Cipher.

Mathematica/Wolfram Language

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
Output:
"DebTyUsLNTg2H01TWHSTfUt5qTHZb2T7ebTl4 8TQHc,0eHTg42NqTuK6CTlHUQl8!"
"The quick brown fox jumps over the lazy dog,who barks VERY loudly!"
True

MiniScript

alphabet = "abcdefghijklmnopqrstuvwxyz".split("")
cipher = alphabet[0:]
cipher.shuffle
encode = {}
decode = {}
for i in alphabet.indexes
    encode[alphabet[i]] = cipher[i]
    decode[cipher[i]] = alphabet[i]
    encode[alphabet[i].upper] = cipher[i].upper
    decode[cipher[i].upper] = alphabet[i].upper
end for

apply = function(map, s)
    chars = s.split("")
    for i in chars.indexes
        if map.hasIndex(chars[i]) then chars[i] = map[chars[i]]
    end for
    return chars.join("")
end function

msg = "Now is the time for all good men (and women) to come together."
secretCode = apply(encode, msg)
print secretCode
print apply(decode, secretCode)
Output:
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.

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
Output:
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!”

Perl

Translation of: Java
sub encode {
    my $source = shift;
    my $key = shift;
    my $out = q();

    @ka = split //, $key;
    foreach $ch (split //, $source) {
        $idx = ord($ch) - 32;
        $out .= $ka[$idx];
    }

    return $out;
}

sub decode {
    my $source = shift;
    my $key = shift;
    my $out = q();

    foreach $ch (split //, $source) {
        $idx = index $key, $ch;
        $val = chr($idx + 32);
        $out .= $val;
    }

    return $out;
}

my $key = q(]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\C1yxJ);
my $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 "
         . "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.";

my $ct = encode($text, $key);
print "Encoded: $ct\n";

my $pt = decode($ct, $key);
print "Decoded: $pt\n";
Output:
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
Decoded: 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 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.

Phix

constant plain = tagset('Z','A')&tagset('z','a'),
         key = shuffle(plain)

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
 
string original = "A simple example.",
       encoded = encode(original),
       decoded = encode(encoded, true)

printf(1,"original: %s\nencoded: %s\ndecoded: %s\n",{original,encoded,decoded})
Output:
original: A simple example.
encoded: j wqGuMv vsQGuMv.
decoded: A simple example.

Phixmonti

include ..\Utilitys.pmt

" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
" VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
"A simple example"

def Encode
    >ps
    tps not if >ps swap ps> endif
    len for
        >ps
        tps get swap >ps
        rot swap find
        rot swap get
        ps> swap ps> set
    endfor
    ps> not if >ps swap ps> endif
enddef

dup ?
true Encode dup ?
false Encode ?
Output:
A simple example
V LRDWnq qMIDWnq
A simple example

=== Press any key to exit ===

PHP

<?php

$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$key      = 'cPYJpjsBlaOEwRbVZIhQnHDWxMXiCtUToLkFrzdAGymKvgNufeSq';

// Encode input.txt, and save result in output.txt
file_put_contents('output.txt', strtr(file_get_contents('input.txt'), $alphabet, $key));

$source  = file_get_contents('input.txt');
$encoded = file_get_contents('output.txt');
$decoded = strtr($encoded, $key, $alphabet);

echo
    '== SOURCE ==', PHP_EOL,
    $source, PHP_EOL, PHP_EOL,
    '== ENCODED ==', PHP_EOL,
    $encoded, PHP_EOL, PHP_EOL,
    '== DECODED ==', PHP_EOL,
    $decoded, PHP_EOL, PHP_EOL;
Output:
== SOURCE ==
Substitution Cipher Implementation - File Encryption/Decryption

Task - 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 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.

== ENCODED ==
vnPhQlQnQlbR ClVBpI kwVEpwpRQcQlbR - TlEp URYIxVQlbR/tpYIxVQlbR

gchO - LpIp Dp BcHp Qb Jb lh QBpIp DlEE Pp c lRVnQ/hbnIYp jlEp lR DBlYB Dp cIp
sblRs Qb URYIxVQ QBp jlEp Px IpVEcYlRs pHpIx nVVpI/EbDpI Ychp cEVBcPpQh bj QBp
hbnIYp jlEp DlQB cRbQBpI VIpJpQpIwlRpJ nVVpI/EbDpI Ychp cEVBcPpQh bI hxwPbEh
cRJ hcHp lQ lRQb cRbQBpI bnQVnQ/pRYIxVQpJ jlEp cRJ QBpR csclR YbRHpIQ QBcQ
bnQVnQ/pRYIxVQpJ jlEp lRQb bIlslRcE/JpYIxVQpJ jlEp.

gBlh QxVp bj URYIxVQlbR/tpYIxVQlbR hYBpwp lh bjQpR YcEEpJ c vnPhQlQnQlbR ClVBpI.

== DECODED ==
Substitution Cipher Implementation - File Encryption/Decryption

Task - 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 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.

Picat

Translation of: Prolog
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).
Output:
tFqNokRJpNwbQShNOQYNAkDWqxNQEqbNLFqNnITMNxQC
The quick brown fox jumped over the lazy dog
ok

Using maps

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").
Output:
tFqNokRJpNwbQShNOQYNAkDWqxNQEqbNLFqNnITMNxQC!!!
The quick brown fox jumped over the lazy dog!!!
ok


PicoLisp

(setq *A (chop "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"))
(setq *K (chop "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"))

(de cipher (Str D)
   (let (K *K  A *A)
      (and D (xchg 'A 'K))
      (pack
         (mapcar
            '((N)
               (or
                  (pick
                     '((A K) (and (= A N) K))
                     A
                     K )
                  N ) )
            (chop Str) ) ) ) )
(and
   (println 'encode (cipher "The quick brown fox jumped over the lazy dog's back"))
   (println 'decode (cipher @ T)) )
Output:
encode "tFq oERJp wbQYh OQM AEDWqx QSqb kFq nINT xQC'L wIJp"
decode "The quick brown fox jumped over the lazy dog's back"

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);
Output:
Encrypted: tFq oERJp wbQYh OQM AEDWqx QSqb kFq nINT xQCL
Decrypted: The quick brown fox jumped over the lazy dogs

Prolog

cypher(O, S) :-
	nonvar(O),
	var(S),
	atom_chars(O,Oc),
	sub_chars(Oc,Sc),
	atom_chars(S,Sc).
cypher(O, S) :-
	nonvar(S),
	var(O),
	atom_chars(S,Sc),
	sub_chars(Oc,Sc),
	atom_chars(O,Oc).	
	
% mapping based on ADA implementation but have added space character	
base(['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,' ']).
subs(['V',s,c,i,'B',j,e,d,g,r,z,y,'H',a,l,v,'X','Z','K',t,'U','P',u,m,'G',f,'I',w,'J',x,q,'O','C','F','R','A',p,n,'D',h,'Q','W',o,b,' ','L',k,'E','S','Y','M','T','N']).

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).
Output:
?- cypher('The quick brown fox jumped over the lazy dog', Result).
Result = tFqNokRJpNwbQShNOQYNAkDWqxNQEqbNLFqNnITMNxQC .

?- cypher(Result, 'tFqNokRJpNwbQShNOQYNAkDWqxNQEqbNLFqNnITMNxQC').
Result = 'The quick brown fox jumped over the lazy dog'.

?-

Python

from string import printable
import random

EXAMPLE_KEY = ''.join(sorted(printable, key=lambda _:random.random()))

def encode(plaintext, key):
    return ''.join(key[printable.index(char)] for char in plaintext)

def decode(plaintext, key):
    return ''.join(printable[key.index(char)] for char in plaintext)

original = "A simple example."
encoded = encode(original, EXAMPLE_KEY)
decoded = decode(encoded, EXAMPLE_KEY)
print("""The original is: {}
Encoding it with the key: {}
Gives: {}
Decoding it by the same key gives: {}""".format(
    original, EXAMPLE_KEY, encoded, decoded))

A straightforward implementation. The output is:

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?
Q%S(�RB;25&s6Z9C3+D-_8kn,`Egiwzp"G
Gives: 
iPMhX\YiYmJhX\Y5
Decoding it by the same key gives: A simple example.

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
Output:
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.

Racket

Uses #REXX input file (in data/substitution.in.txt).

The check-equal? tests assure us that we return the plain text after a cypher/decypher pair; so I don't display the plaintext in the output.

#lang racket/base
(require racket/list racket/function racket/file)

(define abc "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")

;; Used to generate my-key for examples
(define (random-key (alphabet abc))
  (list->string (shuffle (string->list alphabet))))

(define (cypher/decypher key (alphabet abc))
  ;; alist is fine, hashes are better over 40 chars... so alist for
  ;; abc, hash for ASCII.
  (define ab-chars (string->list alphabet))
  (define ky-chars (string->list key))
  (define cypher-alist (map cons ab-chars ky-chars))
  (define decypher-alist (map cons ky-chars ab-chars))
  (define ((subst-map alist) str)
    (list->string (map (lambda (c) (cond [(assoc c alist) => cdr] [else c]))
                       (string->list str))))
  (values (subst-map cypher-alist)
          (subst-map decypher-alist)))

(define (cypher/decypher-files key (alphabet abc))
  (define-values (cypher decypher) (cypher/decypher key alphabet))
  (define ((convert-file f) in out #:exists (exists-flag 'error))
     (curry with-output-to-file out #:exists exists-flag
            (lambda () (display (f (file->string in))))))
  (values (convert-file cypher)
          (convert-file decypher)))

(module+ test
  (require rackunit)
  (define my-key "LXRWzUrIYPJiVQyMwKudbAaDjSEefvhlqmOkGcBZCFsNpxHTgton")
  
  (define-values (cypher decypher) (cypher/decypher my-key abc))
  
  (define in-text #<<T
The quick brown fox...
.. jumped over
the lazy dog!
T
    )
  (define cypher-text (cypher in-text))
  
  (define plain-text (decypher cypher-text))
  (displayln cypher-text)
  (check-equal? plain-text in-text)
  
  (define-values (file-cypher file-decypher) (cypher/decypher-files my-key abc))
  (file-cypher "data/substitution.in.txt" "data/substitution.crypt.txt" #:exists 'replace)
  (file-decypher "data/substitution.crypt.txt" "data/substitution.plain.txt" #:exists 'replace)
  (displayln "---")
  (displayln (file->string "data/substitution.crypt.txt"))
  (check-equal? (file->string "data/substitution.in.txt")
                (file->string "data/substitution.plain.txt")))
Output:
dmh sHOfG eNCgZ lCt...
.. kHBFhv CThN
xmh cEno vCq!
---
             "zThNo  xCCc  mEp  E  pFhfOlOf  'xmNhpmCcv',
               EZv gmhZ xmh HphN htfhhvp xmh xmNhpmCcv,
           xmh xCCc ehfCBhp E mOZvNEZfh NExmhN xmEZ E mhcF.
          LZo pClxgENh Hphv ehoCZv Oxp xmNhpmCcv gOcc fEHph
              vhfNhEphp OZ FNCvHfxOTOxo, ZCx OZfNhEphp.
       LZv gmhZ OZvOTOvHEc FNCvHfxp ENh FHx xCqhxmhN FOhfhBhEc,
       xmh NhpHcx Op E popxhB xmEx mEp qCZh FEpx Oxp xmNhpmCcv
       ─── E fCHZxhNFNCvHfxOTh fCcchfxOCZ Cl BOplOx HZOxp xmEx
        gCNG EqEOZpx hEfm CxmhN NExmhN xmEZ gOxm hEfm CxmhN."
                               ─── VhNch MENGp

Raku

(formerly Perl 6)

Works with: Rakudo version 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.

my $chr = (' ' .. '}').join('');
my $key = $chr.comb.pick(*).join('');

# Be very boring and use the same key every time to fit task reqs.
$key = q☃3#}^",dLs*>tPMcZR!fmC rEKhlw1v4AOgj7Q]YI+|pDB82a&XFV9yzuH<WT%N;iS.0e:`G\n['6@_{bk)=-5qx(/?$JoU☃;

sub MAIN ($action = 'encode', $file = '') {

    die 'Only options are encode or decode.' unless $action ~~ any 'encode'|'decode';

    my $text = qq:to/END/;
        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 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.
        END

    $text = $file.IO.slurp if $file;

    say "Key = $key\n";

    if $file {
        say &::($action)($text);
    } else {
        my $encoded;
        say "Encoded text: \n {$encoded = encode $text}";
        say "Decoded text: \n {decode $encoded}";
    }
}

sub encode ($text) { $text.trans($chr => $key) }

sub decode ($text) { $text.trans($key => $chr) }
Output:
with no passed parameters
Key = 3#}^",dLs*>tPMcZR!fmC rEKhlw1v4AOgj7Q]YI+|pDB82a&XFV9yzuH<WT%N;iS.0e:`G\n['6@_{bk)=-5qx(/?$JoU

Encoded text: 
 +`=`3(`3n.x`35b3:b3[-35n`=`3([@@30`3.3[{kq5Z-bq=e`3G[@`3[{3(n[en3
(`3.=`3\b[{\35b3]{e=?k535n`3G[@`30?3=`k@.e[{\3`x`=?3qkk`=Z@b(`=3
e.-`3.@kn.0`5-3bG35n`3-bq=e`3G[@`3([5n3.{b5n`=3k=`:`5`=_[{`:3
qkk`=Z@b(`=3e.-`3.@kn.0`5-3b=3-?_0b@-3.{:3-.x`3[53[{5b3.{b5n`=3
bq5kq5Z`{e=?k5`:3G[@`3.{:35n`{3.\.[{3eb{x`=535n.53bq5kq5Z`{e=?k5`:3
G[@`3[{5b3b=[\[{.@Z:`e=?k5`:3G[@`c39n[-35?k`3bG3]{e=?k5[b{ZQ`e=?k5[b{
-en`_`3[-3bG5`{3e.@@`:3.3Vq0-5[5q5[b{37[kn`=c

Decoded 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 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.

REXX

Programming notes:   the cipher key (as used by this REXX program) is stored in a file as two records:

  •   the 1st record is the plain-text characters to be encrypted.
  •   the 2nd record is the crypt-text characters used for encryption.
  •   the two records should be equal in the number of characters.
  •   the Nth character of record   1   will be encrypted to the Nth character of record   2.
/*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.*/
if fid.2==''  then fid.2= "CIPHER.OUT"           /* "      "         "   "   "     "    */
if fid.3==''  then fid.3= "CIPHER.KEY"           /* "      "         "   "   "     "    */
if fid.4==''  then fid.4= "CIPHER.ORI"           /* "      "         "   "   "     "    */
say '    input file: '   fid.1                   /*display the fileID used for  input.  */
say '   output file: '   fid.2                   /*   "     "     "     "   "  output.  */
say '   cipher file: '   fid.3                   /*   "     "     "     "   " cipher-key*/
say 'decrypted file: '   fid.4                   /*   "     "     "     "   "  decrypted*/
call closer                                      /*close all files in case they're open.*/
           do c=1  while lines(fid.3)\==0        /*read (hopefully 2 records) from key. */
           @.c= space( linein(fid.3), 0)         /*assign input record to an  @.  array.*/
           end   /*c*/
c= c - 1                                         /*adjust the number of records (for DO)*/
if c==0                       then call ser fid.3,  'not found or is empty.'
if c>2                        then call ser fid.3,  'has too many records  (>2).'
if c<2                        then call ser fid.3,  'has too few records   (<2).'
if length(@.1)\==length(@.2)  then call ser fid.3,  'has unequal length records.'
call encrypt  fid.1, fid.2                       /*encrypt the input file  ───►  output.*/
_=@.1;    @.1=@.2;   @.2=_                       /*switch the cipher keys for decryption*/
call encrypt  fid.2, fid.4                       /*decrypt the output file ───► decrypt.*/
call show     'cipher file ('fid.3")" , fid.3    /*display the cipher─key file.         */
call show      'input file ('fid.1")" , fid.1    /*   "     "     input     "           */
call show     'output file ('fid.2")" , fid.2    /*   "     "    output     "           */
call show ' decrypted file ('fid.4")" , fid.4    /*   "     "   decrypted   "           */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
closer:  do f=1  for 4;   call lineout fid.f;    end  /*f*/;            say;      return
ser:     say  '***error!***  file '     arg(1)" "    arg(2);                      exit
show:    say;   say center( arg(1), 79, '═');        "TYPE"  arg(2);              return
/*──────────────────────────────────────────────────────────────────────────────────────*/
encrypt: parse arg @in,@out                      /* [↓] effectively deletes @out file by*/
         call lineout @out,,1                    /*setting pointer to rec#1 for the file*/
                                do j=0  while lines(@in)\==0       /*read the input file*/
                                call lineout @out, translate( linein(@in), @.2, @.1)
                                end   /*j*/
         if j==0  then call ser @in, 'is empty.' /*was the file not found or was empty? */
         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:

    input file:  CIPHER.IN
   output file:  CIPHER.OUT
   cipher file:  CIPHER.KEY
decrypted file:  CIPHER.ORI

CIPHER.IN  records processed:  10
CIPHER.OUT  records processed:  10

═══════════════════════════cipher file (CIPHER.KEY)════════════════════════════
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
WXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV

════════════════════════════input file (CIPHER.IN)═════════════════════════════
             "Every  tool  has  a  specific  'threshold',
               and when the user exceeds the threshold,
           the tool becomes a hindrance rather than a help.
          Any software used beyond its threshold will cause
              decreases in productivity, not increases.
       And when individual products are put together piecemeal,
       the result is a system that has gone past its threshold
       ─── a counterproductive collection of misfit units that
        work against each other rather than with each other."
                               ─── Merle Parks

═══════════════════════════output file (CIPHER.OUT)════════════════════════════
             "Aranu  pkkh  dWo  W  olaYebeY  'pdnaodkhZ',
               WjZ sdaj pda qoan atYaaZo pda pdnaodkhZ,
           pda pkkh XaYkiao W dejZnWjYa nWpdan pdWj W dahl.
          wju okbpsWna qoaZ XaukjZ epo pdnaodkhZ sehh YWqoa
              ZaYnaWoao ej lnkZqYperepu, jkp ejYnaWoao.
       wjZ sdaj ejZereZqWh lnkZqYpo Wna lqp pkcapdan leaYaiaWh,
       pda naoqhp eo W ouopai pdWp dWo ckja lWop epo pdnaodkhZ
       ─── W YkqjpanlnkZqYpera YkhhaYpekj kb ieobep qjepo pdWp
        skng WcWejop aWYd kpdan nWpdan pdWj sepd aWYd kpdan."
                               ─── Ianha LWngo

═════════════════════════ decrypted file (CIPHER.ORI)══════════════════════════
             "Every  tool  has  a  specific  'threshold',
               and when the user exceeds the threshold,
           the tool becomes a hindrance rather than a help.
          Any software used beyond its threshold will cause
              decreases in productivity, not increases.
       And when individual products are put together piecemeal,
       the result is a system that has gone past its threshold
       ─── a counterproductive collection of misfit units that
        work against each other rather than with each other."
                               ─── Merle Parks

Ring

# Project : Substitution Cipher

plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ciphertext = "ZEBRASCDFGHIJKLMNOPQTUVWXY"
test = "flee at once. we are discovered!"
encrypt = "SIAA ZQ LKBA. VA ZOA RFPBLUAOAR!"

see "Plaintext : " + plaintext + nl
see "Ciphertext : " + ciphertext + nl
see "Test : " + test + nl
see "Encoded : "
encodetext = encode(test)
see encodetext + nl
see "Decoded : "
decodetext = decode(encodetext)
see decodetext + nl

func encode(test)
        str = ""
        for n = 1 to len(test)
              pos = substr(plaintext, upper(test[n]))
              if test[n] = " "
                 str = str + " "
              elseif test[n] = "!"
                 str = str + "!"
              elseif test[n] = "."
                 str = str + "."
              else
                 str = str + substr(ciphertext, pos, 1)
              ok
        next
        return str

func decode(test)
        str = ""
        for n = 1 to len(encodetext)
              pos = substr(ciphertext, upper(encodetext[n]))
              if test[n] = " "
                 str = str + " "
              elseif test[n] = "!"
                 str = str + "!"
              elseif test[n] = "."
                 str = str + "."
              else
                 str = str + lower(substr(plaintext, pos, 1))
              ok
        next
        return str

Output:

Plaintext : ABCDEFGHIJKLMNOPQRSTUVWXYZ
Ciphertext : ZEBRASCDFGHIJKLMNOPQTUVWXY
Test : flee at once. we are discovered!
Encoded : SIAA ZQ LKBA. VA ZOA RFPBLUAOAR!
Decoded : flee at once. we are discovered!

RISC-V Assembly

# 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"

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
» '→CIPHER' STO 

« ""
  1 3 PICK SIZE FOR j
     OVER j DUP SUB 
     CipherKey SWAP POS 31 + CHR +
  NEXT SWAP DROP
» 'CIPHER→' STO 

« "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
  →CIPHER DUP CIPHER→
» 'TASK' STO
Output:
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!"

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)
Output:
"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."

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 =
    """"It was still dark, in the early morning hours of the twenty-second of December
      | 1946, on the second floor of the house at Schilderskade 66 in our town,
      | when the hero of this story, Frits van Egters, awoke."""".stripMargin

  val enc = encode(text)
  println("Encoded: " + enc)
  println("Decoded: " + decode(enc))

  private def encode(s: String) = {
    val sb = new StringBuilder(s.length)
    s.map {
      case c if (' ' to '~').contains(c) => sb.append(key(c.toInt - 32))
      case _ =>
    }
    sb.toString
  }

  private def decode(s: String) = {
    val sb = new StringBuilder(s.length)
    s.map {
      case c if (' ' to '~').contains(c) =>
        sb.append((key.indexOf(c.toInt) + 32).toChar)
      case _ =>
    }
    sb.toString
  }
}
Output:
See it running in your browser by ScalaFiddle (JavaScript, non JVM) or by Scastie (JVM).

Sidef

Translation of: Julia
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"

    func encode(String s) {
        var r = ""
        s.each {|c|
            r += key[c.ord - 32]
        }
        return r
    }

    func decode(String s) {
        var r = ""
        s.each {|c|
            r += (key.first_index { _ == c } + 32 -> chr)
        }
        return r
    }
}


with ("The quick brown fox jumps over the lazy dog, who barks VERY loudly!") { |s|
    var enc = SubstitutionCipher::encode(s)
    var dec = SubstitutionCipher::decode(enc)
    say("Original: ", s, "\n -> Encoded: ", enc, "\n -> Decoded: ", dec)
}
Output:
Original: The quick brown fox jumps over the lazy dog, who barks VERY loudly!
 -> 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!

Tcl

Here we implement a SubCipher class with three public methods:

  • key ?newkey? -- set or return the current substitution key. This validates the key for correspondence with the alphabet, returning an error if something is not right.
  • enc plaintext -- encrypt text with the current key
  • dec ciphertext -- decrypt text with the current key

The default alphabet is a-zA-Z, 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.

oo::class create SubCipher {
    variable Alphabet
    variable Key
    variable EncMap
    variable DecMap
    constructor {{alphabet abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ} {cipherbet ""}} {
        set Alphabet $alphabet
        if {$cipherbet eq ""} {
            my key [my RandomKey]
        } else {
            my key $cipherbet
        }
    }
    method key args {
        if {$args eq ""} {
            return $Key
        } elseif {[llength $args] > 1} {
            throw {TCL WRONGARGS} "Expected \"[self class] key\" or \"[self class]\" key keystring"
        }
        lassign $args s

        set size [string length $Alphabet]
        if {[string length $s] != $size} {
            return -code error "Key must be $size chars long!"
        }
        set encmap {}
        set decmap {}
        foreach c [split $Alphabet {}] e [split $s {}] {
            dict set encmap $c $e
            dict set decmap $e $c
        }
        if {[dict size $encmap] != $size} {
            return -code error "Alphabet has repeating characters!"
        }
        if {[dict size $decmap] != $size} {
            return -code error "Key has repeating characters!"
        }
        set Key $s
        set EncMap $encmap
        set DecMap $decmap
    }
    method RandomKey {} {
        set chars $Alphabet
        set key {}
        for {set n [string length $chars]} {$n > 0} {incr n -1} {
            set i [expr {int(rand()*$n)}]
            append key [string index $chars $i]
            set chars [string range $chars 0 $i-1][string range $chars $i+1 end]
        }
        return $key
    }

    method enc {s} {
        string map $EncMap $s
    }
    method dec {s} {
        string map $DecMap $s
    }
}

Testing looks like this:

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"
Output:
Original:

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.

----

Ciphered:

eVv yzhQzGwm KnLjDFvF lKZV ZVv CvuKGn MgA/rKnDc mJmZvw Gzv Xzvv mhXZlGzv;
ZVv vcGLZ FKmZzKuDZKhn Zvzwm Xhz vGLV yzhQzGw Gzv FvmLzKuvF Kn ZVv
KnFKOKFDGj XKjvm Kn /Dmz/mVGzv/FhL/*/LhyJzKQVZ.

CvuKGn MgA/rKnDc Lhwvm lKZV TbHIrAeWrY gI ETUUTgeY, Zh ZVv vcZvnZ
yvzwKZZvF uJ GyyjKLGujv jGl.

----

Decrypted:

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.

----

Key:
GuLFvXQVKRNjwnhyozmZDOlcJBTbfCWdMkxqprtgIasUHeAiESYP
----

VBScript

Not too efficient. It generates the key string as an array of ASCII codes. Uses the same routine to encode and to decode.

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)
Output:
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)

V (Vlang)

Translation of: Kotlin
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()
}
Output:
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!

Wren

Translation of: Kotlin
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|
    var res = ""
    for (c in s) res = res + key[c.bytes[0] - 32]
    return res
}

var decode = Fn.new { |s|
    var res = ""
    for (c in s) res = res + String.fromByte(key.indexOf(c) + 32)
    return res
}

var s = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
var enc = encode.call(s)
System.print("Encoded:  %(enc)")
System.print("Decoded:  %(decode.call(enc))")
Output:
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!

zkl

class SubstitutionCipher{
   // 92 characters: " !"#$%&" ... "xyz{|}", doesn't include "~"
   const KEY="]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"
             "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";
   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 } }) }
}
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 "
      "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.";
encoded:=SubstitutionCipher.encode(text);
println(  "Encoded: ",encoded);
println("\nDecoded: ",SubstitutionCipher.decode(encoded));
Output:
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

Decoded: 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 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.