Caesar cipher: Difference between revisions

130,183 bytes added ,  1 month ago
(Added XLISP)
(234 intermediate revisions by 100 users not shown)
Line 1:
{{task|Encryption}} [[Category:String manipulation]]
{{task|Encryption}}
 
 
;Task:
Implement a [[wp:Caesar cipher|Caesar cipher]], both encoding and decoding. <br>
The key is an integer from 1 to 25.
Line 8 ⟶ 12:
<br>So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
 
This simple "monoalphabeticmono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
 
Caesar cipher is identical to [[Vigenère cipher]] with a key of length 1. <br>
Line 19 ⟶ 23:
* [[Vigenère Cipher/Cryptanalysis]]
<br><br>
=={{header|8th}}==
<syntaxhighlight lang="forth">\ Ensure the output char is in the correct range:
: modulate \ char base -- char
tuck n:- 26 n:+ 26 n:mod n:+ ;
 
\ Symmetric Caesar cipher. Input is text and number of characters to advance
\ (or retreat, if negative). That value should be in the range 1..26
: caesar \ intext key -- outext
>r
(
\ Ignore anything below '.' as punctuation:
dup '. n:> if
\ Do the conversion
dup r@ n:+ swap
\ Wrap appropriately
'A 'Z between if 'A else 'a then modulate
then
) s:map rdrop ;
 
"The five boxing wizards jump quickly!"
dup . cr
1 caesar dup . cr
-1 caesar . cr
bye</syntaxhighlight>
{{out}}
<pre>
The five boxing wizards jump quickly!
Uif gjwf cpyjoh xjabset kvnq rvjdlmz!
The five boxing wizards jump quickly!
</pre>
=={{header|11l}}==
<syntaxhighlight lang="11l">F caesar(string, =key, decode = 0B)
I decode
key = 26 - key
 
V r = ‘ ’ * string.len
L(c) string
r[L.index] = S c
‘a’..‘z’
Char(code' (c.code - ‘a’.code + key) % 26 + ‘a’.code)
‘A’..‘Z’
Char(code' (c.code - ‘A’.code + key) % 26 + ‘A’.code)
E
c
R r
 
V msg = ‘The quick brown fox jumped over the lazy dogs’
print(msg)
V enc = caesar(msg, 11)
print(enc)
print(caesar(enc, 11, decode' 1B))</syntaxhighlight>
{{out}}
<pre>
The quick brown fox jumped over the lazy dogs
Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozrd
The quick brown fox jumped over the lazy dogs
</pre>
=={{header|360 Assembly}}==
A good example of the use of TR instruction to translate a character.
<syntaxhighlight lang="360asm">* Caesar cypher 04/01/2019
CAESARO PROLOG
XPRNT PHRASE,L'PHRASE print phrase
LH R3,OFFSET offset
BAL R14,CYPHER call cypher
LNR R3,R3 -offset
BAL R14,CYPHER call cypher
EPILOG
CYPHER LA R4,REF(R3) @ref+offset
MVC A,0(R4) for A to I
MVC J,9(R4) for J to R
MVC S,18(R4) for S to Z
TR PHRASE,TABLE translate
XPRNT PHRASE,L'PHRASE print phrase
BR R14 return
OFFSET DC H'22' between -25 and +25
PHRASE DC CL37'THE FIVE BOXING WIZARDS JUMP QUICKLY'
DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
REF DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
TABLE DC CL256' ' translate table for TR
ORG TABLE+C'A'
A DS CL9
ORG TABLE+C'J'
J DS CL9
ORG TABLE+C'S'
S DS CL8
ORG
YREGS
END CAESARO</syntaxhighlight>
{{out}}
<pre>
THE FIVE BOXING WIZARDS JUMP QUICKLY
PDA BERA XKTEJC SEVWNZO FQIL MQEYGHU
THE FIVE BOXING WIZARDS JUMP QUICKLY
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program caresarcode64.s */
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ KEY, 23
.equ STRINGSIZE, 500
/************************************/
/* Initialized data */
/************************************/
.data
szMessString: .asciz "String :\n"
szMessEncrip: .asciz "\nEncrypted :\n"
szMessDecrip: .asciz "\nDecrypted :\n"
szString1: .asciz "The quick brown fox jumps over the lazy dog."
 
szCarriageReturn: .asciz "\n"
/************************************/
/* UnInitialized data */
/************************************/
.bss
szString2: .skip STRINGSIZE
szString3: .skip STRINGSIZE
/************************************/
/* code section */
/************************************/
.text
.global main
main:
ldr x0,qAdrszMessString // display message
bl affichageMess
ldr x0,qAdrszString1 // display string
bl affichageMess
ldr x0,qAdrszString1
ldr x1,qAdrszString2
mov x2,#KEY // key
bl encrypt
ldr x0,qAdrszMessEncrip
bl affichageMess
ldr x0,qAdrszString2 // display string
bl affichageMess
ldr x0,qAdrszString2
ldr x1,qAdrszString3
mov x2,#KEY // key
bl decrypt
ldr x0,qAdrszMessDecrip
bl affichageMess
ldr x0,qAdrszString3 // display string
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc 0 // perform system call
qAdrszMessString: .quad szMessString
qAdrszMessDecrip: .quad szMessDecrip
qAdrszMessEncrip: .quad szMessEncrip
qAdrszString1: .quad szString1
qAdrszString2: .quad szString2
qAdrszString3: .quad szString3
qAdrszCarriageReturn: .quad szCarriageReturn
/******************************************************************/
/* encrypt strings */
/******************************************************************/
/* x0 contains the address of the string1 */
/* x1 contains the address of the encrypted string */
/* x2 contains the key (1-25) */
encrypt:
stp x3,lr,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x3,#0 // counter byte string 1
1:
ldrb w4,[x0,x3] // load byte string 1
cmp w4,#0 // zero final ?
bne 2f
strb w4,[x1,x3]
mov x0,x3
b 100f
2:
cmp w4,#65 // < A ?
bge 3f
strb w4,[x1,x3]
add x3,x3,#1
b 1b // and loop
3:
cmp x4,#90 // > Z
bgt 4f
add x4,x4,x2 // add key
cmp x4,#90 // > Z
sub x5,x4,26
csel x4,x5,x4,gt
//subgt x4,#26
strb w4,[x1,x3]
add x3,x3,#1
b 1b
4:
cmp x4,#97 // < a ?
bge 5f
strb w4,[x1,x3]
add x3,x3,#1
b 1b
5:
cmp x4,#122 //> z
ble 6f
strb w4,[x1,x3]
add x3,x3,#1
b 1b
6:
add x4,x4,x2
cmp x4,#122
sub x5,x4,26
csel x4,x5,x4,gt
//subgt x4,#26
strb w4,[x1,x3]
add x3,x3,#1
b 1b
 
100:
ldp x4,x5,[sp],16 // restaur registers
ldp x3,lr,[sp],16 // restaur registers
ret
/******************************************************************/
/* decrypt strings */
/******************************************************************/
/* x0 contains the address of the encrypted string1 */
/* x1 contains the address of the decrypted string */
/* x2 contains the key (1-25) */
decrypt:
stp x3,lr,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x3,#0 // counter byte string 1
1:
ldrb w4,[x0,x3] // load byte string 1
cmp x4,#0 // zero final ?
bne 2f
strb w4,[x1,x3]
mov x0,x3
b 100f
2:
cmp x4,#65 // < A ?
bge 3f
strb w4,[x1,x3]
add x3,x3,#1
b 1b // and loop
3:
cmp x4,#90 // > Z
bgt 4f
sub x4,x4,x2 // substract key
cmp x4,#65 // < A
add x5,x4,26
csel x4,x5,x4,lt
//addlt x4,#26
strb w4,[x1,x3]
add x3,x3,#1
b 1b
4:
cmp x4,#97 // < a ?
bge 5f
strb w4,[x1,x3]
add x3,x3,#1
b 1b
5:
cmp x4,#122 // > z
ble 6f
strb w4,[x1,x3]
add x3,x3,#1
b 1b
6:
sub x4,x4,x2 // substract key
cmp x4,#97 // < a
add x5,x4,26
csel x4,x5,x4,lt
//addlt x4,#26
strb w4,[x1,x3]
add x3,x3,#1
b 1b
 
100:
ldp x4,x5,[sp],16 // restaur registers
ldp x3,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../includeARM64.inc"
 
</syntaxhighlight>
{{Out}}
<pre>
String :
The quick brown fox jumps over the lazy dog.
Encrypted :
Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald.
Decrypted :
The quick brown fox jumps over the lazy dog.
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">CHAR FUNC Shift(CHAR c BYTE code)
CHAR base
 
IF c>='a AND c<='z THEN
base='a
ELSEIF c>='A AND c<='Z THEN
base='A
ELSE
RETURN (c)
FI
c==+code-base
c==MOD 26
RETURN (c+base)
 
PROC Encrypt(CHAR ARRAY in,out BYTE code)
INT i
 
out(0)=in(0)
FOR i=1 TO in(0)
DO
out(i)=Shift(in(i),code)
OD
RETURN
 
PROC Decrypt(CHAR ARRAY in,out BYTE code)
Encrypt(in,out,26-code)
RETURN
 
PROC Test(CHAR ARRAY in BYTE code)
CHAR ARRAY enc(256),dec(256)
 
PrintE("Original:") PrintE(in)
Encrypt(in,enc,code)
PrintF("Encrypted code=%B:%E",code) PrintE(enc)
Decrypt(enc,dec,code)
PrintF("Decrypted code=%B:%E",code) PrintE(dec)
PutE()
RETURN
 
PROC Main()
Test("The quick brown fox jumps over the lazy dog.",23)
Test("The quick brown fox jumps over the lazy dog.",5)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Caesar_cipher.png Screenshot from Atari 8-bit computer]
<pre>
Original:
The quick brown fox jumps over the lazy dog.
Encrypted code=23:
Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald.
Decrypted code=23:
The quick brown fox jumps over the lazy dog.
 
Original:
The quick brown fox jumps over the lazy dog.
Encrypted code=5:
Ymj vznhp gwtbs ktc ozrux tajw ymj qfed itl.
Decrypted code=5:
The quick brown fox jumps over the lazy dog.
</pre>
=={{header|Ada}}==
<syntaxhighlight lang="ada">-- Caesar Cipher Implementation in Ada
<lang Ada>with Ada.Text_IO;
 
with Ada.Text_IO; use Ada.Text_IO;
procedure Caesar is
 
procedure Caesar is
type M26 is mod 26;
 
-- Base function to encrypt a character
function To_M26(C: Character; Offset: Character) return M26 is
function Cipher(Char_To_Encrypt: Character; Shift: Integer; Base: Character) return Character is
Base_Pos : constant Natural := Character'Pos(Base);
begin
return M26Character'Val((Character'Pos(CChar_To_Encrypt) + Shift -Character'Pos(Offset Base_Pos) mod 26 + Base_Pos);
end To_M26Cipher;
 
-- Function to encrypt a character
function To_Character(Value: in M26; Offset: Character)
function Encrypt_Char(Char_To_Encrypt: Character; Shift: Integer) return Character is
begin
case Char_To_Encrypt is
return Character'Val(Integer(Value)+Character'Pos(Offset));
when 'A'..'Z' =>
end To_Character;
-- Encrypt uppercase letters
 
return Cipher (Char_To_Encrypt, Shift, 'A');
function Encrypt (Plain: String; Key: M26) return String is
Ciph: String(Plain when 'Range);a'..'z' =>
-- Encrypt lowercase letters
return Cipher (Char_To_Encrypt, Shift, 'a');
when others =>
-- Leave other characters unchanged
return Char_To_Encrypt;
end case;
end Encrypt_Char;
 
-- Function to decrypt a character
function Decrypt_Char(Char_To_Decrypt: Character; Shift: Integer) return Character is
begin
return Encrypt_Char(Char_To_Decrypt, -Shift);
for I in Plain'Range loop
end Decrypt_Char;
case Plain(I) is
when 'A' .. 'Z' =>
Ciph(I) := To_Character(To_M26(Plain(I), 'A')+Key, 'A');
when 'a' .. 'z' =>
Ciph(I) := To_Character(To_M26(Plain(I), 'a')+Key, 'a');
when others =>
Ciph(I) := Plain(I);
end case;
end loop;
return Ciph;
end Encrypt;
 
TextMessage: constant String := Ada.Text_IO.Get_Line;
KeyShift: M26Positive := 3; -- Default key from "Commentarii de Bello Gallico" shift cipher
-- Shift value (can be any positive integer)
 
Encrypted_Message: String(Message'Range);
begin -- Caesar main program
Decrypted_Message: String(Message'Range);
begin
-- Encrypt the message
for I in Message'Range loop
Encrypted_Message(I) := Encrypt_Char(Message(I), Shift);
end loop;
 
-- Decrypt the encrypted message
Ada.Text_IO.Put_Line("Plaintext ------------>" & Text);
for I in Message'Range loop
Text := Encrypt(Text, Key);
Decrypted_Message(I) := Decrypt_Char(Encrypted_Message(I), Shift);
Ada.Text_IO.Put_Line("Ciphertext ----------->" & Text);
end loop;
Ada.Text_IO.Put_Line("Decrypted Ciphertext ->" & Encrypt(Text, -Key));
 
-- Display results
end Caesar;</lang>
Put_Line("Plaintext: " & Message);
Put_Line("Ciphertext: " & Encrypted_Message);
Put_Line("Decrypted Ciphertext: " & Decrypted_Message);
 
end Caesar;
</syntaxhighlight>
{{out}}
<pre>> ./caesar
The five boxing wizards jump quickly
Plaintext: ------------>The five boxing wizards jump quickly
Ciphertext: ----------->Wkh ilyh eralqj zlcdugv mxps txlfnob
Decrypted Ciphertext: ->The five boxing wizards jump quickly</pre>
</pre>
 
=={{header|ALGOL 68}}==
Line 78 ⟶ 455:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<langsyntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
 
program caesar: BEGIN
Line 120 ⟶ 497:
printf(($gl$, "Decrypted Ciphertext ->" + encrypt(text, -key)))
 
END #caesar#</langsyntaxhighlight>
{{out}}
<pre>
Line 127 ⟶ 504:
Decrypted Ciphertext ->The five boxing wizards jump quickly
</pre>
 
=={{header|APL}}==
<langsyntaxhighlight lang="apl">
∇CAESAR[⎕]∇
Line 137 ⟶ 513:
[3] A←V
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 158 ⟶ 534:
Esl dyar: dpyargmlyj icwq qugraf dpmk TOODQ BZRD rm jmucp ayqc.
</pre>
=={{header|AppleScript}}==
 
<syntaxhighlight lang="applescript">(* Only non-accented English letters are altered here. *)
 
on caesarDecipher(txt, |key|)
return caesarEncipher(txt, -|key|)
end caesarDecipher
 
on caesarEncipher(txt, |key|)
set codePoints to id of txt
set keyPlus25 to |key| mod 26 + 25
repeat with thisCode in codePoints
tell thisCode mod 32
if ((it < 27) and (it > 0) and (thisCode div 64 is 1)) then ¬
set thisCode's contents to thisCode - it + (it + keyPlus25) mod 26 + 1
end tell
end repeat
return string id codePoints
end caesarEncipher
 
-- Test code:
set txt to "ROMANES EUNT DOMUS!
The quick brown fox jumps over the lazy dog."
set |key| to 9
 
set enciphered to caesarEncipher(txt, |key|)
set deciphered to caesarDecipher(enciphered, |key|)
return "Text: '" & txt & ("'" & linefeed & "Key: " & |key| & linefeed & linefeed) & (enciphered & linefeed & deciphered)</syntaxhighlight>
 
{{output}}
 
<syntaxhighlight lang="applescript">"Text: 'ROMANES EUNT DOMUS!
The quick brown fox jumps over the lazy dog.'
Key: 9
 
AXVJWNB NDWC MXVDB!
Cqn zdrlt kaxfw oxg sdvyb xena cqn ujih mxp.
ROMANES EUNT DOMUS!
The quick brown fox jumps over the lazy dog."</syntaxhighlight>
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="applesoftbasic">100 INPUT ""; T$
 
110 LET K% = RND(1) * 25 + 1
120 PRINT "ENCODED WITH ";
130 GOSUB 200ENCODED
 
140 LET K% = 26 - K%
150 PRINT "DECODED WITH ";
160 GOSUB 200DECODED
 
170 END
 
REM ENCODED/DECODED
200 PRINT "CAESAR " K%;
210 LET K$(1) = " (ROT-13)"
220 PRINT K$(K% = 13)
230 GOSUB 300CAESAR
240 PRINT T$
250 RETURN
 
REM CAESAR T$ K%
300 FOR I = 1 TO LEN(T$)
310 LET C$ = MID$(T$, I, 1)
320 GOSUB 400ENCODE
330 LET L = I - 1
340 LET T$(0) = MID$(T$, 1, L)
350 LET L = I + 1
360 LET T$ = C$ + MID$(T$, L)
370 LET T$ = T$(0) + T$
380 NEXT I
390 RETURN
 
REM ENCODE C$ K%
400 LET C = ASC(C$)
410 LET L = (C > 95) * 32
420 LET C = C - L
430 IF C < 65 THEN RETURN
440 IF C > 90 THEN RETURN
450 LET C = C + K%
460 IF C > 90 THEN C = C - 26
470 LET C$ = CHR$(C + L)
480 RETURN</syntaxhighlight>
{{out}}
<pre>]RUN
The quick brown fox jumps over the lazy dog.
ENCODED WITH CAESAR 12
Ftq cguow ndaiz raj vgybe ahqd ftq xmlk pas.
DECODED WITH CAESAR 14
The quick brown fox jumps over the lazy dog.
 
]?RND(-6):RUN
4.48226274E-08
PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS
ENCODED WITH CAESAR 13 (ROT-13)
CNPX ZL OBK JVGU SVIR QBMRA YVDHBE WHTF
DECODED WITH CAESAR 13 (ROT-13)
PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS
 
]K%=1:GOTO120
ENCODED WITH CAESAR 1
QBDL NZ CPY XJUI GJWF EPAFO MJRVPS KVHT
DECODED WITH CAESAR 25
PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS</pre>
=={{header|Arc}}==
<syntaxhighlight lang="arc">
(= rot (fn (L N)
(if
(and (<= 65 L) (>= 90 L))
(do
(= L (- L 65))
(= L (mod (+ N L) 26))
(= L (+ L 65)))
(and (<= 97 L) (>= 122 L))
(do
(= L (- L 97))
(= L (mod (+ N L) 26))
(= L (+ L 97))))
L))
 
(= caesar (fn (text (o shift))
(unless shift (= shift 13))
(= output (map [int _] (coerce text 'cons)))
(= output (map [rot _ shift] output))
(string output)
))
</syntaxhighlight>
 
{{Out}}
<syntaxhighlight lang="arc">
(caesar "The quick brown fox jumps over the lazy dog.")
"Gur dhvpx oebja sbk whzcf bire gur ynml qbt."
</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program caresarcode.s */
 
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
 
.equ STRINGSIZE, 500
 
/* Initialized data */
.data
szMessString: .asciz "String :\n"
szMessEncrip: .asciz "\nEncrypted :\n"
szMessDecrip: .asciz "\nDecrypted :\n"
szString1: .asciz "Why study medicine because there is internet ?"
 
szCarriageReturn: .asciz "\n"
 
/* UnInitialized data */
.bss
szString2: .skip STRINGSIZE
szString3: .skip STRINGSIZE
/* code section */
.text
.global main
main:
 
ldr r0,iAdrszMessString @ display message
bl affichageMess
ldr r0,iAdrszString1 @ display string
bl affichageMess
ldr r0,iAdrszString1
ldr r1,iAdrszString2
mov r2,#20 @ key
bl encrypt
ldr r0,iAdrszMessEncrip
bl affichageMess
ldr r0,iAdrszString2 @ display string
bl affichageMess
ldr r0,iAdrszString2
ldr r1,iAdrszString3
mov r2,#20 @ key
bl decrypt
ldr r0,iAdrszMessDecrip
bl affichageMess
ldr r0,iAdrszString3 @ display string
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessString: .int szMessString
iAdrszMessDecrip: .int szMessDecrip
iAdrszMessEncrip: .int szMessEncrip
iAdrszString1: .int szString1
iAdrszString2: .int szString2
iAdrszString3: .int szString3
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* encrypt strings */
/******************************************************************/
/* r0 contains the address of the string1 */
/* r1 contains the address of the encrypted string */
/* r2 contains the key (1-25) */
encrypt:
push {r3,r4,lr} @ save registers
mov r3,#0 @ counter byte string 1
1:
ldrb r4,[r0,r3] @ load byte string 1
cmp r4,#0 @ zero final ?
streqb r4,[r1,r3]
moveq r0,r3
beq 100f
cmp r4,#65 @ < A ?
strltb r4,[r1,r3]
addlt r3,#1
blt 1b
cmp r4,#90 @ > Z
bgt 2f
add r4,r2 @ add key
cmp r4,#90 @ > Z
subgt r4,#26
strb r4,[r1,r3]
add r3,#1
b 1b
2:
cmp r4,#97 @ < a ?
strltb r4,[r1,r3]
addlt r3,#1
blt 1b
cmp r4,#122 @> z
strgtb r4,[r1,r3]
addgt r3,#1
bgt 1b
add r4,r2
cmp r4,#122
subgt r4,#26
strb r4,[r1,r3]
add r3,#1
b 1b
 
100:
pop {r3,r4,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* decrypt strings */
/******************************************************************/
/* r0 contains the address of the encrypted string1 */
/* r1 contains the address of the decrypted string */
/* r2 contains the key (1-25) */
decrypt:
push {r3,r4,lr} @ save registers
mov r3,#0 @ counter byte string 1
1:
ldrb r4,[r0,r3] @ load byte string 1
cmp r4,#0 @ zero final ?
streqb r4,[r1,r3]
moveq r0,r3
beq 100f
cmp r4,#65 @ < A ?
strltb r4,[r1,r3]
addlt r3,#1
blt 1b
cmp r4,#90 @ > Z
bgt 2f
sub r4,r2 @ substract key
cmp r4,#65 @ < A
addlt r4,#26
strb r4,[r1,r3]
add r3,#1
b 1b
2:
cmp r4,#97 @ < a ?
strltb r4,[r1,r3]
addlt r3,#1
blt 1b
cmp r4,#122 @ > z
strgtb r4,[r1,r3]
addgt r3,#1
bgt 1b
sub r4,r2 @ substract key
cmp r4,#97 @ < a
addlt r4,#26
strb r4,[r1,r3]
add r3,#1
b 1b
 
100:
pop {r3,r4,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
 
</syntaxhighlight>
=={{header|Arturo}}==
{{trans|11l}}
<syntaxhighlight lang="rebol">ia: to :integer `a`
iA: to :integer `A`
lowAZ: `a`..`z`
uppAZ: `A`..`Z`
 
caesar: function [s, xx][
k: (not? null? attr 'decode)? -> 26-xx -> xx
result: new ""
loop s 'i [
(in? i lowAZ)? -> 'result ++ to :char ia + (k + (to :integer i) - ia) % 26
[
(in? i uppAZ)? -> 'result ++ to :char iA + (k + (to :integer i) - iA) % 26
-> 'result ++ i
]
]
return result
]
 
msg: "The quick brown fox jumped over the lazy dogs"
print ["Original :" msg]
enc: caesar msg 11
print [" Encoded :" enc]
print [" Decoded :" caesar.decode enc 11]</syntaxhighlight>
 
{{out}}
 
<pre>Original : The quick brown fox jumped over the lazy dogs
Encoded : Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozrd
Decoded : The quick brown fox jumped over the lazy dogs</pre>
=={{header|Astro}}==
<syntaxhighlight lang="python">fun caesar(s, k, decode: false):
if decode:
k = 26 - k
result = ''
for i in s.uppercase() where 65 <= ord(i) <= 90:
result.push! char(ord(i) - 65 + k) mod 26 + 65
return result
 
let message = "The quick brown fox jumped over the lazy dogs"
let encrypted = caesar(msg, 11)
let decrypted = caesar(enc, 11, decode: true)
 
print(message, encrypted, decrypted, sep: '\n')</syntaxhighlight>
=={{header|AutoHotkey}}==
This ungodly solution is an attempt at code-golf. It requires input to be all-caps alphabetic, only works on AutoHotkey_L Unicode, and might not run on x64
<syntaxhighlight lang="autohotkey">n=2
<lang AutoHotkey>n=2
s=HI
t:=&s
While *t
o.=Chr(Mod(*t-65+n,26)+65),t+=2
MsgBox % o</langsyntaxhighlight>
This next one is much more sane and handles input very well, including case.
<langsyntaxhighlight AutoHotkeylang="autohotkey">Caesar(string, n){
Loop Parse, string
{
Line 180 ⟶ 910:
}
 
MsgBox % Caesar("h i", 2) "`n" Caesar("Hi", 20)</langsyntaxhighlight>
{{out}}<pre>j k
Bc</pre>
 
=={{header|AutoIt}}==
 
The Ceasar Funktion can enrcypt and decrypt, standart is Encryption, to Decrypt set third parameter to False
<langsyntaxhighlight lang="autoit">
$Caesar = Caesar("Hi", 2, True)
MsgBox(0, "Caesar", $Caesar)
Line 220 ⟶ 949:
Return $sLetters
EndFunc ;==>Caesar
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">
#!/usr/bin/awk -f
 
Line 266 ⟶ 994:
return s
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 274 ⟶ 1,002:
clear: MY HOVERCRAFT IS FULL OF EELS.
</pre>
 
=={{header|Babel}}==
 
<langsyntaxhighlight lang="babel">((main
{"The quick brown fox jumps over the lazy dog.\n"
dup <<
Line 328 ⟶ 1,055:
<- 0x60 cugt ->
0x7b cult
cand }))</langsyntaxhighlight>
 
{{out}}
Line 334 ⟶ 1,061:
Kyv hlztb sifne wfo aldgj fmvi kyv crqp ufx.
The quick brown fox jumps over the lazy dog.</pre>
=={{header|BaCon}}==
<syntaxhighlight lang="qbasic">CONST lc$ = "abcdefghijklmnopqrstuvwxyz"
CONST uc$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
CONST txt$ = "The quick brown fox jumps over the lazy dog."
=={{header|BBC BASIC}}==
 
<lang bbcbasic> plaintext$ = "Pack my box with five dozen liquor jugs"
FUNCTION Ceasar$(t$, k)
 
lk$ = MID$(lc$ & lc$, k+1, 26)
uk$ = MID$(uc$ & uc$, k+1, 26)
 
RETURN REPLACE$(t$, lc$ & uc$, lk$ & uk$, 2)
 
END FUNCTION
 
tokey = RANDOM(25)+1
PRINT "Encrypting text with key: ", tokey
 
en$ = Ceasar$(txt$, tokey)
 
PRINT "Encrypted: ", en$
PRINT "Decrypted: ", Ceasar$(en$, 26-tokey)</syntaxhighlight>
{{out}}
<pre>
user@host $ bacon ceasar
Converting 'ceasar.bac'... done, 20 lines were processed in 0.015 seconds.
Compiling 'ceasar.bac'... cc -c ceasar.bac.c
cc -o ceasar ceasar.bac.o -lbacon -lm
Done, program 'ceasar' ready.
user@host $ ./ceasar
Encrypting text with key: 23
Encrypted: Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald.
Decrypted: The quick brown fox jumps over the lazy dog.
</pre>
=={{header|bash}}==
Caesar cipher bash implementation
{{works with|GNU bash, version 4}}
 
<syntaxhighlight lang="bash">
caesar_cipher() {
 
# michaeltd 2019-11-30
# https://en.wikipedia.org/wiki/Caesar_cipher
# E n ( x ) = ( x + n ) mod 26.
# D n ( x ) = ( x − n ) mod 26.
 
local -a _ABC=( "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" )
local -a _abc=( "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" )
 
local _out
 
if (( $# < 3 )) || [[ "$1" != "-e" && "$1" != "-d" ]] || (( $2 < 1 || $2 > 25 )); then
echo "Usage: ${FUNCNAME[0]} -e|-d rotation (1-25) argument[(s)...]" >&2
return 1
fi
 
_func="${1}"; shift
_rotval="${1}"; shift
 
while [[ -n "${1}" ]]; do
for (( i = 0; i < ${#1}; i++ )); do
for (( x = 0; x < ${#_abc[*]}; x++ )); do
case "${_func}" in
"-e")
[[ "${1:$i:1}" == "${_ABC[$x]}" ]] && _out+="${_ABC[(( ( x + _rotval ) % 26 ))]}" && break
[[ "${1:$i:1}" == "${_abc[$x]}" ]] && _out+="${_abc[(( ( x + _rotval ) % 26 ))]}" && break;;
"-d")
[[ "${1:$i:1}" == "${_ABC[$x]}" ]] && _out+="${_ABC[(( ( x - _rotval ) % 26 ))]}" && break
[[ "${1:$i:1}" == "${_abc[$x]}" ]] && _out+="${_abc[(( ( x - _rotval ) % 26 ))]}" && break;;
esac
# If char has not been found by now lets add it as is.
(( x == ${#_abc[*]} - 1 )) && _out+="${1:$i:1}"
done
done
_out+=" "
shift
done
echo "${_out[*]}"
}
 
</syntaxhighlight>
{{in}}
<pre>
caesar_cipher -e 13 "Hello World!"
</pre>
{{out}}
<pre>
Uryyb Jbeyq!
</pre>
 
{{in}}
<pre>
caesar_cipher -d 13 "Uryyb Jbeyq!"
</pre>
{{out}}
<pre>
Hello World!
</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="text">
# Caeser Cipher
# basic256 1.1.4.0
 
dec$ = ""
type$ = "cleartext "
 
input "If decrypting enter " + "<d> " + " -- else press enter > ",dec$ # it's a klooj I know...
input "Enter offset > ", iOffset
 
if dec$ = "d" then
iOffset = 26 - iOffset
type$ = "ciphertext "
end if
 
input "Enter " + type$ + "> ", str$
 
str$ = upper(str$) # a bit of a cheat really, however old school encryption is always upper case
len = length(str$)
 
for i = 1 to len
iTemp = asc(mid(str$,i,1))
if iTemp > 64 AND iTemp < 91 then
iTemp = ((iTemp - 65) + iOffset) % 26
print chr(iTemp + 65);
else
print chr(iTemp);
end if
next i
</syntaxhighlight>
{{out}}
<pre>
Enter offset > 21
Enter cleartext > My hovercraft is full of eels.
HT CJQZMXMVAO DN APGG JA ZZGN.
 
Enter offset > 21
Enter ciphertext > HT CJQZMXMVAO DN APGG JA ZZGN.
MY HOVERCRAFT IS FULL OF EELS.
</pre>
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> plaintext$ = "Pack my box with five dozen liquor jugs"
PRINT plaintext$
Line 358 ⟶ 1,228:
NEXT
= text$
</syntaxhighlight>
</lang>
{{out}}
<pre>Pack my box with five dozen liquor jugs
Line 364 ⟶ 1,234:
Pack my box with five dozen liquor jugs</pre>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|QBasic}}
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">
10 rem Caesar cipher
20 cls
30 dec$ = ""
40 type$ = "cleartext "
50 print "If decrypting enter "+"<d> "+" -- else press enter "; : input dec$
60 input "Enter offset > ",ioffset
70 if dec$ = "d" then
80 ioffset = 26-ioffset
90 type$ = "ciphertext "
100 endif
110 print "Enter "+type$+"> ";
120 input cad$
130 cad$ = ucase$(cad$)
140 longitud = len(cad$)
150 for i = 1 to longitud
160 itemp = asc(mid$(cad$,i,1))
170 if itemp > 64 and itemp < 91 then
180 itemp = ((itemp-65)+ioffset) mod 26
190 print chr$(itemp+65);
200 else
210 print chr$(itemp);
220 endif
230 next i
240 print
250 end
</syntaxhighlight>
{{out}}
<pre> >run
If decrypting enter <d> -- else press enter ?
Enter offset > 21
Enter cleartext > ? My hovercraft is full of eels.
HT CJQZMXMVAO DN APGG JA ZZGN.
>run
If decrypting enter <d> -- else press enter ? d
Enter offset > 21
Enter ciphertext > ? HT CJQZMXMVAO DN APGG JA ZZGN.
MY HOVERCRAFT IS FULL OF EELS.</pre>
 
==={{header|GW-BASIC}}===
{{works with|Chipmunk Basic}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
{{works with|MSX BASIC}}
{{trans|Chipmunk Basic}}
<syntaxhighlight lang="qbasic">10 REM Caesar cipher
20 CLS
30 DEC$ = ""
40 TYPE$ = "cleartext "
50 PRINT "If decrypting enter "+"<d> "+" -- else press enter "; : INPUT DEC$
60 INPUT "Enter offset > "; IOFFSET
70 IF DEC$ = "d" THEN IOFFSET = 26-IOFFSET: TYPE$ = "ciphertext "
110 PRINT "Enter "+TYPE$+"> ";
120 INPUT CAD$
140 LONGITUD = LEN(CAD$)
150 FOR I = 1 TO LONGITUD
160 ITEMP = ASC(MID$(CAD$,I,1))
170 IF ITEMP > 64 AND ITEMP < 91 THEN ITEMP = ((ITEMP-65)+IOFFSET) MOD 26 : PRINT CHR$(ITEMP+65); : ELSE PRINT CHR$(ITEMP);
230 NEXT I
240 PRINT
250 END</syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
=={{header|Beads}}==
<syntaxhighlight lang="beads">beads 1 program 'Caesar cipher'
calc main_init
var str = "The five boxing wizards (🤖) jump quickly."
log "Plain: {str}"
str = Encrypt(str, 3)
log "Encrypted: {str}"
str = Decrypt(str, 3)
log "Decrypted: {str}"
 
// encrypt a string by shifting the letters over by a number of slots
// pass through any characters that are not in the Roman alphabet
calc Encrypt(
input:str --- string to encrypt
nshift --- number of characters to slide over
) : str --- encrypted string
var newStr = ""
loop from:1 to:str_len(input) count:myCount
var unicode : num = from_char(subset(input, from:myCount, len:1))
if unicode >= 65 and unicode <= 90
unicode = mod((unicode - 65 + nshift), 26) + 65
elif unicode >= 97 and unicode <= 122
unicode = mod((unicode - 97 + nshift), 26) + 97
newStr = newStr & to_char(unicode)
return newStr
 
// undo the encryption
calc Decrypt(
input:str
nshift
) : str
// we could also just shift by 26-nshift, same as going in reverse
return Encrypt(input, -nshift)</syntaxhighlight>
{{out}}
<pre>Plain: The five boxing wizards (🤖) jump quickly.
Encrypted: Wkh ilyh eralqj zlcdugv (🤖) mxps txlfnob.
Decrypted: The five boxing wizards (🤖) jump quickly.
</pre>
=={{header|Befunge}}==
Almost direct copy of the [[Vigenère cipher#Befunge|Vigenère cipher]], although the code has been reversed and the first line eliminated because of the simpler key initialisation.
Line 369 ⟶ 1,348:
The text to encrypt is read from stdin, and the key is the first integer on the stack - 11 (<tt>65+</tt>) in the example below.
 
<langsyntaxhighlight lang="befunge">65+>>>>10p100p1>:v:+>#*,#g1#0-#0:#!<<
"`"::_@#!`\*84:<~<$<^+"A"%*2+9<v"{"\`
**-"A"-::0\`\55*`+#^_\0g+"4"+4^>\`*48</langsyntaxhighlight>
 
{{out}}
Line 379 ⟶ 1,358:
The decrypter is essentially identical, except for a change of sign on the last line.
 
<langsyntaxhighlight lang="befunge">65+>>>>10p100p1>:v:+>#*,#g1#0-#0:#!<<
"`"::_@#!`\*84:<~<$<^+"A"%*2+9<v"{"\`
**-"A"-::0\`\55*`+#^_\0g-"4"+4^>\`*48</langsyntaxhighlight>
 
{{out}}
<pre>ESPBFTNVMCZHYQZIUFXAPOZGPCESPWLKJOZRD
THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGS</pre>
=={{header|BQN}}==
<syntaxhighlight lang="bqn">o ← @‿'A'‿@‿'a'‿@ ⋄ m ← 5⥊↕2 ⋄ p ← m⊏∞‿26
Rot ← {i←⊑"A[a{"⍋𝕩 ⋄ i⊑o+p|(𝕨×m)+𝕩-o}⎉0</syntaxhighlight>
 
Example:
 
<syntaxhighlight lang="bqn">3 Rot "We're no strangers to love // You know the rules and so do I"</syntaxhighlight>
<pre>"Zh'uh qr vwudqjhuv wr oryh // Brx nqrz wkh uxohv dqg vr gr L"</pre>
 
([https://mlochbaum.github.io/BQN/try.html#code=byDihpAgQOKAvydBJ+KAv0DigL8nYSfigL9AIOKLhCBtIOKGkCA14qWK4oaVMiDii4QgcCDihpAgbeKKj+KInuKAvzI2ClJvdCDihpAge2nihpDiipEiQVtheyLijYvwnZWpIOKLhCBp4oqRbytwfCjwnZWow5dtKSvwnZWpLW994o6JMAoKMyBSb3QgIldlJ3JlIG5vIHN0cmFuZ2VycyB0byBsb3ZlIC8vIFlvdSBrbm93IHRoZSBydWxlcyBhbmQgc28gZG8gSSIK online REPL])
=={{header|Brainf***}}==
<syntaxhighlight lang="bf"> Author: Ettore Forigo | Hexwell
 
+ start the key input loop
[
memory: | c | 0 | cc | key |
^
 
, take one character of the key
 
:c : condition for further ifs
!= ' ' (subtract 32 (ascii for ' '))
--------------------------------
 
(testing for the condition deletes it so duplication is needed)
[>>+<+<-] duplicate
> |
[<+>-] |
> | :cc : copy of :c
 
[ if :cc
|
> | :key : already converted digits
|
[>++++++++++<-] | multiply by 10
> | |
[<+>-] | |
< | |
|
< | :cc
[-] | clear (making the loop an if)
] |
 
<< :c
 
[>>+<+<-] duplicate
> |
[<+>-] |
> | :cc
 
[ if :cc
---------------- | subtract 16 (difference between ascii for ' ' (already subtracted before) and ascii for '0'
| making '0' 0; '1' 1; etc to transform ascii to integer)
|
[>+<-] | move/add :cc to :key
] |
 
<< :c
]
 
memory: | 0 | 0 | 0 | key |
^
 
>>> :key
 
[<<<+>>>-] move key
 
memory: | key | 0 | 0 | 0 |
^
< ^
+ start the word input loop
[
memory: | key | 0 | c | 0 | cc |
^
 
, take one character of the word
 
:c : condition for further if
!= ' ' (subtract 32 (ascii for ' '))
--------------------------------
 
[>>+<+<-] duplicate
> |
[<+>-] |
> | :cc : copy of :c
 
[ if :cc
| subtract 65 (difference between ascii for ' ' (already subtracted before) and ascii for 'a'; making a 0; b 1; etc)
-----------------------------------------------------------------
|
<<<< | :key
|
[>>>>+<<<+<-] | add :key to :cc := :shifted
> | |
[<+>-] | |
|
| memory: | key | 0 | c | 0 | cc/shifted | 0 | 0 | 0 | 0 | 0 | divisor |
| ^
|
>>>>>>>>> | :divisor
++++++++++++++++++++++++++ | = 26
|
<<<<<< | :shifted
|
| memory: | shifted/remainder | 0 | 0 | 0 | 0 | 0 | divisor |
| ^
|
| shifted % divisor
[ | | while :remainder
| | |
| | | memory: | shifted | 0 | 0 | 0 | 0 | 0 | divisor | 0 |
| | | ^
| | |
[>>>>>>>+<<<<+<<<-] | | | duplicate :cshifted : copy of shifted
| | |
| | | memory: | 0 | 0 | 0 | shifted | 0 | 0 | divisor | cshifted |
| | | ^
>>>>>> | | | :divisor ^
| | |
[<<+>+>-] | | | duplicate
< | | | |
[>+<-] | | | |
< | | | | :cdiv : copy of divisor
| | |
| | | memory: | 0 | 0 | 0 | shifted | cdiv | 0 | divisor | cshifted |
| | | ^
| | |
| | | subtract :cdiv from :shifted until :shifted is 0
[ | | | | while :cdiv
< | | | | | :shifted
| | | | |
[<<+>+>-] | | | | | duplicate
< | | | | | |
[>+<-] | | | | | |
< | | | | | | :csh
| | | | |
| | | | | memory: | 0 | csh | 0 | shifted/remainder | cdiv | 0 | divisor | cshifted |
| | | | | ^
| | | | |
| | | | | subtract 1 from :shifted if not 0
[ | | | | | | if :csh
>>-<< | | | | | | | subtract 1 from :shifted
[-] | | | | | | | clear
] | | | | | | |
| | | | |
>>> | | | | | :cdiv
- | | | | | subtract 1
] | | | | |
| | |
| | |
| | | memory: | 0 | 0 | 0 | remainder | 0 | 0 | divisor | cshifted |
| | | ^
< | | | :remainder ^
| | |
[>+<<<<+>>>-] | | | duplicate
| | |
| | | memory: | remainder | 0 | 0 | 0 | crem | 0 | divisor | shifted/modulus |
| | | ^
> | | | :crem ^
| | |
| | | clean up modulus if a remainder is left
[ | | | if :crem
>>>[-]<<< | | | | clear :modulus
[-] | | | | clear
] | | | |
| | |
| | | if subtracting :cdiv from :shifted left a remainder we need to do continue subtracting;
| | | otherwise modulus is the modulus between :divisor and :shifted
| | |
<<<< | | | :remainder
] | | |
|
| memory: | 0 | 0 | 0 | 0 | 0 | 0 | divisor | modulus | 0 | cmod | eq26 |
| ^
|
>>>>>>> | :modulus
|
[>>+<+<-] | duplicate
> | |
[<+>-] | |
> | | :cmod : copy of :modulus
|
| memory: | 0 | 0 | 0 | 0 | 0 | 0 | divisor | modulus | 0 | cmod | eq26 |
| ^
|
-------------------------- | subtract 26
|
> | :eq26 : condition equal to 26
+ | add 1 (set true)
|
< | :cmod
[ | if :cmod not equal 26
>-< | | subtract 1 from :eq26 (set false)
[-] | | clear
] | |
|
> | :eq26
|
[ | if :eq26
<<<[-]>>> | | clear :modulus
[-] | | clear
] | |
|
| the modulus operation above gives 26 as a valid modulus; so this is a workaround for setting a
| modulus value of 26 to 0
|
<<<< |
[-] | clear :divisor
|
| memory: | c | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | modulus |
| ^
> | :modulus ^
[<<<<<<<+>>>>>>>-] | move :modulus
|
| memory: | c | 0 | modulus/cc | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| ^
<<<<<<< | :modulus/cc ^
|
| add 97 (ascii for 'a'; making 0 a; 1 b; etc)
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
. | print
[-] | clear
] |
 
memory: | c | 0 | modulus/cc |
^
<< :c ^
]</syntaxhighlight>
Usage:
Give to the program the key and the word to encrypt, each followed by a space.<br>
Input:
<!-- Using whitespace syntax highlighting to show the spaces, used by the program to separate arguments -->
<syntaxhighlight lang="whitespace">10 abc </syntaxhighlight>
Output:
<pre>klm</pre>
Input:
<syntaxhighlight lang="whitespace">16 klm </syntaxhighlight>
Output:
<pre>abc</pre>
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
 
#define caesar(x) rot(13, x)
Line 399 ⟶ 1,617:
{
int l = strlen(str);
const char *alpha[2] = { "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
const char* alpha_low = "abcdefghijklmnopqrstuvwxyz";
 
int i;
const char* alpha_high = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (i = 0; i < l; i++)
char subst; /* substitution character */
int idx; /* index */
 
int i; /* loop var */
 
for (i = 0; i < l; i++) /* for each letter in string */
{
if (! 0 == isalpha(str[i]) ) continue; /* not alphabet character */
 
continue;
idx = (int) (tolower(str[i]) - 'a') + c) % 26; /* compute index */
 
str[i] = alpha[isupper(str[i])][((int)(tolower(str[i])-'a')+c)%26];
if( isupper(str[i]) )
subst = alpha_high[idx];
else
subst = alpha_low[idx];
 
str[i] = subst;
 
}
}
 
 
int main(int argc, char** argv)
{
char str[] = "This is a top secret text message!";
Line 423 ⟶ 1,656:
return 0;
}</langsyntaxhighlight>
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Linq;
 
namespace CaesarCypher
{
class Program
{
static char Encrypt(char ch, int code)
{
if (!char.IsLetter(ch)) return ch;
 
char offset = char.IsUpper(ch) ? 'A' : 'a';
return (char)((ch + code - offset) % 26 + offset);
}
 
static string Encrypt(string input, int code)
{
return new string(input.Select(ch => Encrypt(ch, code)).ToArray());
}
 
static string Decrypt(string input, int code)
{
return Encrypt(input, 26 - code);
}
 
const string TestCase = "Pack my box with five dozen liquor jugs.";
 
static void Main()
{
string str = TestCase;
 
Console.WriteLine(str);
str = Encrypt(str, 5);
Console.WriteLine("Encrypted: " + str);
str = Decrypt(str, 5);
Console.WriteLine("Decrypted: " + str);
Console.ReadKey();
}
}
}</syntaxhighlight>
{{out}}
<pre>Pack my box with five dozen liquor jugs.
Encrypted: Ufhp rd gtc bnym knaj itejs qnvztw ozlx.
Decrypted: Pack my box with five dozen liquor jugs.</pre>
=={{header|C++}}==
<langsyntaxhighlight Cpplang="cpp">#include <string>
#include <iostream>
#include <algorithm>
Line 470 ⟶ 1,747:
std::cout << input << std::endl ;
return 0 ;
}</langsyntaxhighlight>
{{out}}
<pre>Which text is to be encrypted ?
Line 484 ⟶ 1,761:
</pre>
 
=={{header|C sharp|C#}}==
<lang csharp>using System;
using System.Linq;
 
'''Alternative version - ''lambda functions, auto, iterators'' '''
namespace CaesarCypher
{
class Program
{
static char Encrypt(char ch, int code)
{
if (!char.IsLetter(ch))
{
return ch;
}
char offset = char.IsUpper(ch) ? 'A' : 'a';
return (char)(((ch + code - offset) % 26) + offset);
}
 
===={{works with|C++-11}}====
static string Encrypt(string input, int code)
{
return new string(input.ToCharArray().Select(ch => Encrypt(ch, code)).ToArray());
}
 
<syntaxhighlight lang="cpp">/* caesar cipher */
static string Decrypt(string input, int code)
{
return Encrypt(input, 26 - code);
}
 
#include <string>
const string TestCase = "Pack my box with five dozen liquor jugs.";
#include <iostream>
#include <cctype>
int main( ) {
 
using namespace std;
static void Main()
{
string str = TestCase;
 
string input ;
Console.WriteLine(str);
int key = 0;
str = Encrypt(str, 5);
 
Console.WriteLine("Encrypted: {0}", str);
// lambda functions
str = Decrypt(str, 5);
 
Console.WriteLine("Decrypted: {0}", str);
auto encrypt = [&](char c, int key ) {
Console.ReadKey();
char A = }( islower(c) )? 'a': 'A';
c = (isalpha(c))? (c - A + key) % 26 + A : c;
return (char) c;
};
 
auto decrypt = [&](char c, int key ) {
char A = ( islower(c) )? 'a': 'A';
c = (isalpha(c))? (c - A + (26 - key) ) % 26 + A : c;
return (char) c;
};
 
 
cout << "Enter a line of text.\n";
getline( cin , input );
 
cout << "Enter an integer to shift text.\n";
cin >> key;
while ( (key < 1) || (key > 25) )
{
cout << "must be an integer between 1 and 25 -->" << endl;
cin >> key;
}
}</lang>
{{out}}
<pre>Pack my box with five dozen liquor jugs.
Encrypted: Ufhp rd gtc bnym knaj itejs qnvztw ozlx.
Decrypted: Pack my box with five dozen liquor jugs.</pre>
 
cout << "Plain: \t" << input << endl ;
 
for ( auto & cp : input) // use & for mutability
cp = encrypt(cp, key);
 
cout << "Encrypted:\t" << input << endl;
 
for ( auto & cp : input)
cp = decrypt(cp, key);
 
cout << "Decrypted:\t" << input << endl;
 
return 0 ;
}
</syntaxhighlight>
 
{{out}}
<pre>
Enter a line of text.
This is a line of plain text, 50 characters long.
Enter an integer to shift text.
5
Plain: This is a line of plain text, 50 characters long.
Encrypted: Ymnx nx f qnsj tk uqfns yj}y1 :5 hmfwfhyjwx qtsl3
Decrypted: This is a line of plain text, 50 characters long.
</pre>
=={{header|Clojure}}==
Readable version:
<lang Clojure>(defn encrypt-character [offset c]
<syntaxhighlight lang="clojure">(defn encrypt-character [offset c]
(if (Character/isLetter c)
(let [v (int c)
Line 555 ⟶ 1,856:
(print "Original text:" text "\n")
(print "Encryption:" enc "\n")
(print "Decryption:" (decrypt -1 enc) "\n"))</langsyntaxhighlight>
 
output:
{{out}}
<pre>
Original text: The Quick Brown Fox Jumps Over The Lazy Dog.
Encryption: Sgd Pthbj Aqnvm Enw Itlor Nudq Sgd Kzyx Cnf.
Decryption: The Quick Brown Fox Jumps Over The Lazy Dog.</pre>
 
Terser version using replace:
<syntaxhighlight lang="clojure">(defn encode [k s]
(let [f #(take 26 (drop %3 (cycle (range (int %1) (inc (int %2))))))
a #(map char (concat (f \a \z %) (f \A \Z %)))]
(apply str (replace (zipmap (a 0) (a k)) s))))
 
(defn decode [k s]
(encode (- 26 k) s))</syntaxhighlight>
 
output:<pre>
(encode 12 "The Quick Brown Fox jumped over the lazy dog")
=> "Ftq Cguow Ndaiz Raj vgybqp ahqd ftq xmlk pas"
(decode 12 (encode 12 "The Quick Brown Fox jumped over the lazy dog"))
=> "The Quick Brown Fox jumped over the lazy dog"
</pre>
 
Fast version, using str/escape:
<syntaxhighlight lang="clojure">(defn fast-caesar [n s]
(let [m (mod n 26)
upper (map char (range 65 91))
upper->new (zipmap upper (drop m (cycle upper)))
lower (map char (range 97 123))
lower->new (zipmap lower (drop m (cycle lower)))]
(clojure.string/escape s (merge upper->new lower->new))))</syntaxhighlight>
output:<pre>
(fast-caesar 12 "The Quick Brown Fox jumped over the lazy dog")
=> "Ftq Cguow Ndaiz Raj vgybqp ahqd ftq xmlk pas"
</pre>
 
=={{header|COBOL}}==
[[COBOL-85]] ASCII or EBCIDIC
{{works with|OpenCOBOL|2.0}}
<syntaxhighlight lang ="cobol"> >>SOURCE FORMAT ISIDENTIFICATION FREEDIVISION.
PROGRAM-ID. CAESAR.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 MSG PIC X(50)
VALUE "The quick brown fox jumped over the lazy dog.".
01 OFFSET PIC 9(4) VALUE 7 USAGE BINARY.
01 FROM-CHARS PIC X(52).
01 TO-CHARS PIC X(52).
01 TABL.
02 PIC X(26) VALUE "abcdefghijklmnopqrstuvwxyz".
02 PIC X(26) VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
02 PIC X(26) VALUE "abcdefghijklmnopqrstuvwxyz".
02 PIC X(26) VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
 
PROCEDURE DIVISION.
BEGIN.
DISPLAY MSG
PERFORM ENCRYPT
DISPLAY MSG
PERFORM DECRYPT
DISPLAY MSG
STOP RUN.
 
ENCRYPT.
MOVE TABL (1:52) TO FROM-CHARS
MOVE TABL (1 + OFFSET:52) TO TO-CHARS
INSPECT MSG CONVERTING FROM-CHARS TO TO-CHARS.
 
DECRYPT.
MOVE TABL (1 + OFFSET:52) TO FROM-CHARS
MOVE TABL (1:52) TO TO-CHARS
INSPECT MSG CONVERTING FROM-CHARS TO TO-CHARS.
 
END PROGRAM CAESAR.</syntaxhighlight>
{{out}}
<pre>
The quick brown fox jumped over the lazy dog.
aol xBpjr iyvDu mvE qBtwlk vCly Aol shGF kvn.
The quick brown fox jumped over the lazy dog.
</pre>
 
{{works with|COBOL 2002}}
<syntaxhighlight lang="cobolfree"> >>SOURCE FORMAT IS FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. caesar-cipher.
 
Line 572 ⟶ 1,947:
REPOSITORY.
FUNCTION encrypt
FUNCTION decrypt.
 
.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 plaintext PIC X(50).
01 offset PICUSAGE 99BINARY-CHAR.
 
01 encrypted-str PIC X(50).
 
PROCEDURE DIVISION.
DISPLAY "Enter a message to encrypt: " WITH NO ADVANCING
ACCEPT plaintext
DISPLAY "Enter the amount to shift by: " WITH NO ADVANCING
ACCEPT offset
MOVE encrypt(offset, plaintext) TO encrypted-str
DISPLAY "Encrypted: " encrypted-str
DISPLAY "Decrypted: " decrypt(offset, encrypted-str).
 
MOVE FUNCTION encrypt(offset, plaintext) TO encrypted-str
DISPLAY "Encrypted: " encrypted-str
DISPLAY "Decrypted: " FUNCTION decrypt(offset, encrypted-str)
.
END PROGRAM caesar-cipher.
 
IDENTIFICATION DIVISION.
 
FUNCTION-ID. encrypt.
 
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
 
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 i PICUSAGE 9(3)INDEX.
01 a USAGE BINARY-CHAR.
 
01 a PIC 9(3).
 
LINKAGE SECTION.
01 offset PICUSAGE 99BINARY-CHAR.
01 str PIC X(50).
 
01 encrypted-str PIC X(50).
 
PROCEDURE DIVISION USING offset, str RETURNING encrypted-str.
PERFORM VARYING i FROM 1 BY 1 UNTIL i > LENGTH(str)
MOVE str TO encrypted-str
PERFORM VARYING i FROM 1 BYIF str(i:1) UNTILIS iNOT >ALPHABETIC FUNCTIONOR LENGTH(str(i:1) = SPACE
IF encrypted- MOVE str (i:1) IS NOT ALPHABETIC ORTO encrypted-str (i:1) = SPACE
EXIT PERFORM CYCLE
END-IF
IF str(i:1) IS ALPHABETIC-UPPER
 
IF encrypted-str MOVE ORD(i:1"A") ISTO ALPHABETIC-UPPERa
MOVE FUNCTION ORD("A") TO a
ELSE
MOVE FUNCTION ORD("a") TO a
END-IF
MOVE CHAR(MOD(ORD(str(i:1)) - a + offset, 26) + a)
 
MOVE FUNCTION CHAR(FUNCTION MOD(FUNCTION ORD(TO encrypted-str (i:1))
- a + offset, 26) + a)
TO encrypted-str (i:1)
END-PERFORM
EXIT FUNCTION.
 
END FUNCTION encrypt.
 
IDENTIFICATION DIVISION.
 
FUNCTION-ID. decrypt.
 
Line 634 ⟶ 2,007:
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION encrypt.
 
.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 decrypt-offset PICUSAGE 99BINARY-CHAR.
 
LINKAGE SECTION.
01 offset PICUSAGE 99BINARY-CHAR.
01 str PIC X(50).
 
01 decrypted-str PIC X(50).
 
PROCEDURE DIVISION USING offset, str RETURNING decrypted-str.
SUBTRACT 26offset FROM offset26 GIVING decrypt-offset
MOVE FUNCTION encrypt(decrypt-offset, str) TO decrypted-str
EXIT FUNCTION.
 
END FUNCTION decrypt.</lang>
END FUNCTION decrypt.</syntaxhighlight>
 
{{out}}
Line 661 ⟶ 2,033:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">cipher = (msg, rot) ->
msg.replace /([a-z|A-Z])/g, ($1) ->
c = $1.charCodeAt(0)
Line 670 ⟶ 2,042:
console.log cipher "Hello World", 2
console.log cipher "azAz %^&*()", 3</langsyntaxhighlight>
{{out}}
<pre>
Line 677 ⟶ 2,049:
dcDc %^&*()
</pre>
=={{header|Commodore BASIC}}==
 
Very generic implementation. Please note that in Commodore BASIC, SHIFT-typed letters (to generate either graphic symbols in upper-case mode, or capital letters in lower-case mode) do '''not''' translate to PETSCII characters 97 through 122, but instead to characters 193 through 218.
 
<syntaxhighlight lang="gwbasic">1 rem caesar cipher
2 rem rosetta code
10 print chr$(147);chr$(14);
15 input "Enter a key value from 1 to 25";kv
20 if kv<1 or kv>25 then print "Out of range.":goto 15
25 gosub 1000
30 print chr$(147);"Enter a message to translate."
35 print:print "Press CTRL-Z when finished.":print
40 mg$="":gosub 2000
45 print chr$(147);"Processing...":gosub 3000
50 print chr$(147);"The translated message is:"
55 print:print cm$
100 print:print "Do another one? ";
110 get k$:if k$<>"y" and k$<>"n" then 110
120 print k$:if k$="y" then goto 10
130 end
 
1000 rem generate encoding table
1010 ec$=""
1015 rem lower case
1020 for i=kv to 26:ec$=ec$+chr$(i+64):next i
1021 for i=1 to kv-1:ec$=ec$+chr$(i+64):next i
1025 rem upper case
1030 for i=kv to 26:ec$=ec$+chr$(i+192):next i
1031 for i=1 to kv-1:ec$=ec$+chr$(i+192):next i
1099 return
 
2000 rem get user input routine
2005 print chr$(18);" ";chr$(146);chr$(157);
2010 get k$:if k$="" then 2010
2012 if k$=chr$(13) then print " ";chr$(157);
2015 print k$;
2020 if k$=chr$(20) then mg$=left$(mg$,len(mg$)-1):goto 2040
2025 if len(mg$)=255 or k$=chr$(26) then return
2030 mg$=mg$+k$
2040 goto 2005
 
3000 rem translate message
3005 cm$=""
3010 for i=1 to len(mg$)
3015 c=asc(mid$(mg$,i,1))
3020 if c<65 or (c>90 and c<193) or c>218 then cm$=cm$+chr$(c):goto 3030
3025 if c>=65 and c<=90 then c=c-64
3030 if c>=193 and c<=218 then c=(c-192)+26
3035 cm$=cm$+mid$(ec$,c,1)
3040 next i
3050 return</syntaxhighlight>
 
{{Output}}
<pre>Enter a key value from 1 to 25? 10
 
Enter a message to translate.
Press CTRL-Z when finished.
 
You know it is going to be a bad day
when the letters in your alphabet soup
spell D-I-S-A-S-T-E-R.
 
Processing...
 
The translated message is:
Iye uxyg sd sc qysxq dy lo k lkn nki
grox dro voddobc sx iyeb kvzrklod cyez
czovv N-S-C-K-C-D-O-B.
Do another one? n
 
ready.
&#9608;
</pre>
=={{header|Common Lisp}}==
====Main version====
<lang lisp>(defun encipher-char (ch key)
<syntaxhighlight lang="lisp">(defun encipher-char (ch key)
(let* ((c (char-code ch)) (la (char-code #\a)) (ua (char-code #\A))
(base (cond ((<= la c (char-code #\z)) la)
Line 697 ⟶ 2,145:
(format t " Original: ~a ~%" original-text)
(format t "Encrypted: ~a ~%" cipher-text)
(format t "Decrypted: ~a ~%" recovered-text))</langsyntaxhighlight>
{{out}}
<pre> Original: The five boxing wizards jump quickly
Encrypted: Wkh ilyh eralqj zlcdugv mxps txlfnob
Decrypted: The five boxing wizards jump quickly</pre>
<syntaxhighlight lang="lisp">
(defun caesar-encipher (s k)
(map 'string #'(lambda (c) (z c k)) s))
 
(defun caesar-decipher (s k) (caesar-encipher s (- k)))
 
(defun z (h k &aux (c (char-code h))
(b (or (when (<= 97 c 122) 97)
(when (<= 65 c 90) 65))))
(if b (code-char (+ (mod (+ (- c b) k) 26) b)) h))
</syntaxhighlight>
{{out}}
<pre>
> (caesar-encipher "The quick brown fox jumps over the lazy dog" 23)
"Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald"
> (caesar-decipher "Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald" 23)
"The quick brown fox jumps over the lazy dog"</pre>
 
====Alternate version====
1. Program
 
<syntaxhighlight lang="lisp">(defconstant +a+ "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz")
(defun caesar (txt offset)
(map 'string
#'(lambda (c)
(if (find c +a+)
(char +a+ (mod (+ (position c +a+) (* 2 offset)) 52))
c))
txt))</syntaxhighlight>
 
2. Execution
 
{{out}}
<pre>(caesar "Ave Caesar morituri te salutant" 13)
Nir Pnrfne zbevghev gr fnyhgnag
(caesar "Nir Pnrfne zbevghev gr fnyhgnag" -13)
Ave Caesar morituri te salutant</pre>
=={{header|Crystal}}==
<syntaxhighlight lang="crystal">class String
ALPHABET = ("A".."Z").to_a
 
def caesar_cipher(num)
self.tr(ALPHABET.join, ALPHABET.rotate(num).join)
end
end
 
# demo
encrypted = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG".caesar_cipher(5)
decrypted = encrypted.caesar_cipher(-5)
</syntaxhighlight>
=={{header|Cubescript}}==
<langsyntaxhighlight lang="cubescript">alias modn [ mod (+ (mod $arg1 $arg2) $arg2) $arg2 ]
//Cubescript's built-in mod will fail on negative numbers
 
Line 761 ⟶ 2,259:
] ]
result $arg1
]</langsyntaxhighlight>
 
Usage:
<syntaxhighlight lang="text">>>> cipher "The Quick Brown Fox Jumps Over The Lazy Dog." 5
> Ymj Vznhp Gwtbs Ktc Ozrux Tajw Ymj Qfed Itl.
>>> decipher "Ymj Vznhp Gwtbs Ktc Ozrux Tajw Ymj Qfed Itl." 5
> The Quick Brown Fox Jumps Over The Lazy Dog.</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.traits;
 
S rot(S)(in S s, in int key) pure nothrow @safe
Line 791 ⟶ 2,288:
writeln("Encrypted: ", txt.rot(key));
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
}</langsyntaxhighlight>
{{out}}
<pre>Original: The five boxing wizards jump quickly
Line 797 ⟶ 2,294:
Decrypted: The five boxing wizards jump quickly</pre>
Simpler in-place version (same output):
<langsyntaxhighlight lang="d">import std.stdio, std.ascii;
 
void inplaceRot(char[] txt, in int key) pure nothrow {
Line 816 ⟶ 2,313:
txt.inplaceRot(26 - key);
writeln("Decrypted: ", txt);
}</langsyntaxhighlight>
 
A version that uses the standard library (same output):
<langsyntaxhighlight lang="d">import std.stdio, std.ascii, std.string, std.algorithm;
 
string rot(in string s, in int key) pure nothrow @safe {
Line 835 ⟶ 2,332:
writeln("Encrypted: ", txt.rot(key));
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">class Caesar {
int _key;
 
Line 901 ⟶ 2,397:
trip(".-:/\"\\!");
trip("The Quick Brown Fox Jumps Over The Lazy Dog.");
}</langsyntaxhighlight>
{{out}}
<pre>JK
Line 923 ⟶ 2,419:
"Dro Aesmu Lbygx Pyh Tewzc Yfob Dro Vkji Nyq." decrypts to:
"The Quick Brown Fox Jumps Over The Lazy Dog."</pre>
=={{header|Delphi}}==
See [[#Pascal]].
=={{header|Dyalect}}==
 
{{trans|C#}}
 
<syntaxhighlight lang="dyalect">func Char.Encrypt(code) {
if !this.IsLetter() {
return this
}
var offset = (this.IsUpper() ? 'A' : 'a').Order()
return Char((this.Order() + code - offset) % 26 + offset)
}
func String.Encrypt(code) {
var xs = []
for c in this {
xs.Add(c.Encrypt(code))
}
return String.Concat(values: xs)
}
func String.Decrypt(code) {
this.Encrypt(26 - code);
}
var str = "Pack my box with five dozen liquor jugs."
print(str)
str = str.Encrypt(5)
print("Encrypted: \(str)")
str = str.Decrypt(5)
print("Decrypted: \(str)")</syntaxhighlight>
 
{{out}}
 
<pre>Pack my box with five dozen liquor jugs.
Encrypted: Ufhp rd gtc bnym knaj itejs qnvztw ozlx.
Decrypted: Pack my box with five dozen liquor jugs.</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
func$ crypt str$ key .
for c$ in strchars str$
c = strcode c$
if c >= 65 and c <= 90
c = (c + key - 65) mod 26 + 65
elif c >= 97 and c <= 122
c = (c + key - 97) mod 26 + 97
.
enc$ &= strchar c
.
return enc$
.
enc$ = crypt "Rosetta Code" 4
print enc$
print crypt enc$ -4
</syntaxhighlight>
 
=={{header|EDSAC order code}}==
The EDSAC had only upper-case letters, which were represented by 5-bit codes.
From a programming point of view the assignment of codes to letters was random,
so tables are used to convert between EDSAC code and alphabetic position.
 
In this program, the alphabetic shift to encipher or decipher a message
is specified by adding the translation of 'A' to the beginning of the message.
For instance, if encipherment shifts letters 3 forward then the message
should be prefixed with 'D' to encipher, or 'X' to decipher.
 
The program prints a test message, enciphered and deciphered, and then prompts for further messages.
If the program is running in the EdsacPC simulator, the user can enter a message by storing it in a text file, making that file the active file, and clicking Reset.
The message must be terminated by a blank row of tape (represented by '.' in EdsacPC).
<syntaxhighlight lang="edsac">
[Caesar cipher for Rosetta Code.
EDSAC program, Initial Orders 2.]
 
[Table for converting alphabetic position 0..25 to EDSAC code.
The EDSAC code is in the high 5 bits.]
T 54 K [access table via C parameter]
P 56 F
T 56 K
AFBFCFDFEFFFGFHFIFJFKFLFMFNFOFPFQFRFSFTFUFVFWFXFYFZF
 
[Table for converting 5-bit EDSAC code to alphabetic position 0..25.
Computed at run time (so the programmer doesn't need to know the EDSAC codes).
32 entries; entry is -1 if the EDSAC code does not represent a letter.]
T 53 K [access table via B parameter]
P 82 F
 
[Subroutine to read string from input and
store with char codes in high 5 bits.
String is terminated by blank row of tape, which is stored.
Input: 0F holds address of string in address field (bits 1..11).
22 locations; workspace: 4D]
T 114 K
GKA3FT19@AFA20@T10@I5FA4DR16FT4DA4FUFE14@A21@G18@T5FA10@A2FE4@T5FEFUFK2048F
 
[Subroutine to print string with character codes in high 5 bits.
String is terminated by blank row of tape, which is not printed.
Input: 0F holds address of string in address field (bits 1..11).
18 locations; orkspace: 4F]
T 136 K
GKA3FT16@AFA2@T5@AFU4FE10@A17@G15@O4FT4FA5@A2FG4@TFEFK2048F
 
[Define start of user message]
T 47 K [access message via M parameter]
P 350 F [address of message]
 
T 154 K
G K
[Constants]
[0] P M [address of user message]
[1] A B
[2] A C
[3] T B
[4] P 25 F
[5] P 26 F
[6] P 31 F
[7] K 2048 F [(1) letter shift (2) used in test for
blank row of tape at end of message]
[8] @ F [carriage return]
[9] & F [line feed]
[10] K 4096 F [null char]
 
[Constant messages. Each includes new line at the end.]
[11] TF EF SF TF IF NF GF @F &F K4096F
[21] P 11 @
[22] EF NF TF EF RF !F MF EF SF SF AF GF EF @F &F K4096F
[38] P 22 @
[39] MF UF SF TF !F SF TF AF RF TF !F WF IF TF HF !F BF !F TF OF !F ZF @F &F K4096F
[64] P 39 @
 
[Subroutine to convert EDSAC code to alphabetic position.
Input: 4F holds EDSAC code in high 5 bits
Output: 4F holds alphabetic position (0..25, or -1 if not a letter).
Workspace: 5F]
[65] A 3 F [make jump for return]
T 75 @ [plant in code]
A 4 F [load EDSAC code]
R 512 F [shift code into address field]
T 5 F [temp store]
C 5 F [acc := address bits only]
A 1 @ [make order to load alphabetic position]
T 73 @ [plant in code]
[73] A B [load alphabetic position]
T 4 F [store in 4F]
[75] E F [return]
 
[Subroutine to encipher or decipher a message by Caesar shift.
Input: Message is accessed by the M parameter, and
terminated by a blank row of tape.
Output: 0F = error flag: 0 if OK, < 0 if error (bad message prefix)
Workspace 4F.]
[76] A 3 F [make jump for return]
T 119 @ [plant in code]
A 80 @ [load order to access first char]
T 95 @ [plant in code]
[80] A M [load first char of message]
T 4 F [pass to subroutine]
[82] A 82 @ [get alphabetic position]
G 65 @
A 4 F [load alphabetic position]
U F [to 0F for use as shift]
S 2 F [check it's not 0 or -1]
G 118 @ [error exit if it is]
T 1 F [clear acc]
S F [load negative of shift]
G 108 @ [jump to store first char
and convert rest of message]
[Here after skipping non-letter]
[91] T 4 F [clear acc]
[Here after converting letter]
[92] A 95 @ [load order to read character]
A 2 F [inc address to next character]
T 95 @ [store back]
[95] A M [load char from message (in top 5 bits)]
E 100 @ [if >= 0 then not blank row]
A 7 @ [if < 0, test for blank row]
G 117 @ [jump out if so]
S 7 @ [restore after test]
[100] T 4 F [character to 4F for subroutine]
[101] A 101 @ [for return from subroutine]
G 65 @ [sets 4F := alphabetic position]
A 4 F [to acc]
G 91 @ [if < 0 then not a letter; don't change it]
A F [apply Caesar shift]
[Subtract 26 if required, so result is in range 0..25]
S 5 @ [subtract 26]
E 109 @ [skip next if result >= 0]
[108] A 5 @ [add 26]
[109] A 2 @ [make order to read EDSAC letter at that position]
T 114 @ [plant in code]
A 95 @ [load A order from above]
A 14 C [add 'O F' to make T order]
T 115 @ [plant in code]
[114] A C [load enciphered letter]
[115] T M [overwrite original letter]
E 92 @ [loop back]
[117] T F [flag = 0 for OK]
[118] T F [flag to 0F: 0 if OK, < 0 if error]
[119] E F [return with acc = 0]
 
[Subroutine to print encipered or deciphered message, plus new line]
[120] A 3 F [make jump order for return]
T 128 @ [plant in code]
A @ [load address of message]
T F [to 0F for print subroutine]
[124] A 124 @
G 136 F [print message, clears acc]
O 8 @ [print new line]
O 9 @
[128] E F [return with acc = 0]
 
[Main routine]
[129] O 7 @ [set letter shift]
H 6 @ [mult reg has this value throughout;
selects bits 1..5 of 17-bit value]
[Build inverse table from direct table
First initialize all 32 locations to -1]
A 6 @ [work backwards]
[132] A 3 @ [make T order for inverse table]
T 135 @ [plant in code]
S 2 F [make -1 in address field]
[135] T B [store in inverse table]
A 135 @ [get T order]
S 2 F [dec address]
S 3 @ [compare with start of table]
E 132 @ [loop till done]
[Now fill in entries by reversing direct table]
T F [clear acc]
A 4 @ [work backwards]
[142] U 5 F [index in 5F]
A 2 @ [make A order for direct table]
T 145 @ [plant in code]
[145] A C [load entry from direct table, code in top 5 bits]
R 512 F [shift 11 right, 5-bit code to address field]
T 4 F [temp store]
C 4 F [pick out 5-bit code]
A 3 @ [make T order for inverse table]
T 152 @ [plant in code]
A 5 F [load index]
[152] T B [store in inverse table]
A 5 F [load index again]
S 2 F [update index]
E 142 @ [loop back]
[Here when inverse table is complete]
[156] T F [clear acc]
[157] A 21 @ [load address of "testing" message]
T F [to 0F for print subroutine]
[159] A 159 @
G 136 F [print "testing message"]
E 168 @ [jump to read from end of this file]
[Loop back here to get message from user]
[162] A 38 @ [load address of prompt]
T F [to 0F for print subroutine]
[164] A 164 @
G 136 F [print prompt]
O 10 @ [print null to flush teleprinter buffer]
Z F [stop]
[First time here, read message from end of this file.
Later times, read message from file chosen by the user.]
[168] A @ [load address of message]
T F [to 0F for input]
[170] A 170 @
G 114 F [read message]
[172] A 172 @
G 120 @ [print message]
[174] A 174 @
G 76 @ [call Caesar shift subroutine]
A F [load error flag]
E 184 @ [jump if OK]
T F [error, clear acc]
A 64 @ [load address of error message]
T F
[181] A 181 @
G 136 F [print error message]
E 162 @ [back to try again]
[Here if message was enciphered without error]
[184] A 184 @
G 120 @ [print enciphered message]
[186] A 186 @
G 76 @ [call Caesar shift subroutine]
[188] A 188 @
G 120 @ [print deciphered message]
E 162 @ [back for another message]
E 129 Z [define entry point]
P F [acc = 0 on entry]
DGAZA!FREQUENS!LIBYCUM!DUXIT!KARTHAGO!TRIUMPHUM.
</syntaxhighlight>
{{out}}
<pre>
TESTING
DGAZA FREQUENS LIBYCUM DUXIT KARTHAGO TRIUMPHUM
XJDCD IUHTXHQV OLEBFXP GXALW NDUWKDJR WULXPSKXP
DGAZA FREQUENS LIBYCUM DUXIT KARTHAGO TRIUMPHUM
ENTER MESSAGE
WGALLIA EST OMNIS DIVISA IN PARTES TRES
ECWHHEW AOP KIJEO ZEREOW EJ LWNPAO PNAO
WGALLIA EST OMNIS DIVISA IN PARTES TRES
ENTER MESSAGE
</pre>
 
=={{header|Eiffel}}==
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 980 ⟶ 2,774:
end
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 987 ⟶ 2,781:
Decoded string (after encoding and decoding): The tiny tiger totally taunted the tall Till.
</pre>
 
=={{header|Ela}}==
 
<langsyntaxhighlight lang="ela">open number char monad io string
 
chars = "ABCDEFGHIJKLMOPQRSTUVWXYZ"
Line 1,017 ⟶ 2,810:
putStrLn ""
putStr "Decoded string: "
put $ decypher key cstr</langsyntaxhighlight>
 
{{out}}
Line 1,025 ⟶ 2,818:
Encoded string: "JGOOQ! VJKU KU C UGETGV PGUUCIG!"
Decoded string: "HELLO! THIS IS A SECRET MESSAGE!"</pre>
 
=={{header|Elena}}==
ELENA 6.x :
<lang elena>#define system.
#define<syntaxhighlight lang="elena">import system'routines.;
#defineimport system'math.;
#defineimport extensions.;
import extensions'text;
 
#symbolconst string Letters = "abcdefghijklmnopqrstuvwxyz".;
#symbolconst string BigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".;
#symbolconst string TestText = "Pack my box with five dozen liquor jugs.".;
#symbolconst int Key = 12.;
 
#class Encrypting :: Enumerator
{
#fieldint theKey. _key;
Enumerator _enumerator;
#field theEnumerator.
#constructor(int new &key:aKey, string &text:aText)
[{
theKey_key := aKey.key;
theEnumerator_enumerator := aText text.enumerator.();
]}
#methodbool next() => theEnumerator._enumerator;
#method reset() => theEnumerator._enumerator;
enumerable() => _enumerator;
#method get
[
get Value()
#var aChar := theEnumerator get.
{
var ch := *_enumerator;
#var anIndexindex := Letters .indexOf:(0:aChar., ch);
if (-1 < anIndexindex)
? [{
^ Letters @ ([(theKey_key+anIndexindex) .mod:(26).]
]}
! [else
{
anIndex := BigLetters indexOf:0:aChar.
index := BigLetters.indexOf(-1 <0, anIndexch);
if (-1 < ? [index)
{
^ BigLetters @ ((theKey+anIndex) mod:26).
^ BigLetters[(_key+index).mod(26)]
! [}
^ aChar.else
].{
]. ^ ch
] }
}
}
}
 
#class(extension) encryptOp
{
#method encrypt : aKey(key)
= Encrypting new &Encrypting(key:aKey, &text:self ).summarize:(String new StringWriter().);
 
#method decrypt :aKey(key)
= Encrypting new &key:Encrypting(26 - aKey)key, &text:self ).summarize:(String new StringWriter().);
}
 
#symbolpublic program =()
{
[
console writeLine:.printLine("Original text :" :,TestText.);
#var anEncryptedTextencryptedText := TestText .encrypt:(Key.);
 
console writeLine:.printLine("Encrypted text:" :anEncryptedText.,encryptedText);
 
#var aDecryptedTextdecryptedText := anEncryptedText encryptedText.decrypt:(Key.);
 
console writeLine:.printLine("Decrypted text:" :aDecryptedText.,decryptedText);
 
console readChar.readChar()
}</syntaxhighlight>
].</lang>
{{out}}
<pre>
Line 1,106 ⟶ 2,903:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Caesar_cipher do
defp set_map(map, range, key) do
org = Enum.map(range, &List.to_string [&1])
Line 1,115 ⟶ 2,912:
def encode(text, key) do
map = Map.new |> set_map(?a..?z, key) |> set_map(?A..?Z, key)
String.codepointsgraphemes(text) |> Enum.map_join(fn c -> DictMap.get(map, c, c) end)
end
end
Line 1,123 ⟶ 2,920:
IO.puts "Original: #{text}"
IO.puts "Encrypted: #{enc = Caesar_cipher.encode(text, key)}"
IO.puts "Decrypted: #{Caesar_cipher.encode(enc, -key)}"</langsyntaxhighlight>
 
{{out}}
Line 1,131 ⟶ 2,928:
Decrypted: The five boxing wizards jump quickly
</pre>
=={{header|Elm}}==
 
<syntaxhighlight lang="elm">
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
module Main exposing (main)
 
import Browser
import Html exposing (Html, h2, div, p, input, button, text, textarea)
import Html.Attributes exposing (style, class, placeholder, value)
import Html.Events exposing (onInput, onClick)
 
 
-- MAIN
 
main =
Browser.sandbox { init = init, update = update, view = view }
 
 
-- MODEL
 
type alias Model =
{ codeKey : Int
, normtext : String
}
 
 
init : Model
init =
{ codeKey = 3
, normtext = "" }
 
 
-- UPDATE
 
type Msg
= Change String
| DecKey
| IncKey
 
 
update : Msg -> Model -> Model
update msg model =
case msg of
DecKey ->
{ model | codeKey = model.codeKey - 1}
IncKey ->
{ model | codeKey = model.codeKey + 1}
Change newContent ->
{ model | normtext = String.toUpper newContent }
 
 
 
encodeChar : Int -> Char -> Char
encodeChar codeKey character =
if Char.isUpper character then
Char.fromCode (modBy 26 (Char.toCode character - 65 + codeKey) + 65)
 
else if Char.isLower character then
Char.fromCode (modBy 26 (Char.toCode (Char.toUpper character) - 65 + codeKey) + 65)
 
else
character
 
 
encodeText : Int -> String -> String
encodeText codeKey normtext =
String.map (encodeChar codeKey) normtext
 
 
subheads aKey =
if aKey > 0 then "Original"
else if aKey < 0 then "Encrypted text"
else "?"
 
-- VIEW
 
view : Model -> Html Msg
view model =
div []
[ div []
[h2 [class "h2style"] [text (subheads model.codeKey)]
, textarea [ class "textframe", placeholder "Write here your text!"
, value model.normtext, onInput Change ] []
]
, div []
[h2 [class "h2style"] [text (subheads (negate model.codeKey))]
, textarea [ class "textframe", value (encodeText model.codeKey model.normtext) ] []]
, div [class "keystyle"] [ button [ class "butstyle", onClick DecKey ] [ text "-1" ]
, text (" Key " ++ String.fromInt model.codeKey)
, button [ class "butstyle", onClick IncKey ] [ text "+1" ]
]
]
 
</syntaxhighlight>
 
{{out}}
<pre>
Original: THE QUICK ORANGE FOX JUMPED OVER THE SLOW DOG
Encrypted: WKH TXLFN RUDQJH IRA MXPSHG RYHU WKH VORZ GRJ (used key value 3)
Encrypted: XLI UYMGO SVERKI JSB NYQTIH SZIV XLI WPSA HSK (used key value 4)
Decrypted: THE QUICK ORANGE FOX JUMPED OVER THE SLOW DOG (used key value -3)
Decrypted: THE QUICK ORANGE FOX JUMPED OVER THE SLOW DOG (used key value -4)
 
Live version with html file calling the elm module as compiled to JavaScript
at https://ellie-app.com/qVvVDKdK6PQa1
</pre>
%% Ceasar cypher in Erlang for the rosetta code wiki.
%% Implemented by J.W. Luiten
Line 1,168 ⟶ 3,068:
PlainText = lists:map(fun(Char) -> rot(Char, Decode) end, CypherText).
 
</syntaxhighlight>
</lang>
Command: <langsyntaxhighlight Erlanglang="erlang">ceasar:main("The five boxing wizards jump quickly", 3).</langsyntaxhighlight>
{{out}}
<pre>
Line 1,176 ⟶ 3,076:
"The five boxing wizards jump quickly"
</pre>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM CAESAR
 
Line 1,208 ⟶ 3,107:
 
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,215 ⟶ 3,114:
Pack my box with five dozen liquor jugs
</pre>
 
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.0}}
<syntaxhighlight lang="euphoria">
<lang Euphoria>
--caesar cipher for Rosetta Code wiki
--User:Lnettnay
Line 1,274 ⟶ 3,172:
printf(1,"%s\n",{text})
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,281 ⟶ 3,179:
"The Quick Brown Fox Jumps Over The Lazy Dog."
</pre>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">module caesar =
open System
 
Line 1,295 ⟶ 3,192:
 
let encrypt n = cipher n
let decrypt n = cipher (26 - n)</langsyntaxhighlight>
<pre>&gt; caesar.encrypt 2 "HI";;
val it : string = "JK"
Line 1,305 ⟶ 3,202:
val it : string = "The quick brown fox jumps over the lazy dog."
</pre>
=={{header|Factor}}==
{{works with|Factor|0.97}}
{{trans|F#}}
<syntaxhighlight lang="factor">USING: io kernel locals math sequences unicode.categories ;
IN: rosetta-code.caesar-cipher
 
:: cipher ( n s -- s' )
[| c |
c Letter? [
c letter? CHAR: a CHAR: A ? :> a
c a - n + 26 mod a +
]
[ c ] if
] :> shift
s [ shift call ] map ;
: encrypt ( n s -- s' ) cipher ;
: decrypt ( n s -- s' ) [ 26 swap - ] dip cipher ;
 
11 "Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr." decrypt print
11 "The quick brown fox jumped over the lazy dog." encrypt print</syntaxhighlight>
{{out}}
<pre>
The quick brown fox jumped over the lazy dog.
Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr.
</pre>
=={{header|Fantom}}==
 
Shifts upper/lower case letters, leaves other characters as they are.
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,363 ⟶ 3,285:
}
}
</syntaxhighlight>
</lang>
 
Example:
Line 1,382 ⟶ 3,304:
Decode: Encrypt - With ! Case,
</pre>
=={{header|Fhidwfe}}==
only encodes letters
<syntaxhighlight lang="fhidwfe">
lowers = ['a','z']
uppers = ['A','Z']
function void caesar_encode(message:ptr key:uint) {
len = strlen$ message
for uint [0u,len) with index {
temp = deref_ubyte$ + message index
if in temp lowers {
temp = + temp key// shift lowercase letters
if > temp 'z' {
temp = - temp 26ub
} ;
} {
if in temp uppers {
temp = + temp key// shift uppercase letters
if > temp 'Z' {
temp = - temp 26ub
} ;
} ;//don't shift other characters
}
put_ubyte$ + message index temp
}
}
function void caesar_decode(message:ptr key:uint) {
caesar_encode$ message - 26u key
}
 
key = 1u
response = malloc$ 256u
puts$ "plaintext: "
getline$ response
caesar_encode$ response key
puts$ "cyphertext: "
puts$ response
putln$
caesar_decode$ response key
puts$ "decoded: "
puts$ response
free$ response
free$ lowers // ranges are objects and must be freed
free$ uppers
 
//this compiles with only 6 warnings!
</syntaxhighlight>
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: ceasarcaesar ( c n -- c )
over 32 or [char] a -
dup 0 26 within if
Line 1,390 ⟶ 3,357:
else 2drop then ;
 
: ceasarcaesar-string ( n str len -- )
over + swap do i c@ over ceasarcaesar i c! loop drop ;
: ceasarcaesar-inverse ( n -- 'n ) 26 swap - 26 mod ;
 
2variable test
s" The five boxing wizards jump quickly!" test 2!
 
3 test 2@ ceasarcaesar-string
test 2@ cr type
 
3 ceasarcaesar-inverse test 2@ ceasarcaesar-string
test 2@ cr type</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortan 90 and later}}
<langsyntaxhighlight lang="fortran">program Caesar_Cipher
implicit none
 
Line 1,448 ⟶ 3,415:
end subroutine
 
end program Caesar_Cipher</langsyntaxhighlight>
{{out}}
<pre>Original message = The five boxing wizards jump quickly
Encrypted message = Wkh ilyh eralgj zlcdugv mxps txlfnob
Decrypted message = The five boxing wizards jump quickly</pre>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub Encrypt(s As String, key As Integer)
Dim c As Integer
For i As Integer = 0 To Len(s)
Select Case As Const s[i]
Case 65 To 90
c = s[i] + key
If c > 90 Then c -= 26
s[i] = c
Case 97 To 122
c = s[i] + key
If c > 122 Then c -= 26
s[i] = c
End Select
Next
End Sub
 
Sub Decrypt(s As String, key As Integer)
Dim c As Integer
For i As Integer = 0 To Len(s)
Select Case As Const s[i]
Case 65 To 90
c = s[i] - key
If c < 65 Then c += 26
s[i] = c
Case 97 To 122
c = s[i] - key
If c < 97 Then c += 26
s[i] = c
End Select
Next
End Sub
 
Dim As String s = "Bright vixens jump; dozy fowl quack."
Print "Plain text : "; s
Encrypt s, 8
Print "Encrypted : "; s
Decrypt s, 8
Print "Decrypted : "; s
Sleep</syntaxhighlight>
 
{{out}}
<pre>
Plain text : Bright vixens jump; dozy fowl quack.
Encrypted : Jzqopb dqfmva rcux; lwhg nwet yciks.
Decrypted : Bright vixens jump; dozy fowl quack.
</pre>
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=cb96008082bc0d8278224cd2a5ec74d3 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim byKey As Byte = 3 'The key (Enter 26 to get the same output as input)
Dim byCount As Byte 'Counter
Dim sCeasar As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" 'Used to calculate the cipher
Dim sString As String = "The five boxing wizards jump quickly" 'Phrase to encrypt
Dim sCoded, sTemp As String 'Various strings
 
For byCount = 1 To Len(sString) 'Count through each letter in the phrase
If Mid(sString, byCount, 1) = " " Then 'If it's a space..
sCoded &= " " 'Keep it a space
Continue 'Jump to the next iteration of the loop
Endif
sTemp = Mid(sCeasar, InStr(sCeasar, Mid(UCase(sString), byCount, 1)) + byKey, 1) 'Get the new 'coded' letter
If Asc(Mid(sString, byCount, 1)) > 96 Then sTemp = Chr(Asc(sTemp) + 32) 'If the original was lower case then make the new 'coded' letter lower case
sCoded &= sTemp 'Add the result to the code string
Next
 
Print sString & gb.NewLine & sCoded 'Print the result
 
End</syntaxhighlight>
Output:
<pre>
The five boxing wizards jump quickly
Wkh ilyh eralqj zlcdugv mxps txlfnob
</pre>
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">CaesarCipher := function(s, n)
local r, c, i, lower, upper;
lower := "abcdefghijklmnopqrstuvwxyz";
Line 1,480 ⟶ 3,522:
 
CaesarCipher("Vgg cphvi wzdibn vmz wjmi amzz viy zlpvg di ydbidot viy mdbcon.", 5);
# "All human beings are born free and equal in dignity and rights."</langsyntaxhighlight>
 
=={{header|GFA Basic}}==
<langsyntaxhighlight lang="basic">
'
' Caesar cypher
Line 1,520 ⟶ 3,561:
RETURN @encrypt$(text$,26-key%)
ENDFUNC
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
Obvious solution with explicit testing for character ranges:
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,582 ⟶ 3,622:
fmt.Println(" Deciphered:", ck.decipher(ct))
}
}</langsyntaxhighlight>
Data driven version using functions designed for case conversion. (And for method using % operator, see [[Vigen%C3%A8re_cipher#Go]].)
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,640 ⟶ 3,680:
fmt.Println(" Deciphered:", ck.decipher(ct))
}
}</langsyntaxhighlight>
{{out}} (either version)
<pre>
Line 1,656 ⟶ 3,696:
Key 26 invalid
</pre>
 
=={{header|Groovy}}==
Java style:
<langsyntaxhighlight lang="groovy">def caesarEncode(​cipherKey, text) {
def builder = new StringBuilder()
text.each { character ->
Line 1,671 ⟶ 3,710:
builder as String
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</langsyntaxhighlight>
 
Functional style:
<langsyntaxhighlight lang="groovy">def caesarEncode(cipherKey, text) {
text.chars.collect { c ->
int off = c.isUpperCase() ? 'A' : 'a'
Line 1,680 ⟶ 3,719:
}.join()
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</langsyntaxhighlight>
 
Ninja style:
<langsyntaxhighlight lang="groovy">def caesarEncode(k, text) {
(text as int[]).collect { it==' ' ? ' ' : (((it & 0x1f) + k - 1) % 26 + 1 | it & 0xe0) as char }.join()
}
def caesarDecode(k, text) { caesarEncode(26 - k, text) }</langsyntaxhighlight>
Using built in 'tr' function and a replacement alphabet:
<langsyntaxhighlight lang="groovy">def caesarEncode(k, text) {
text.tr('a-zA-Z', ((('a'..'z')*2)[k..(k+25)] + (('A'..'Z')*2)[k..(k+25)]).join())
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</langsyntaxhighlight>
and the same with closures for somewhat better readability:
<langsyntaxhighlight lang="groovy">def caesarEncode(k, text) {
def c = { (it*2)[k..(k+25)].join() }
text.tr('a-zA-Z', c('a'..'z') + c('A'..'Z'))
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</langsyntaxhighlight>
Test code:
<langsyntaxhighlight lang="groovy">
def plainText = "The Quick Brown Fox jumped over the lazy dog"
def cipherKey = 12
Line 1,711 ⟶ 3,750:
assert plainText == decodedText
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,717 ⟶ 3,756:
cypherText(12): Ftq Cguow Ndaiz Raj vgybqp ahqd ftq xmlk pas
decodedText(12): The Quick Brown Fox jumped over the lazy dog</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">module Caesar (caesar, uncaesar) where
 
import Data.Char
Line 1,735 ⟶ 3,773:
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c
</syntaxhighlight>
</lang>
 
And trying it out in GHCi:
Line 1,744 ⟶ 3,782:
"hal"
</pre>
 
Similarly, but allowing for negative cipher keys, and using isAlpha, isUpper, negate:
 
<syntaxhighlight lang="haskell">import Data.Bool (bool)
import Data.Char (chr, isAlpha, isUpper, ord)
 
---------------------- CAESAR CIPHER ---------------------
 
caesar, uncaesar :: Int -> String -> String
caesar = fmap . tr
uncaesar = caesar . negate
 
tr :: Int -> Char -> Char
tr offset c
| isAlpha c =
chr
. ((+) <*> (flip mod 26 . (-) (offset + ord c)))
$ bool 97 65 (isUpper c)
| otherwise = c
 
--------------------------- TEST -------------------------
main :: IO ()
main = do
let k = -114
cipher = caesar k
plain = "Curio, Cesare venne, e vide e vinse ? "
mapM_ putStrLn $ [cipher, uncaesar k . cipher] <*> [plain]</syntaxhighlight>
{{Out}}
<pre>Skhye, Suiqhu luddu, u lytu u lydiu ?
Curio, Cesare venne, e vide e vinse ? </pre>
 
Or with proper error handling:
<langsyntaxhighlight lang="haskell">{-# LANGUAGE LambdaCase #-}
module Main where
 
Line 1,777 ⟶ 3,845:
addChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26)
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c</langsyntaxhighlight>
=={{header|Hoon}}==
 
<syntaxhighlight lang="hoon">|%
++ enc
|= [msg=tape key=@ud]
^- tape
(turn `(list @)`msg |=(n=@ud (add (mod (add (sub n 'A') key) 26) 'A')))
++ dec
|= [msg=tape key=@ud]
(enc msg (sub 26 key))
--</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
Strictly speaking a Ceasar Cipher is a shift of 3 (the default in this case).
<langsyntaxhighlight Iconlang="icon">procedure main()
ctext := caesar(ptext := map("The quick brown fox jumped over the lazy dog"))
dtext := caesar(ctext,,"decrypt")
Line 1,796 ⟶ 3,873:
"d"|"decrypt" : return map(text,(&lcase||&lcase)[k+:*&lcase],&lcase)
}
end</langsyntaxhighlight>
 
{{out}}
Line 1,803 ⟶ 3,880:
Decphered text = "the quick brown fox jumped over the lazy dog"</pre>
 
=={{Header|Insitux}}==
 
<syntaxhighlight lang="insitux">
(function caeser by of
(let alphabets (proj (map char-code) (range 65 91) (range 97 123))
shifted (.. vec (map (rotate by) alphabets))
table (kv-dict (flatten alphabets) (flatten shifted)))
(... str (map #(or (table %) %) of)))
 
(let original "The Quick Brown Fox Jumps Over The Lazy Dog."
encrypted (caeser -1 original)
decrypted (caeser 1 encrypted))
(str "Original: " original "
Encrypted: " encrypted "
Decrypted: " decrypted)
</syntaxhighlight>
 
{{out}}
 
<pre>
Original: The Quick Brown Fox Jumps Over The Lazy Dog.
Encrypted: Sgd Pthbj Aqnvm Enw Itlor Nudq Sgd Kzyx Cnf.
Decrypted: The Quick Brown Fox Jumps Over The Lazy Dog.
</pre>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 PROGRAM "CaesarCi.bas"
110 STRING M$*254
120 INPUT PROMPT "String: ":M$
130 DO
140 INPUT PROMPT "Key (1-25): ":KEY
150 LOOP UNTIL KEY>0 AND KEY<26
160 PRINT "Original message: ";M$
170 CALL ENCRYPT(M$,KEY)
180 PRINT "Encrypted message: ";M$
190 CALL DECRYPT(M$,KEY)
200 PRINT "Decrypted message: ";M$
210 DEF ENCRYPT(REF M$,KEY)
220 STRING T$*254
230 LET T$=""
240 FOR I=1 TO LEN(M$)
250 SELECT CASE M$(I)
260 CASE "A" TO "Z"
270 LET T$=T$&CHR$(65+MOD(ORD(M$(I))-65+KEY,26))
280 CASE "a" TO "z"
290 LET T$=T$&CHR$(97+MOD(ORD(M$(I))-97+KEY,26))
300 CASE ELSE
310 LET T$=T$&M$(I)
320 END SELECT
330 NEXT
340 LET M$=T$
350 END DEF
360 DEF DECRYPT(REF M$,KEY)
370 STRING T$*254
380 LET T$=""
390 FOR I=1 TO LEN(M$)
400 SELECT CASE M$(I)
410 CASE "A" TO "Z"
420 LET T$=T$&CHR$(65+MOD(ORD(M$(I))-39-KEY,26))
430 CASE "a" TO "z"
440 LET T$=T$&CHR$(97+MOD(ORD(M$(I))-71-KEY,26))
450 CASE ELSE
460 LET T$=T$&M$(I)
470 END SELECT
480 NEXT
490 LET M$=T$
500 END DEF</syntaxhighlight>
=={{header|J}}==
If we assume that the task also requires us to leave non-alphabetic characters alone:
<langsyntaxhighlight lang="j">cndx=: [: , 65 97 +/ 26 | (i.26)&+
caesar=: (cndx 0)}&a.@u:@cndx@[ {~ a.i.]</langsyntaxhighlight>
Example use:<langsyntaxhighlight lang="j"> 2 caesar 'This simple "monoalphabetic substitution cipher" provides almost no security, ...'
Vjku ukorng "oqpqcnrjcdgvke uwduvkvwvkqp ekrjgt" rtqxkfgu cnoquv pq ugewtkva, ...</langsyntaxhighlight>
If we instead assume the task only requires we treat upper case characters:
<langsyntaxhighlight lang="j">CAESAR=:1 :'(26|m&+)&.((26{.64}.a.)&i.)'</langsyntaxhighlight>
Example use:<langsyntaxhighlight lang="j"> 20 CAESAR 'HI'
BC</langsyntaxhighlight>
=={{header|Janet}}==
<syntaxhighlight lang="janet">
(def alphabet "abcdefghijklmnopqrstuvwxyz")
 
(defn rotate
"shift bytes given x"
[str x]
(let [r (% x (length alphabet))
b (string/bytes str)
abyte (get (string/bytes "a") 0)
zbyte (get (string/bytes "z") 0)]
(var result @[])
(for i 0 (length b)
(let [ch (bor (get b i) 0x20)] # convert uppercase to lowercase
(when (and (<= abyte ch) (<= ch zbyte))
(array/push result (get alphabet (% (+ (+ (+ (- zbyte abyte) 1) (- ch abyte)) r) (length alphabet)))))))
(string/from-bytes ;result)))
 
(defn code
"encodes and decodes str given argument type"
[str rot type]
(case type
:encode (rotate str rot)
:decode (rotate str (* rot -1))))
 
(defn main [& args]
(let [cipher (code "The quick brown fox jumps over the lazy dog" 23 :encode)
str (code cipher 23 :decode)]
(print cipher)
(print str)))
</syntaxhighlight>
 
{{out}}
<pre>
> encode:
"qebnrfzhyoltkclugrjmplsboqebixwvald"
> decode:
"thequickbrownfoxjumpsoverthelazydog"
</pre>
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">public class Cipher {
public static void main(String[] args) {
 
Line 1,845 ⟶ 4,027:
return encoded.toString();
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,851 ⟶ 4,033:
The quick brown fox Jumped over the lazy Dog
</pre>
 
=={{header|JavaScript}}==
==={{header|ES5}}===
 
===ES5===
<lang javascript>function caesar (text, shift) {
 
return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/[A-Z]/g, function(a) {
<syntaxhighlight lang="javascript">function caesar (text, shift) {
return String.fromCharCode(65+(a.charCodeAt(0)-65+shift)%26);
return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/./g, function(a) {
return String.fromCharCode(((a.charCodeAt(0) - 65 + shift) % 26 + 26) % 26 + 65);
});
}
Line 1,865 ⟶ 4,047:
for (var i = 0; i<26; i++) {
console.log(i+': '+caesar(text,i));
}</langsyntaxhighlight>
 
{{output}}
Line 1,875 ⟶ 4,057:
...
</pre>
 
==={{header|ES6}}===
===ES6===
<lang javascript>
 
var caesar = (text, shift) => text
<syntaxhighlight lang="javascript">var caesar = (text, shift) => text
.toUpperCase()
.replace(/[^A-Z]/g, '')
.replace(/[A-Z]./g, a =>
String.fromCharCode(65 + ((a.charCodeAt(0) - 65 + shift) % 26 + 26) % 26 + 65));</syntaxhighlight>
</lang>
 
 
Or, allowing encoding and decoding of both lower and upper case:
 
<syntaxhighlight lang="javascript">((key, strPlain) => {
 
// Int -> String -> String
let caesar = (k, s) => s.split('')
.map(c => tr(
inRange(['a', 'z'], c) ? 'a' :
inRange(['A', 'Z'], c) ? 'A' : 0,
k, c
))
.join('');
 
// Int -> String -> String
let unCaesar = (k, s) => caesar(26 - (k % 26), s);
 
// Char -> Int -> Char -> Char
let tr = (base, offset, char) =>
base ? (
String.fromCharCode(
ord(base) + (
ord(char) - ord(base) + offset
) % 26
)
) : char;
 
// [a, a] -> a -> b
let inRange = ([min, max], v) => !(v < min || v > max);
 
// Char -> Int
let ord = c => c.charCodeAt(0);
 
// range :: Int -> Int -> [Int]
let range = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
 
// TEST
let strCipher = caesar(key, strPlain),
strDecode = unCaesar(key, strCipher);
 
return [strCipher, ' -> ', strDecode];
 
})(114, 'Curio, Cesare venne, e vide e vinse ? ');</syntaxhighlight>
 
{{Out}}
<pre>Mebsy, Mockbo foxxo, o fsno o fsxco ? , -> , Curio, Cesare venne, e vide e vinse ?</pre>
=={{header|jq}}==
{{trans|Wren}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<syntaxhighlight lang="jq">def encrypt(key):
. as $s
| explode as $xs
| (key % 26) as $offset
| if $offset == 0 then .
else reduce range(0; length) as $i ( {chars: []};
$xs[$i] as $c
| .d = $c
| if ($c >= 65 and $c <= 90) # 'A' to 'Z'
then .d = $c + $offset
| if (.d > 90) then .d += -26 else . end
else if ($c >= 97 and $c <= 122) # 'a' to 'z'
then .d = $c + $offset
| if (.d > 122)
then .d += -26
else .
end
else .
end
end
| .chars[$i] = .d )
| .chars | implode
end ;
def decrypt(key): encrypt(26 - key);
 
"Bright vixens jump; dozy fowl quack."
| .,
(encrypt(8)
| ., decrypt(8) )
</syntaxhighlight>
{{out}}
<pre>
Bright vixens jump; dozy fowl quack.
Jzqopb dqfmva rcux; lwhg nwet yciks.
Bright vixens jump; dozy fowl quack.
</pre>
=={{header|Jsish}}==
From Typescript entry.
<syntaxhighlight lang="javascript">/* Caesar cipher, in Jsish */
"use strict";
 
function caesarCipher(input:string, key:number):string {
return input.replace(/([a-z])/g,
function(mat, p1, ofs, str) {
return Util.fromCharCode((p1.charCodeAt(0) + key + 26 - 97) % 26 + 97);
}).replace(/([A-Z])/g,
function(mat, p1, ofs, str) {
return Util.fromCharCode((p1.charCodeAt(0) + key + 26 - 65) % 26 + 65);
});
}
 
provide('caesarCipher', 1);
 
if (Interp.conf('unitTest')) {
var str = 'The five boxing wizards jump quickly';
; str;
; 'Enciphered:';
; caesarCipher(str, 3);
; 'Enciphered then deciphered';
; caesarCipher(caesarCipher(str, 3), -3);
}
 
/*
=!EXPECTSTART!=
str ==> The five boxing wizards jump quickly
'Enciphered:'
caesarCipher(str, 3) ==> Wkh ilyh eralqj zlcdugv mxps txlfnob
'Enciphered then deciphered'
caesarCipher(caesarCipher(str, 3), -3) ==> The five boxing wizards jump quickly
=!EXPECTEND!=
*/</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish -u caesarCipher.jsi
[PASS] caesarCipher.jsi</pre>
=={{header|Julia}}==
===updated version for Julia 1.x | Rename isalpha to isletter #27077 | https://github.com/JuliaLang/julia/pull/27077===
<lang julia>
 
function rot(s::String, key::Integer)
<syntaxhighlight lang="julia">
map(s) do c
# Caeser cipher
if 'a' <= c <= 'z'
# Julia 1.5.4
char( mod(c - 'a' + key, 26) + 'a')
# author: manuelcaeiro | https://github.com/manuelcaeiro
elseif 'A' <= c <= 'Z'
 
char( mod(c - 'A' + key, 26) + 'A')
function csrcipher(text, key)
ciphtext = ""
for l in text
numl = Int(l)
ciphnuml = numl + key
if numl in 65:90
if ciphnuml > 90
rotciphnuml = ciphnuml - 26
ciphtext = ciphtext * Char(rotciphnuml)
else
ciphtext = ciphtext * Char(ciphnuml)
end
elseif numl in 97:122
if ciphnuml > 122
rotciphnuml = ciphnuml - 26
ciphtext = ciphtext * Char(rotciphnuml)
else
ciphtext = ciphtext * Char(ciphnuml)
end
else
cciphtext = ciphtext * Char(numl)
end
end
return ciphtext
end
 
text = "Magic Encryption"; key = 13
key = 3
csrcipher(text, key)
txt = "The five boxing wizards jump quickly"
</syntaxhighlight>
 
{{out}}
println("Original: ", txt);
<pre>
println("Encrypted: ", rot(txt, key))
"Zntvp Rapelcgvba"
println("Decrypted: ", rot(rot(txt, key), 26 - key))
</langpre>
Based on the D code.
 
=={{header|K}}==
 
Assumes lowercase letters, and no punctuation.
 
<syntaxhighlight lang="k">
<lang k>
s:"there is a tide in the affairs of men"
caesar:{ :[" "=x; x; {x!_ci 97+!26}[y]@_ic[x]-97]}'
caesar[s;1]
"uifsf jt b ujef jo uif bggbjst pg nfo"
</syntaxhighlight>
</lang>
=={{header|Koka}}==
<syntaxhighlight lang="koka">
fun encode(s : string, shift : int)
fun encode-char(c)
if c < 'A' || (c > 'Z' && c < 'a') || c > 'z' return c
val base = if c < 'Z' then (c - 'A').int else (c - 'a').int
val rot = (base + shift) % 26
(rot.char + (if c < 'Z' then 'A' else 'a'))
s.map(encode-char)
 
fun decode(s: string, shift: int)
s.encode(0 - shift)
 
fun trip(s: string, shift: int)
s.encode(shift).decode(shift)
 
fun main()
"HI".encode(2).println
"HI".encode(20).println
"HI".trip(10).println
val enc = "The quick brown fox jumped over the lazy dog".encode(11)
enc.println
enc.decode(11).println
</syntaxhighlight>
{{out}}
<pre>
JK
BC
HI
Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr
The quick brown fox jumped over the lazy dog
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.5-2
 
object Caesar {
fun encrypt(s: String, key: Int): String {
val offset = key % 26
if (offset == 0) return s
var d: Char
val chars = CharArray(s.length)
for ((index, c) in s.withIndex()) {
if (c in 'A'..'Z') {
d = c + offset
if (d > 'Z') d -= 26
}
else if (c in 'a'..'z') {
d = c + offset
if (d > 'z') d -= 26
}
else
d = c
chars[index] = d
}
return chars.joinToString("")
}
fun decrypt(s: String, key: Int): String {
return encrypt(s, 26 - key)
}
}
 
fun main(args: Array<String>) {
val encoded = Caesar.encrypt("Bright vixens jump; dozy fowl quack.", 8)
println(encoded)
val decoded = Caesar.decrypt(encoded, 8)
println(decoded)
}</syntaxhighlight>
 
{{out}}
<pre>
Jzqopb dqfmva rcux; lwhg nwet yciks.
Bright vixens jump; dozy fowl quack.
</pre>
 
=={{header|LabVIEW}}==
For readability, input is in all caps.<br/>{{VI snippet}}<br/>[[File:LabVIEW_Caesar_cipher.png]]
=={{header|Lambdatalk}}==
The caesar function encodes and decodes texts containing exclusively the set [ABCDEFGHIJKLMNOPQRSTUVWXZ].
<syntaxhighlight lang="scheme">
{def caesar
 
{def caesar.alphabet {A.split ABCDEFGHIJKLMNOPQRSTUVWXYZ}}
 
{def caesar.delta
{lambda {:s :i :a}
{A.get {% {+ {A.in? {A.get :i :a} {caesar.alphabet}} 26 :s} 26}
{caesar.alphabet}}}}
{def caesar.loop
{lambda {:s :a :b :n :i}
{if {> :i :n}
then :b
else {caesar.r :s
:a
{A.set! :i {caesar.delta :s :i :a} :b}
:n
{+ :i 1}} }}}
 
{lambda {:shift :txt}
{let { {:s :shift}
{:t {S.replace [^A-Z] by in :txt}} }
{A.join {caesar.loop :s
{A.split :t}
{A.new}
{- {W.length :t} 1}
0 }}}}}
-> caesar
 
 
{def text VENI, VIDI, VICI}
-> text
{S.map {lambda {:i} {br}:i: {caesar :i {text}}}
{S.serie 0 26}}
->
 
0: VENIVIDIVICI
1: WFOJWJEJWJDJ
2: XGPKXKFKXKEK
3: YHQLYLGLYLFL
...
23: SBKFSFAFSFZF
24: TCLGTGBGTGAG
25: UDMHUHCHUHBH
26: VENIVIDIVICI
 
As a shorter alternative:
 
{def CAESAR
{def CAESAR.rot
{lambda {:shift :txt :alpha :i}
{A.get {% {+ {A.in? {A.get :i :txt} :alpha} 26 :shift} 26}
:alpha}}}
{def CAESAR.loop
{lambda {:shift :txt :alpha}
{S.map {CAESAR.rot :shift :txt :alpha}
{S.serie 0 {- {A.length :txt} 1}}} }}
{lambda {:shift :txt}
{S.replace \s by in
{CAESAR.loop :shift
{A.split {S.replace \s by in :txt}}
{A.split ABCDEFGHIJKLMNOPQRSTUVWXYZ}} }}}
-> CAESAR
 
{CAESAR 1 VENI VIDI VICI}
-> WFOJWJEJWJDJ
{CAESAR 25 WFOJWJEJWJDJ}
-> VENIVIDIVICI
 
</syntaxhighlight>
=={{header|langur}}==
Using the built-in rotate() function on a number over a range, a number outside of the range will pass through unaltered.
 
<syntaxhighlight lang="langur">val .rot = fn(.s, .key) {
cp2s map(fn(.c) { rotate(rotate(.c, .key, 'a'..'z'), .key, 'A'..'Z') }, s2cp .s)
}
 
 
val .s = "A quick brown fox jumped over something."
val .key = 3
 
writeln " original: ", .s
writeln "encrypted: ", .rot(.s, .key)
writeln "decrypted: ", .rot(.rot(.s, .key), -.key)</syntaxhighlight>
 
{{out}}
<pre> original: A quick brown fox jumped over something.
encrypted: X nrfzh yoltk clu grjmba lsbo pljbqefkd.
decrypted: A quick brown fox jumped over something.</pre>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">key = 7
 
Print "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 1,945 ⟶ 4,441:
CaesarCypher$ = (CaesarCypher$ + Chr$(rotate))
Next i
End Function</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">function caesarCipher rot phrase
local rotPhrase, lowerLetters, upperLetters
put "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" into lowerLetters
Line 1,963 ⟶ 4,458:
end repeat
return rotPhrase
end caesarCipher</langsyntaxhighlight>
 
=={{header|Logo}}==
{{trans|Common Lisp}}
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">; some useful constants
make "lower_a ascii "a
make "lower_z ascii "z
Line 2,001 ⟶ 4,495:
print sentence "|Encrypted:| :ciphertext
print sentence "|Recovered:| :recovered
bye</langsyntaxhighlight>
 
{{out}}
Line 2,007 ⟶ 4,501:
Encrypted: Wkh ilyh eralqj zlcdugv mxps txlfnob
Recovered: The five boxing wizards jump quickly</pre>
 
=={{header|Lua}}==
 
<langsyntaxhighlight Lualang="lua">local function encrypt(text, key)
return text:gsub("%a", function(t)
local base = (t:lower() == t and string.byte('a') or string.byte('A'))
Line 2,040 ⟶ 4,533:
print("Decrypted text: ", decrypted)
end
</syntaxhighlight>
</lang>
 
 
'''Fast version'''
<syntaxhighlight lang="lua">local memo = {}
 
local function make_table(k)
local t = {}
local a, A = ('a'):byte(), ('A'):byte()
 
for i = 0,25 do
local c = a + i
local C = A + i
local rc = a + (i+k) % 26
local RC = A + (i+k) % 26
t[c], t[C] = rc, RC
end
 
return t
end
 
local function caesar(str, k, decode)
k = (decode and -k or k) % 26
 
local t = memo[k]
if not t then
t = make_table(k)
memo[k] = t
end
 
local res_t = { str:byte(1,-1) }
for i,c in ipairs(res_t) do
res_t[i] = t[c] or c
end
return string.char(unpack(res_t))
end</syntaxhighlight>
=={{header|M2000 Interpreter}}==
We use a Buffer object (is a pointer type to a block of memory), to store string, to have access using unsigned integers.
 
<syntaxhighlight lang="m2000 interpreter">
a$="THIS IS MY TEXT TO ENCODE WITH CAESAR CIPHER"
Function Cipher$(a$, N) {
If Len(a$)=0 Then Exit
a$=Ucase$(a$)
\\ Integer in Mem is unsigned number
Buffer Mem as Integer*Len(a$)
Return Mem, 0:=a$
For i=0 to Len(a$)-1 {
If Eval(mem, i)>=65 and Eval(mem, i)<=90 then Return Mem, i:=(Eval(mem, i)-39+n) mod 26 + 65
}
=Eval$(Mem)
}
B$=Cipher$(a$, 10)
Print B$
Print Cipher$(B$,-10)
 
n=1 ' n negative or positive or zero
for i=65 to 65+25
a=(1+(i -64)+n+24) mod 26 + 65
? chr$(a),
next
</syntaxhighlight>
?
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
> StringTools:-Encode( "The five boxing wizards jump quickly", encoding = alpharot[3] );
"Wkh ilyh eralqj zlcdugv mxps txlfnob"
Line 2,049 ⟶ 4,604:
> StringTools:-Encode( %, encoding = alpharot[ 23 ] );
"The five boxing wizards jump quickly"
</syntaxhighlight>
</lang>
(The symbol % refers the the last (non-NULL) value computed.)
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">cypher[mesg_String,n_Integer]:=StringReplace[mesg,Flatten[Thread[Rule[#,RotateLeft[#,n]]]&/@CharacterRange@@@{{"a","z"},{"A","Z"}}]]</langsyntaxhighlight>
{{out}}
<pre>cypher["The five boxing wizards jump quickly",3]
-> Wkh ilyh eralqj zlcdugv mxps txlfnob</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight Matlablang="matlab"> function s = cipherCaesar(s, key)
s = char( mod(s - 'A' + key, 25 ) + 'A');
end;
function s = decipherCaesar(s, key)
s = char( mod(s - 'A' - key, 25 ) + 'A');
end; </langsyntaxhighlight>
Here is a test:
<langsyntaxhighlight Matlablang="matlab"> decipherCaesar(cipherCaesar('ABC',4),4)
ans = ABC </langsyntaxhighlight>
=={{header|Microsoft Small Basic}}==
<syntaxhighlight lang="microsoft small basic">
TextWindow.Write("Enter a 1-25 number key (-ve number to decode): ")
key = TextWindow.ReadNumber()
TextWindow.Write("Enter message: ")
message = text.ConvertToUpperCase(TextWindow.Read())
caeser = ""
For n = 1 To Text.GetLength(message)
letter = Text.GetSubText(message,n,1)
code = Text.GetCharacterCode(letter)
If code = 32 Then
newCode = 32
Else
newCode = code + key
If newCode > 90 Then
newCode = newCode - 26
ElseIf newCode < 65 then
newCode = newCode + 26
EndIf
EndIf
codeLetter = Text.GetCharacter(newCode)
caeser = Text.Append(caeser,codeLetter)
EndFor
TextWindow.WriteLine(message)
TextWindow.WriteLine(caeser)
</syntaxhighlight>
{{out}}
<pre>Enter a 1-25 number key (-ve number to decode): 10
Enter message: HAVE A NICE DAY
HAVE A NICE DAY
RKFO K XSMO NKI
Press any key to continue...
 
Enter a 1-25 number key (-ve number to decode): -10
Enter message: RKFO K XSMO NKI
RKFO K XSMO NKI
HAVE A NICE DAY
Press any key to continue...
</pre>
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">caesar = function(s, key)
chars = s.values
for i in chars.indexes
c = chars[i]
if c >= "a" and c <= "z" then chars[i] = char(97 + (code(c)-97+key)%26)
if c >= "A" and c <= "Z" then chars[i] = char(65 + (code(c)-65+key)%26)
end for
return chars.join("")
end function
 
print caesar("Hello world!", 7)
print caesar("Olssv dvysk!", 26-7)</syntaxhighlight>
 
{{out}}
<pre>Olssv dvysk!
Hello world!</pre>
=={{header|ML}}==
==={{header|mLite}}===
In this implementation, the offset can be positive or negative and is wrapped around if greater than 25 or less than -25.
<langsyntaxhighlight lang="ocaml">fun readfile () = readfile []
| x = let val ln = readln ()
in if eof ln then
Line 2,112 ⟶ 4,720:
;
map println ` map (fn s = encipher (s,ston ` default (argv 0, "1"))) ` readfile ();
</syntaxhighlight>
</lang>
The string for encoding is supplied as an input stream, and the offset supplied on the command line (defaults to 1). For example
<pre>echo The cat sat on the mat | mlite -f caecip.m ~5</pre>
Output:
<pre>Ocz xvo nvo ji ocz hvo</pre>
=={{header|Modula-2}}==
{{trans|Java}}
<syntaxhighlight lang="modula2">MODULE CaesarCipher;
FROM Conversions IMPORT IntToStr;
FROM Terminal IMPORT WriteString, WriteLn, ReadChar;
 
TYPE String = ARRAY[0..64] OF CHAR;
 
PROCEDURE Encrypt(p : String; key : CARDINAL) : String;
VAR e : String;
VAR i,t : CARDINAL;
VAR c : CHAR;
BEGIN
FOR i:=0 TO HIGH(p) DO
IF p[i]=0C THEN BREAK; END;
 
t := ORD(p[i]);
IF (p[i]>='A') AND (p[i]<='Z') THEN
t := t + key;
IF t>ORD('Z') THEN
t := t - 26;
END;
ELSIF (p[i]>='a') AND (p[i]<='z') THEN
t := t + key;
IF t>ORD('z') THEN
t := t - 26;
END;
END;
e[i] := CHR(t);
END;
RETURN e;
END Encrypt;
 
PROCEDURE Decrypt(p : String; key : CARDINAL) : String;
VAR e : String;
VAR i,t : CARDINAL;
VAR c : CHAR;
BEGIN
FOR i:=0 TO HIGH(p) DO
IF p[i]=0C THEN BREAK; END;
 
t := ORD(p[i]);
IF (p[i]>='A') AND (p[i]<='Z') THEN
t := t - key;
IF t<ORD('A') THEN
t := t + 26;
END;
ELSIF (p[i]>='a') AND (p[i]<='z') THEN
t := t - key;
IF t<ORD('a') THEN
t := t + 26;
END;
END;
e[i] := CHR(t);
END;
RETURN e;
END Decrypt;
 
VAR txt,enc : String;
VAR key : CARDINAL;
BEGIN
txt := "The five boxing wizards jump quickly";
key := 3;
 
WriteString("Original: ");
WriteString(txt);
WriteLn;
 
enc := Encrypt(txt, key);
WriteString("Encrypted: ");
WriteString(enc);
WriteLn;
 
WriteString("Decrypted: ");
WriteString(Decrypt(enc, key));
WriteLn;
 
ReadChar;
END CaesarCipher.</syntaxhighlight>
=={{header|Modula-3}}==
This implementation distinguishes between "encoding" and "encryption."
The former turns letters into numbers;
the latter turns numbers into different ("cryptic") numbers.
The distinction between "decoding" and "decryption" is similar.
It also illustrates the use of exceptions in Modula-3.
 
<syntaxhighlight lang="modula3">MODULE Caesar EXPORTS Main;
 
IMPORT IO, IntSeq, Text;
 
EXCEPTION BadCharacter;
(* Used whenever message contains a non-alphabetic character. *)
 
PROCEDURE Encode(READONLY message: TEXT; numbers: IntSeq.T) RAISES { BadCharacter } =
(*
Converts upper or lower case letter to 0..25.
Raises a "BadCharacter" exception for non-alphabetic characters.
*)
VAR
c: CHAR;
v: INTEGER;
BEGIN
FOR i := 0 TO Text.Length(message) - 1 DO
c := Text.GetChar(message, i);
CASE c OF
| 'A'..'Z' => v := ORD(c) - ORD('A');
| 'a'..'z' => v := ORD(c) - ORD('a');
ELSE
RAISE BadCharacter;
END;
numbers.addhi(v);
END;
END Encode;
 
PROCEDURE Decode(READONLY numbers: IntSeq.T; VAR message: TEXT) =
(* converts numbers in 0..26 to lower case characters *)
BEGIN
FOR i := 0 TO numbers.size() - 1 DO
message := message & Text.FromChar(VAL(numbers.get(i) + ORD('a'), CHAR));
END;
END Decode;
 
PROCEDURE Crypt(numbers: IntSeq.T; key: INTEGER) =
(*
In the Caesar cipher, encryption and decryption are really the same;
one adds the key, the other subtracts it. We can view this as adding a positive
or nevative integer; the common task is adding an integer. We call this "Crypt".
*)
BEGIN
FOR i := 0 TO numbers.size() - 1 DO
numbers.put(i, (numbers.get(i) + key) MOD 26);
END;
END Crypt;
 
PROCEDURE Encrypt(numbers: IntSeq.T; key := 4) =
(*
Encrypts a message of numbers using the designated key.
The result is also stored in "numbers".
*)
BEGIN
Crypt(numbers, key);
END Encrypt;
 
PROCEDURE Decrypt(numbers: IntSeq.T; key := 4) =
(*
Decrypts a message of numbers using the designated key.
The result is also stored in "numbers".
*)
BEGIN
Crypt(numbers, -key);
END Decrypt;
 
VAR
 
message := "";
buffer := NEW(IntSeq.T).init(22); (* sequence of 22 int's *)
 
BEGIN
TRY
Encode("WhenCaesarSetOffToGaul", buffer);
EXCEPT BadCharacter =>
(*
This should never occur.
Try adding spaces to the above to see what happens.
*)
IO.Put("Encountered a bad character in the input; completing partial task\n");
END;
Encrypt(buffer);
Decrypt(buffer);
Decode(buffer, message);
IO.Put(message); IO.PutChar('\n');
END Caesar.</syntaxhighlight>
 
{{out}}
Notice the output comes out all lower-case.
<pre>
whencaesarsetofftogaul
</pre>
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">def caesar_encode(plaintext, shift)
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercase = "abcdefghijklmnopqrstuvwxyz"
cipher = ""
for char in plaintext
if char in uppercase
cipher += uppercase[uppercase[char] - (26 - shift)]
else if char in lowercase
cipher += lowercase[lowercase[char] - (26 - shift)]
else
cipher += char
end
end
return cipher
end
 
def caesar_decode(cipher, shift)
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercase = "abcdefghijklmnopqrstuvwxyz"
 
plaintext = ""
for char in cipher
if char in uppercase
plaintext += uppercase[uppercase[char] - shift]
else if char in lowercase
plaintext += lowercase[lowercase[char] - shift]
else
plaintext += char
end
end
 
return plaintext
end</syntaxhighlight>
=={{header|NetRexx}}==
The cipher code in this sample is also used in the [[Rot-13#NetRexx|Rot-13&nbsp;&ndash;&nbsp;NetRexx]] task.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols nobinary
Line 2,211 ⟶ 5,032:
 
method isFalse public static returns boolean
return \isTrue</langsyntaxhighlight>
 
<pre style="height: 60ex; overflow: scroll;">
Line 2,304 ⟶ 5,125:
HI
</pre>
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import strutils
 
proc caesar(s: string, k: int, decode = false): string =
Line 2,320 ⟶ 5,140:
let enc = caesar(msg, 11)
echo enc
echo caesar(enc, 11, decode = true)</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
Works with oo2c version2
<langsyntaxhighlight lang="oberon2">
MODULE Caesar;
IMPORT
Line 2,384 ⟶ 5,203:
 
END Caesar.
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,391 ⟶ 5,210:
The five boxing wizards jump quickly =e=> Wkh ilyh eralqj zlcdugv mxps txlfnob =d=> The five boxing wizards jump quickly
</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Caesar {
function : native : Encode(enc : String, offset : Int) ~ String {
Line 2,423 ⟶ 5,241:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,429 ⟶ 5,247:
the quick brown fox jumped over the lazy dog
</pre>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let islower c =
c >= 'a' && c <= 'z'
 
Line 2,438 ⟶ 5,255:
 
let rot x str =
let upchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
and lowchars = "abcdefghijklmnopqrstuvwxyz" in
let rec decal x =
if x < 0 then decal (x + 26) else x
in
let x = (decal x) mod 26 in
let decal_up = x - (int_of_char 'A')
and decal_low = x - (int_of_char 'a') in
let len = String.length str in
let res = String.create len in
for i = 0 to pred len do
let c = str.[i] in
if islower c then
let j = ((int_of_char c) + decal_low) mod 26 in
res.[i] <- lowchars.[j]
else if isupper c then
let j = ((int_of_char c) + decal_up) mod 26 in
res.[i] <- upchars.[j]
else
res.[i] <- c
done;
(res)
 
(* or in OCaml 4.00+:
let rot x =
let upchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
and lowchars = "abcdefghijklmnopqrstuvwxyz" in
Line 2,480 ⟶ 5,272:
else
c
) str</syntaxhighlight>
)
<syntaxhighlight lang="ocaml">let () =
*)</lang>
<lang ocaml>let () =
let key = 3 in
let orig = "The five boxing wizards jump quickly" in
Line 2,490 ⟶ 5,281:
print_endline deciphered;
Printf.printf "equal: %b\n" (orig = deciphered)
;;</langsyntaxhighlight>
{{out}}
<pre>$ ocaml caesar.ml
Line 2,496 ⟶ 5,287:
The five boxing wizards jump quickly
equal: true</pre>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: ceasar(c, key)
c dup isLetter ifFalse: [ return ]
isUpper ifTrue: [ 'A' ] else: [ 'a' ] c key + over - 26 mod + ;
 
: cipherE(s, key) s map(#[ key ceasar ]) charsAsString ;
: cipherD(s, key) cipherE(s, 26 key - ) ;</langsyntaxhighlight>
 
{{out}}
Line 2,514 ⟶ 5,304:
Pack my box with five dozen liquor jugs.
</pre>
 
=={{header|OOC}}==
<langsyntaxhighlight lang="ooc">main: func (args: String[]) {
shift := args[1] toInt()
if (args length != 3) {
Line 2,534 ⟶ 5,323:
str println()
}
}</langsyntaxhighlight>
{{out}}
<pre>$ ./caesar 8 "This should be a fairly original sentence."
Line 2,540 ⟶ 5,329:
$ ./caesar -9 "Yet another, fairly original sentence!"
Pvk refkyvi, wrzicp fizxzerc jvekvetv!</pre>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">enc(s,n)={
Strchr(Vecsmall(apply(k->if(k>96&&k<123,(k+n-97)%26+97, if(k>64&&k<91, (k+n-65)%26+65, k)),
Vec(Vecsmall(s)))))
};
dec(s,n)=enc(s,-n);</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program CaesarCipher(output);
 
procedure encrypt(var message: string; key: integer);
Line 2,585 ⟶ 5,372:
decrypt(message, key);
writeln ('Decrypted message: ', message);
readln;
end.</lang>
end.</syntaxhighlight>
{{out}}
<pre>>: ./CaesarCipher
Line 2,592 ⟶ 5,380:
Decrypted message: The five boxing wizards jump quickly
>: </pre>
 
=={{header|Perl}}==
 
<langsyntaxhighlight Perllang="perl">sub caesar {
my ($message, $key, $decode) = @_;
$key = 26 - $key if $decode;
Line 2,606 ⟶ 5,393:
print "msg: $msg\nenc: $enc\ndec: $dec\n";
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,612 ⟶ 5,399:
enc: DRO PSFO LYHSXQ GSJKBNC TEWZ AESMUVI
dec: THE FIVE BOXING WIZARDS JUMP QUICKLY</pre>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2015.12}}
<lang perl6>my @alpha = 'A' .. 'Z';
sub encrypt ( $key where 1..25, $plaintext ) {
$plaintext.trans( @alpha Z=> @alpha.rotate($key) );
}
sub decrypt ( $key where 1..25, $cyphertext ) {
$cyphertext.trans( @alpha.rotate($key) Z=> @alpha );
}
 
my $original = 'THE FIVE BOXING WIZARDS JUMP QUICKLY';
my $en = encrypt( 13, $original );
my $de = decrypt( 13, $en );
 
.say for $original, $en, $de;
 
say 'OK' if $original eq all( map { .&decrypt(.&encrypt($original)) }, 1..25 );</lang>
{{out}}
<pre>THE FIVE BOXING WIZARDS JUMP QUICKLY
GUR SVIR OBKVAT JVMNEQF WHZC DHVPXYL
THE FIVE BOXING WIZARDS JUMP QUICKLY
OK</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence alpha_b = repeat(0,255)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
alpha_b['A'..'Z'] = 'A'
<span style="color: #004080;">sequence</span> <span style="color: #000000;">alpha_b</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">255</span><span style="color: #0000FF;">)</span>
alpha_b['a'..'z'] = 'a'
<span style="color: #000000;">alpha_b</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">..</span><span style="color: #008000;">'Z'</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'A'</span>
 
<span style="color: #000000;">alpha_b</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'a'</span><span style="color: #0000FF;">..</span><span style="color: #008000;">'z'</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'a'</span>
function caesar(string s, integer key)
integer ch, base
<span style="color: #008080;">function</span> <span style="color: #000000;">caesar</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">)</span>
for i=1 to length(s) do
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">base</span>
ch = s[i]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
base = alpha_b[ch]
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
if base then
<span style="color: #000000;">base</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">alpha_b</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">]</span>
s[i] = base+remainder(ch-base+key,26)
<span style="color: #008080;">if</span> <span style="color: #000000;">base</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">-</span><span style="color: #000000;">base</span><span style="color: #0000FF;">+</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">26</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return s
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
string s = "One fine day in the middle of the night, two dead men got up to fight. \n"&
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
"Back to back they faced each other, drew their swords and shot each other. %^&*()[",
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"One fine day in the middle of the night, two dead men got up to fight. \n"</span><span style="color: #0000FF;">&</span>
e = caesar(s,5),
<span style="color: #008000;">"Back to back they faced each other, drew their swords and shot each other. %^&*()["</span><span style="color: #0000FF;">,</span>
r = caesar(e,26-5) ?e ?r</lang>
<span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">caesar</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">caesar</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">26</span><span style="color: #0000FF;">-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">e</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">r</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,663 ⟶ 5,429:
Back to back they faced each other, drew their swords and shot each other. %^&*()[
</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
function caesarEncode( $message, $key ){
$plaintext = strtolower( $message );
Line 2,683 ⟶ 5,448:
 
echo caesarEncode( "The quick brown fox Jumped over the lazy Dog", 12 ), "\n";
?></langsyntaxhighlight>
{{out}}
<pre>ftq cguow ndaiz raj vgybqp ahqd ftq xmlk pas</pre>
 
Or, using PHP's '''strtr()''' built-in function
 
<syntaxhighlight lang="php"><?php
 
function caesarEncode($message, $key) {
$from = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$to = substr($from, $key) . substr($from, 0, $key);
return strtr($message, $from, $to);
}
 
echo caesarEncode('THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG', 12), PHP_EOL;</syntaxhighlight>
 
{{out}}
<pre>FTQ CGUOW NDAIZ RAJ VGYBQP AHQD FTQ XMLK PAS</pre>
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
S = "All human beings are born free and equal in dignity and rights.",
println(S),
println(caesar(S,5)),
println(caesar(caesar(S,5),-5)),
nl.
 
caesar(String, N) = Cipher =>
Lower = [chr(I): I in 97..122],
Upper = [chr(I): I in 65..90],
M = create_map(Lower, Upper, N),
% If a char is not in a..zA..z then show it as it is.
Cipher := [M.get(C,C) : C in String].
 
create_map(Lower,Upper, N) = M =>
M = new_map(),
Len = Lower.length,
foreach(I in 1..Len)
II = (N+I) mod Len,
if II == 0 then II := Len end, % Adjust for 1 based
M.put(Upper[I],Upper[II]),
M.put(Lower[I],Lower[II])
end.
</syntaxhighlight>
 
{{out}}
<pre>Picat> main
All human beings are born free and equal in dignity and rights.
Fqq mzrfs gjnslx fwj gtws kwjj fsi jvzfq ns inlsnyd fsi wnlmyx.
All human beings are born free and equal in dignity and rights.</pre>
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(setq *Letters (apply circ (mapcar char (range 65 90))))
 
(de caesar (Str Key)
(pack
(mapcar '((C) (cadr (nth (member C *Letters) Key)))
(chop (uppc Str)) ) ) )</langsyntaxhighlight>
Test:
<pre>: (caesar "IBM" 25)
Line 2,704 ⟶ 5,514:
: (caesar @ (- 26 7))
-> "THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGSBACK"</pre>
=={{header|Pike}}==
Pike has built in support for substitution cryptos in the Crypto module. It's possible to set the desired alphabet, but the default a-z matches the Caesar range.
<syntaxhighlight lang="pike">object c = Crypto.Substitution()->set_rot_key(2);
string msg = "The quick brown fox jumped over the lazy dogs";
string msg_s2 = c->encrypt(msg);
c->set_rot_key(11);
string msg_s11 = c->encrypt(msg);
string decoded = c->decrypt(msg_s11);
 
write("%s\n%s\n%s\n%s\n", msg, msg_s2, msg_s11, decoded);</syntaxhighlight>
 
{{out}}
<pre>
The quick brown fox jumped over the lazy dogs
Vjg swkem dtqyp hqz lworgf qxgt vjg ncba fqiu
Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozrd
The quick brown fox jumped over the lazy dogs
</pre>
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">caesar: procedure options (main);
declare cypher_string character (52) static initial
((2)'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
Line 2,725 ⟶ 5,552:
put skip list ('Decyphered text=', text);
 
end caesar;</langsyntaxhighlight>
{{out}} with offset of 5:
<pre>
Line 2,732 ⟶ 5,559:
Decyphered text= THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG
</pre>
 
=={{header|PowerShell}}==
<langsyntaxhighlight Powershelllang="powershell"># Author: M. McNabb
function Get-CaesarCipher
{
Line 2,808 ⟶ 5,634:
$OutText = $null
}
}</langsyntaxhighlight>
Usage examples:
<pre>
Line 2,825 ⟶ 5,651:
Vsxo drboo;
</pre>
 
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}
{{libheader|clpfd}}
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(clpfd)).
 
caesar :-
Line 2,861 ⟶ 5,686:
 
% compute values of V1 and V2
label([A, V1, V2]).</langsyntaxhighlight>
{{out}}
<pre> ?- caesar.
Line 2,869 ⟶ 5,694:
true .
</pre>
 
=={{header|PureBasic}}==
The case is maintained for alphabetic characters (uppercase/lowercase input = uppercase/lowercase output) while non-alphabetic characters, if present are included and left unchanged in the result.
<syntaxhighlight lang="basic">
<lang PureBasic>Procedure.s CC_encrypt(plainText.s, key, reverse = 0)
Procedure.s CC_encrypt(plainText.s, key, reverse = 0)
;if reverse <> 0 then reverse the encryption (decrypt)
If reverse: reverse = 26: key = 26 - key: EndIf
Line 2,908 ⟶ 5,733:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre> Plain text = "The quick brown fox jumped over the lazy dogs."
Line 2,915 ⟶ 5,740:
===Alternate solution===
Here is an alternate and more advanced form of the encrypt procedure. It improves on the simple version in terms of speed, in case Caesar is using the cipher on some very long documents. It is meant to replace the encrypt procedure in the previous code and produces identical results.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.s CC_encrypt(text.s, key, reverse = 0)
;if reverse <> 0 then reverse the encryption (decrypt)
Protected i, *letter.Character, *resultLetter.Character, result.s = Space(Len(text))
Line 2,935 ⟶ 5,760:
Wend
ProcedureReturn result
EndProcedure</lang>
</syntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight Pythonlang="python">def caesar(s, k, decode = False):
if decode: k = 26 - k
return "".join([chr((ord(i) - 65 + k) % 26 + 65)
Line 2,948 ⟶ 5,774:
enc = caesar(msg, 11)
print enc
print caesar(enc, 11, decode = True)</langsyntaxhighlight>
{{out}}
<pre>The quick brown fox jumped over the lazy dogs
Line 2,955 ⟶ 5,781:
Alternate solution
{{works with|Python|2.x}} (for 3.x change <code>string.maketrans</code> to <code>str.maketrans</code>)
<langsyntaxhighlight lang="python">import string
def caesar(s, k, decode = False):
if decode: k = 26 - k
Line 2,969 ⟶ 5,795:
enc = caesar(msg, 11)
print enc
print caesar(enc, 11, decode = True)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,976 ⟶ 5,802:
The quick brown fox jumped over the lazy dogs
</pre>
 
Variant with memoization of translation tables
{{works with|Python|3.x}}
<syntaxhighlight lang="python">import string
def caesar(s, k = 13, decode = False, *, memo={}):
if decode: k = 26 - k
k = k % 26
table = memo.get(k)
if table is None:
table = memo[k] = str.maketrans(
string.ascii_uppercase + string.ascii_lowercase,
string.ascii_uppercase[k:] + string.ascii_uppercase[:k] +
string.ascii_lowercase[k:] + string.ascii_lowercase[:k])
return s.translate(table)</syntaxhighlight>
 
A compact alternative solution
<langsyntaxhighlight lang="python">
from string import ascii_uppercase as abc
 
Line 2,988 ⟶ 5,828:
print(caesar(msg, 11))
print(caesar(caesar(msg, 11), 11, True))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,994 ⟶ 5,834:
THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGS
</pre>
=={{header|QBasic}}==
{{works with|QBasic}}
{{works with|QuickBasic}}
{{works with|True BASIC}} Note that TrueBasic uses '!' for comments
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">LET dec$ = ""
LET tipo$ = "cleartext "
 
PRINT "If decrypting enter 'd' -- else press enter ";
INPUT dec$
PRINT "Enter offset ";
INPUT llave
 
IF dec$ = "d" THEN
LET llave = 26 - llave
LET tipo$ = "ciphertext "
END IF
 
PRINT "Enter "; tipo$;
INPUT cadena$
 
LET cadena$ = UCASE$(cadena$)
LET longitud = LEN(cadena$)
 
FOR i = 1 TO longitud
LET iTemp = ASC(MID$(cadena$,i,1)) 'QBasic
'LET itemp = ORD((cadena$)[i:i+1-1][1:1]) 'True BASIC
IF iTemp > 64 AND iTemp < 91 THEN
LET iTemp = ((iTemp - 65) + llave) MOD 26 'QBasic
'LET iTemp = MOD(((iTemp - 65) + llave), 26) 'True BASIC
PRINT CHR$(iTemp + 65);
ELSE
PRINT CHR$(iTemp);
END IF
NEXT i
END</syntaxhighlight>
=={{header|Quackery}}==
<syntaxhighlight lang="quackery"> [ dup upper != ] is lower? ( c --> b )
 
[ dup lower != ] is upper? ( c --> b )
 
[ swap $ "" unrot witheach
[ dup lower? iff
[ over +
dup lower? not if
[ 26 - ] ]
else
[ dup upper? if
[ over +
dup upper? not if
[ 26 - ] ] ]
rot swap join swap ]
drop ] is caesar ( $ --> $ )
 
[ 26 swap - ] is decode ( n --> n )
 
$ "Fere libenter homines id quod volunt credunt."
dup echo$ cr
23 caesar dup echo$ cr
23 decode caesar echo$ cr</syntaxhighlight>
 
{{out}}
 
<pre>Fere libenter homines id quod volunt credunt.
Cbob ifybkqbo eljfkbp fa nrla slirkq zobarkq.
Fere libenter homines id quod volunt credunt.</pre>
=={{header|R}}==
This is a generalization of the Rot-13 solution for R at: http://rosettacode.org/wiki/Rot-13#R .
<syntaxhighlight lang="r">
<lang R>
# based on Rot-13 solution: http://rosettacode.org/wiki/Rot-13#R
ceasar <- function(x, key)
Line 3,027 ⟶ 5,932:
 
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,043 ⟶ 5,948:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
Line 3,063 ⟶ 5,968:
(define (encrypt s) (caesar s 1))
(define (decrypt s) (caesar s -1))
</syntaxhighlight>
</lang>
Example:
<pre>
Line 3,072 ⟶ 5,977:
"The five boxing wizards jump quickly."
</pre>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" line>my @alpha = 'A' .. 'Z';
sub encrypt ( $key where 1..25, $plaintext ) {
$plaintext.trans( @alpha Z=> @alpha.rotate($key) );
}
sub decrypt ( $key where 1..25, $cyphertext ) {
$cyphertext.trans( @alpha.rotate($key) Z=> @alpha );
}
 
my $original = 'THE FIVE BOXING WIZARDS JUMP QUICKLY';
my $en = encrypt( 13, $original );
my $de = decrypt( 13, $en );
 
.say for $original, $en, $de;
 
say 'OK' if $original eq all( map { .&decrypt(.&encrypt($original)) }, 1..25 );</syntaxhighlight>
{{out}}
<pre>THE FIVE BOXING WIZARDS JUMP QUICKLY
GUR SVIR OBKVAT JVMNEQF WHZC DHVPXYL
THE FIVE BOXING WIZARDS JUMP QUICKLY
OK</pre>
=={{header|Red}}==
<syntaxhighlight lang="red">
Red ["Ceasar Cipher"]
 
rot: func [
char [char!]
key [number!]
ofs [char!]
][
to-char key + char - ofs // 26 + ofs
]
 
caesar: function [
src [string!]
key [integer!]
][
lower: charset [#"a" - #"z"]
upper: charset [#"A" - #"Z"]
parse src [
any [
change s: [lower (o: #"a") | upper (o: #"A")] (rot s/1 key o)
| skip
]
]
src
]
 
encrypt: :caesar
decrypt: func spec-of :caesar [caesar src negate key]
</syntaxhighlight>
<pre>
>> print encrypt "Ceasar Cipher" 4
Giewev Gmtliv
>> print decrypt "Giewev Gmtliv" 4
Ceasar Cipher
>>
</pre>
=={{header|Retro}}==
Retro provides a number of classical cyphers in the '''crypto'''' library. This implementation is from the library.
<syntaxhighlight lang="retro">{{
<lang Retro>{{
variable offset
: rotate ( cb-c ) tuck - @offset + 26 mod + ;
Line 3,088 ⟶ 6,052:
( Example )
"THEYBROKEOURCIPHEREVERYONECANREADTHIS" 3 ceaser ( returns encrypted string )
23 ceaser ( returns decrypted string )</langsyntaxhighlight>
 
=={{header|REXX}}==
===only Latin letters===
This version conforms to the task's restrictions.
<langsyntaxhighlight lang="rexx">/*REXX program supports the Caesar cyphercipher for the Latin alphabet only, no punctuation */
/*──────────── no punctuation or blanks allowed, all lowercase Latin letters areis treated as uppercase. */
parseParse argUpper Arg key .; arg . p text /* get key & uppercased text to be used.ciphered*/
ptext=space(ptext,0) /* elide any and blanks /*elide any and all spaces (blanks). */
Say 'Caesar cipher key:' key /* echo the say 'Caesar cyphercipher key:' key /*echo the Caesar cypher key to console */
saySay ' plain text:' ptext /* " " plain text " " */
code=caesar(text,key)
y=Caesar(p, key); say ' cyphered:' y /* " " cyphered text " " */
z=Caesar(y,-key);Say ' say ' uncypheredciphered:' zcode /* " " uncyphered ciphered text " " */
back=caesar(code,-key)
if z\==p then say "plain text doesn't match uncyphered cyphered text."
exitSay ' unciphered:' back /* " " unciphered text /*stick a fork in it, we're all done. */
If back\==text Then
/*──────────────────────────────────────────────────────────────────────────────────────*/
Say "unciphered text doesn't match plain text."
Caesar: procedure; arg s,k; @='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Exit ak=abs(k) /* stick a fork in it, we're all /*obtain the absolute value of the key.done*/
/*----------------------------------------------------------------------*/
L=length(@) /*obtain the length of the @ string. */
caesar: Procedure
if ak>length(@)-1 | k==0 then call err k 'key is invalid.'
Parse Arg text,key
_=verify(s,@) /*any illegal characters specified ? */
abc='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if _\==0 then call err 'unsupported character:' substr(s, _, 1)
If abs(key)>length(abc)-1|key==0 Then
if k>0 then ky=k+1 /*either cypher it, or ··· */
Call err 'key ('key') is invalid.'
else ky=L+1-ak /* decypher it. */
badpos=verify(text,abc) /* any illegal character in the text */
return translate(s, substr(@||@,ky,L),@) /*return the processed text. */
If badpos\==0 Then
/*──────────────────────────────────────────────────────────────────────────────────────*/
Call err 'unsupported character:' substr(text,badpos,1)
err: say; say '***error***'; say; say arg(1); say; exit 13</lang>
If key>0 Then /* cipher */
'''output''' &nbsp; when using the input of: <br><br>
key2=key+1
22 The definition of a trivial program is one that has no bugs
Else /* decipher */
key2=length(abc)+key+1
Return translate(text,substr(abc||abc,key2,length(abc)),abc)
/*----------------------------------------------------------------------*/
err:
Say
Say '***error***'
Say
Say arg(1)
Say
Exit 13</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 22 The definition of a trivial program is one that has no bugs </tt>}}
<pre>
Caesar cypher key: 22
Line 3,127 ⟶ 6,102:
This version allows upper and lowercase Latin alphabet as well as all the
characters on the standard (computer) keyboard including blanks.
<langsyntaxhighlight lang="rexx">/*REXX program supports the Caesar cyphercipher for most keyboard characters including blanks.*/
parse/* arg key p /*get key and the text to be cyphered. including blanks.*/
Parse Arg key text say 'Caesar/* cypherget key:' key /*echoand the Caesartext cypherto keybe ciph to console*/
Say 'Caesar cipher say key:' key plain text:' p /* echo " " plain text the Caesar cipher "key " */
y=Caesar(p, key); saySay ' plain cypheredtext:' ytext /* " " cyphered plain text " " */
code=caesar(text,key)
z=Caesar(y,-key); say ' uncyphered:' z /* " " uncyphered text " " */
Say ' ciphered:' code /* " " ciphered text */
if z\==p then say "plain text doesn't match uncyphered cyphered text."
back=caesar(code,-key)
exit /*stick a fork in it, we're all done. */
Say ' unciphered:' back /* " " unciphered text */
/*──────────────────────────────────────────────────────────────────────────────────────*/
If back\==text Then
Caesar: procedure; parse arg s,k; @= 'abcdefghijklmnopqrstuvwxyz'
Say "plain text doesn't match unciphered ciphered text."
@=translate(@)@"0123456789(){}[]<>'" /*add uppercase, digitss, group symbols*/
Exit @=@'~!@#$%^&*_+:";?,./`-= ' /*also addstick othera charactersfork in it, we're toall thedone list*/
/*----------------------------------------------------------------------*/
L=length(@) /*obtain the length of the @ string. */
caesar: Procedure
ak=abs(k) /*obtain the absolute value of the key.*/
Parse Arg txt,ky
if ak>length(@)-1 | k==0 then call err k 'key is invalid.'
abcx='abcdefghijklmnopqrstuvwxyz'
_=verify(s,@) /*any illegal characters specified ? */
abcx=translate(abcx)abcx"0123456789(){}[]<>'" /*add uppercase, digits */
if _\==0 then call err 'unsupported character:' substr(s, _, 1)
abcx=abcx'~!@#$%^&*_+:";?,./`-= ' /* also add other characters */
if k>0 then ky=k+1 /*either cypher it, or ··· */
l=length(abcx) else ky=L+1-ak /* obtain the length of decypher it. abcx */
aky=abs(ky) /* absolute value of the key */
return translate(s, substr(@ || @, ky, L), @)
If aky>length(abcx)-1|ky==0 Then
/*──────────────────────────────────────────────────────────────────────────────────────*/
Call err ky 'key is invalid.'
err: say; say '***error***'; say; say arg(1); say; exit 13</lang>
badpos=verify(txt,abcx) /* any illegal character in txt */
'''output''' &nbsp; when using the input of: <br><br>
If badpos\==0 Then
31 Batman's hood is called a "cowl" (old meaning).
Call err 'unsupported character:' substr(txt,badpos,1)
If ky>0 Then /* cipher */
ky=ky+1
Else /* decipher */
ky=l+1-aky
/* return translated input */
Return translate(txt,substr(abcx||abcx,ky,l),abcx)
/*----------------------------------------------------------------------*/
err:
Say
Say '***error***'
Say
Say arg(1)
Say
Exit 13</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 31 Batman's hood is called a "cowl" (old meaning). </tt>}}
<pre>
Caesar cypher key: 31
Line 3,158 ⟶ 6,149:
</pre>
 
=={{header|RubyRing}}==
<syntaxhighlight lang="ring">
{{trans|Perl 6}}
# Project : Caesar cipher
{{works with|Ruby|1.9.2+}} (use of <code>rotate</code>)
<lang ruby>module CaesarCipher
AtoZ = (0..25).each_with_object({}) do |key,h|
str = [*"A".."Z"].rotate(key).join
h[key] = str + str.downcase
end
def encrypt(key, plaintext)
(1..25) === key or raise ArgumentError, "key not in 1..25"
plaintext.tr(AtoZ[0], AtoZ[key])
end
def decrypt(key, ciphertext)
(1..25) === key or raise ArgumentError, "key not in 1..25"
ciphertext.tr(AtoZ[key], AtoZ[0])
end
end
 
cipher = "pack my box with five dozen liquor jugs"
include CaesarCipher
abc = "abcdefghijklmnopqrstuvwxyz"
see "text is to be encrypted:" + nl
see cipher+ nl + nl
str = ""
key = random(24) + 1
see "key = " + key + nl + nl
see "encrypted:" + nl
caesarencode(cipher, key)
see str + nl + nl
cipher = str
see "decrypted again:" + nl
caesardecode(cipher, key)
see str + nl
 
func caesarencode(cipher, key)
original = "THEYBROKEOURCIPHEREVERYONECANREADTHIS"
str = ""
en = encrypt(3, original)
for n = 1 to len(cipher)
de = decrypt(3, en)
if cipher[n] != " "
pos = substr(abc, cipher[n])
if pos + key < len(abc)
str = str + abc[pos + key]
else
if (pos+key)-len(abc) != 0
str = str + abc[(pos+key)%len(abc)]
else
str = str +abc[key+pos]
ok
ok
else
str = str + " "
ok
next
return str
 
func caesardecode(cipher, key)
[original, en, de].each {|e| puts e}
str = ""
for n= 1 to len(cipher)
if cipher[n] != " "
pos = substr(abc, cipher[n])
if (pos - key) > 0 and pos != key
str = str + abc[pos - key]
loop
else
if pos = key
str = str + char(122)
else
str = str + abc[len(abc)-(key-pos)]
ok
ok
else
str = str + " "
ok
next
return str
</syntaxhighlight>
Output:
<pre>
text is to be encrypted:
pack my box with five dozen liquor jugs
 
key = 9
puts 'OK' if
(1..25).all? {|k| original == decrypt(k, encrypt(k, original))}</lang>
 
encrypted:
The Ruby translation saves the rotations in an <code>AtoZ</code> hash. (The Perl 6 code called <code>rotate()</code> during each encrypt or decrypt.)
yjlt vh kxg frcq oren mxinw urzdxa sdpb
 
decrypted again:
* <code>AtoZ[0]</code> becomes <code>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"</code>,
pack my box with five dozen liquor jugs
* <code>AtoZ[3]</code> becomes <code>"DEFGHIJKLMNOPQRSTUVWXYZABCdefghijklmnopqrstuvwxyzabc"</code>,
</pre>
* and so on.
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL Code
! Comments
|-
|
≪ → a shift
≪ '''IF''' DUP a ≥ LAST 26 + < AND
'''THEN''' a - shift + 26 MOD a + '''END'''
≫ ≫ ‘'''Rotate'''’ STO
≪ → string shift
≪ "" 1 string SIZE '''FOR''' j
string j DUP SUB NUM
65 shift '''Rotate''' 90 shift '''Rotate'''
CHR +
'''NEXT'''
≫ ''''CESAR'''' STO
|
''( m a shift -- n )''
if m in [a, a+26[
then shift it modulo 26
''( string shift -- string )''
Scan input string
extract jth ASCII code
shift if [A..Z] or [a..z]
back to character
|}
The following line of command delivers what is required:
"The quick brown fox jumped over the lazy dogs" '''CESAR'''
{{out}}
<pre>
1: "Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozrd"
</pre>
 
=={{header|Ruby}}==
When the key is 3, encryption uses <code>String#tr(AtoZ[0], AtoZ[3])</code> to substitute characters. Decryption uses <code>String#tr(AtoZ[3], AtoZ[0])</code>.
<syntaxhighlight lang="ruby">class String
ALFABET = ("A".."Z").to_a
 
def caesar_cipher(num)
self.tr(ALFABET.join, ALFABET.rotate(num).join)
end
 
end
 
#demo:
To make a rotation, Ruby is worse than Perl 6. Ruby needs two extra conversions: the code <code>[*"A".."Z"].rotate(key).join</code> uses <code>to_a</code> to convert a Range to an Array, to access the Array#rotate method. Then <code>join</code> converts the rotated Array to a String, because String#tr needs a String, not an Array.
encypted = "THEYBROKEOURCIPHEREVERYONECANREADTHIS".caesar_cipher(3)
decrypted = encypted.caesar_cipher(-3)
</syntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">input "Gimme a ofset:";ofst ' set any offset you like
 
a$ = "Pack my box with five dozen liquor jugs"
Line 3,220 ⟶ 6,298:
cipher$ = cipher$;code$
next i
END FUNCTION</langsyntaxhighlight>
{{out}}
<pre>Gimme a ofset:?9
Line 3,226 ⟶ 6,304:
Encrypted: Zkmu wi lyh gsdr psfo nyjox vsaeyb teqc
Decrypted: Pack my box with five dozen liquor jugs</pre>
 
=={{header|Rust}}==
This example shows proper error handling. It skips non-ASCII characters.
<langsyntaxhighlight lang="rust">use std::io::{self, Write};
use std::fmt::Display;
use std::{env, process};
Line 3,264 ⟶ 6,341:
let _ = writeln!(&mut io::stderr(), "ERROR: {}", msg);
process::exit(code);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object Caesar {
private val alphaU='A' to 'Z'
private val alphaL='a' to 'z'
Line 3,278 ⟶ 6,354:
def decode(text:String, key:Int)=encode(text,-key)
private def rot(a:IndexedSeq[Char], c:Char, key:Int)=a((c-a.head+key+a.size)%a.size)
}</langsyntaxhighlight>
<langsyntaxhighlight lang="scala">val text="The five boxing wizards jump quickly"
println("Plaintext => " + text)
val encoded=Caesar.encode(text, 3)
println("Ciphertext => " + encoded)
println("Decrypted => " + Caesar.decode(encoded, 3))</langsyntaxhighlight>
{{out}}
<pre>Plaintext => The five boxing wizards jump quickly
Line 3,292 ⟶ 6,368:
This version first creates non shifted and shifted character sequences
and then encodes and decodes by indexing between those sequences.
<langsyntaxhighlight lang="scala">class Caeser(val key: Int) {
@annotation.tailrec
private def rotate(p: Int, s: IndexedSeq[Char]): IndexedSeq[Char] = if (p < 0) rotate(s.length + p, s) else s.drop(p) ++ s.take(p)
Line 3,303 ⟶ 6,379:
def encode(c: Char) = if (as.contains(c)) bs(as.indexOf(c)) else c
def decode(c: Char) = if (bs.contains(c)) as(bs.indexOf(c)) else c
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="scala">val text = "The five boxing wizards jump quickly"
val myCaeser = new Caeser(3)
val encoded = text.map(c => myCaeser.encode(c))
println("Plaintext => " + text)
println("Ciphertext => " + encoded)
println("Decrypted => " + encoded.map(c => myCaeser.decode(c)))</langsyntaxhighlight>
 
{{out}}
Line 3,316 ⟶ 6,392:
Ciphertext => Wkh ilyh eralqj zlcdugv mxps txlfnob
Decrypted => The five boxing wizards jump quickly</pre>
 
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="scheme">;
; Works with R7RS-compatible Schemes (e.g. Chibi).
; Also current versions of Chicken, Gauche and Kawa.
Line 3,346 ⟶ 6,421:
(display (string-map caesar msg))
(newline)
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,352 ⟶ 6,427:
Gur dhvpx oebja sbk whzcf bire gur ynml qbt.
</pre>
 
=={{header|sed}}==
This code is roughly equivalent to the [[Rot-13#sed|rot-13]] cypher sed implementation, except that the conversion table is parameterized by a number and that the conversion done manually, instead of using `y///' command.
<langsyntaxhighlight lang="sed">#!/bin/sed -rf
# Input: <number 0..25>\ntext to encode
 
Line 3,391 ⟶ 6,465:
/\n\n/! s/\n([^\n])/\1\n/
t loop
s/\n\n.*//</langsyntaxhighlight>
{{out}}
<pre>
Line 3,404 ⟶ 6,478:
Error: Key must be <= 25
</pre>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func string: rot (in string: stri, in integer: encodingKey) is func
Line 3,434 ⟶ 6,507:
writeln("Encrypted: " <& rot(testText, exampleKey));
writeln("Decrypted: " <& rot(rot(testText, exampleKey), 26 - exampleKey));
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,441 ⟶ 6,514:
Decrypted: The five boxing wizards jump quickly
</pre>
 
=={{header|SequenceL}}==
You only have to write an encrypt and decrypt function for characters. The semantics of Normalize Transpose allow those functions to be applied to strings.
<langsyntaxhighlight lang="sequencel">import <Utilities/Sequence.sl>;
import <Utilities/Conversion.sl>;
 
Line 3,475 ⟶ 6,547:
"Input: \t" ++ args[1] ++ "\n" ++
"Encrypted:\t" ++ encrypted ++ "\n" ++
"Decrypted:\t" ++ decrypted;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,483 ⟶ 6,555:
Decrypted: Pack my box with five dozen liquor jugs."
</pre>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func caesar(msg, key, decode=false) {
decode && (key = (26 - key));
msg.gsub(/([A-Z])/i, {|c| ((c.uc.ord - 65 + key) % 26) + 65 -> chr});
Line 3,498 ⟶ 6,569:
say "msg: #{msg}";
say "enc: #{enc}";
say "dec: #{dec}";</langsyntaxhighlight>
 
{{out}}
Line 3,506 ⟶ 6,577:
dec: THE FIVE BOXING WIZARDS JUMP QUICKLY
</pre>
=={{header|Sinclair ZX81 BASIC}}==
 
Works with 1k of RAM. A negative key decodes.
<syntaxhighlight lang="basic"> 10 INPUT KEY
20 INPUT T$
30 LET C$=""
40 FOR I=1 TO LEN T$
50 LET L$=T$(I)
60 IF L$<"A" OR L$>"Z" THEN GOTO 100
70 LET L$=CHR$ (CODE L$+KEY)
80 IF L$>"Z" THEN LET L$=CHR$ (CODE L$-26)
90 IF L$<"A" THEN LET L$=CHR$ (CODE L$+26)
100 LET C$=C$+L$
110 NEXT I
120 PRINT C$</syntaxhighlight>
{{in}}
<pre>12
GALLIA EST OMNIS DIVISA IN PARTES TRES</pre>
{{out}}
<pre>SMXXUM QEF AYZUE PUHUEM UZ BMDFQE FDQE</pre>
{{in}}
<pre>
-12
SMXXUM QEF AYZUE PUHUEM UZ BMDFQE FDQE</pre>
{{out}}
<pre>GALLIA EST OMNIS DIVISA IN PARTES TRES</pre>
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
well, I'm lucky: the standard library already contains a rot:n method!
<langsyntaxhighlight Smalltalklang="smalltalk">'THE QUICK BROWN FOX' rot:3 -> 'WKH TXLFN EURZQ IRA' </langsyntaxhighlight>
but if it wasn't, here is an implementation for other smalltalks:
<langsyntaxhighlight lang="smalltalk">
!CharacterArray methodsFor:'encoding'!
rot:n
Line 3,532 ⟶ 6,627:
^ self
 
</syntaxhighlight>
</lang>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "caesar" )
@( description, "Implement a Caesar cipher, both encoding and ")
@( description, "decoding. The key is an integer from 1 to " )
@( description, "25. This cipher rotates (either towards left ")
@( description, "or right) the letters of the alphabet (A to " )
@( description, "Z). " )
@( see_also, "http://rosettacode.org/wiki/Caesar_cipher" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure caesar is
 
type cipher_value is new natural;
 
function to_cipher_value(c: character; offset: character) return cipher_value is
cv : integer;
begin
cv := ( numerics.pos(c)-numerics.pos(offset) ) mod 26;
return cipher_value(cv);
end to_cipher_value;
 
function to_character(cv: cipher_value; offset: character) return character is
begin
return strings.val( integer(cv) + numerics.pos(offset) );
end to_character;
 
function encrypt( plain: string; key: cipher_value) return string is
cv : cipher_value;
cipher_char : character;
cipher_text : string;
plain_char : character;
begin
for i in 1..strings.length( plain ) loop
plain_char := strings.element( plain, i);
if plain_char >= 'A' and plain_char <= 'Z' then
cv := ( to_cipher_value( plain_char, 'A')+key ) mod 26;
cipher_char := to_character( cv, 'A' );
elsif plain_char >= 'a' and plain_char <= 'z' then
cv := ( to_cipher_value( plain_char, 'a')+key ) mod 26;
cipher_char := to_character( cv, 'a' );
else
cipher_char := plain_char;
end if;
cipher_text := strings.overwrite( @, i, string( cipher_char ) );
end loop;
return cipher_text;
end encrypt;
 
text: string := get_line;
key: constant cipher_value := 3; -- Default key from "Commentarii de Bello Gallico"
 
begin
put_line("Plaintext ------------>" & text);
text := encrypt(text, key);
put_line("Ciphertext ----------->" & text);
text := encrypt(text, -key);
put_line("Decrypted Ciphertext ->" & text);
end caesar;</syntaxhighlight>
 
=={{header|SSEM}}==
ASCII didn't exit in 1948, and the task specification explicitly says we only need to convert Roman capitals; so we adopt a simpler encoding, representing the letters of the alphabet from <tt>A</tt>=0 to <tt>Z</tt>=25.
 
The program will convert one character at a time. Load the character code into storage address 20, and the key into address 19. The machine will halt with the cyphered encoding in the accumulator. A negative (two's complement) key decodes.
 
This is in fact a general solution that will work equally well with alphabets of more or fewer than 26 characters: simply replace the constant 26 in storage address 18 with 22 for Hebrew, 24 for Greek, 28 for Arabic, 33 for Russian, etc.
<syntaxhighlight lang="ssem">00101000000000100000000000000000 0. -20 to c
11001000000000010000000000000000 1. Sub. 19
10101000000001100000000000000000 2. c to 21
10101000000000100000000000000000 3. -21 to c
00000000000000110000000000000000 4. Test
10001000000000000000000000000000 5. 17 to CI
10101000000001100000000000000000 6. c to 21
10101000000000100000000000000000 7. -21 to c
01001000000000010000000000000000 8. Sub. 18
10101000000001100000000000000000 9. c to 21
10101000000000100000000000000000 10. -21 to c
00000000000001110000000000000000 11. Stop
01001000000000010000000000000000 12. Sub. 18
00000000000000110000000000000000 13. Test
00000000000001110000000000000000 14. Stop
10101000000000100000000000000000 15. -21 to c
00000000000001110000000000000000 16. Stop
11010000000000000000000000000000 17. 11
01011000000000000000000000000000 18. 26</syntaxhighlight>
=={{header|Stata}}==
 
<syntaxhighlight lang="stata">function caesar(s, k) {
u = ascii(s)
i = selectindex(u:>=65 :& u:<=90)
if (length(i)>0) u[i] = mod(u[i]:+(k-65), 26):+65
i = selectindex(u:>=97 :& u:<=122)
if (length(i)>0) u[i] = mod(u[i]:+(k-97), 26):+97
return(char(u))
}
 
caesar("layout", 20)
fusion</syntaxhighlight>
=={{header|Swift}}==
<syntaxhighlight lang="swift">
func usage(_ e:String) {
print("error: \(e)")
print("./caeser -e 19 a-secret-string")
print("./caeser -d 19 tskxvjxlskljafz")
}
 
func charIsValid(_ c:Character) -> Bool {
return c.isASCII && ( c.isLowercase || 45 == c.asciiValue ) // '-' = 45
}
 
func charRotate(_ c:Character, _ by:Int) -> Character {
var cv:UInt8! = c.asciiValue
if 45 == cv { cv = 96 } // if '-', set it to 'a'-1
cv += UInt8(by)
if 122 < cv { cv -= 27 } // if larget than 'z', reduce by 27
if 96 == cv { cv = 45 } // restore '-'
return Character(UnicodeScalar(cv))
}
 
func caesar(_ enc:Bool, _ key:Int, _ word:String) -> String {
let r = enc ? key : 27 - key
func charRotateWithKey(_ c:Character) -> Character {
return charRotate(c,r)
}
return String(word.map(charRotateWithKey))
}
 
func main() {
var encrypt = true
 
if 4 != CommandLine.arguments.count {
return usage("caesar expects exactly three arguments")
}
 
switch ( CommandLine.arguments[1] ) {
case "-e":
encrypt = true
case "-d":
encrypt = false
default:
return usage("first argument must be -e (encrypt) or -d (decrypt)")
}
 
guard let key = Int(CommandLine.arguments[2]) else {
return usage("second argument not a number (must be in range 0-26)")
}
 
if key < 0 || 26 < key {
return usage("second argument not in range 0-26")
}
 
if !CommandLine.arguments[3].allSatisfy(charIsValid) {
return usage("third argument must only be lowercase ascii characters, or -")
}
 
let ans = caesar(encrypt,key,CommandLine.arguments[3])
print("\(ans)")
}
 
func test() {
if ( Character("a") != charRotate(Character("a"),0) ) {
print("Test Fail 1")
}
if ( Character("-") != charRotate(Character("-"),0) ) {
print("Test Fail 2")
}
if ( Character("-") != charRotate(Character("z"),1) ) {
print("Test Fail 3")
}
if ( Character("z") != charRotate(Character("-"),26)) {
print("Test Fail 4")
}
if ( "ihgmkzma" != caesar(true,8,"a-zecret") ) {
print("Test Fail 5")
}
if ( "a-zecret" != caesar(false,8,"ihgmkzma") ) {
print("Test Fail 6")
}
}
 
test()
main()
</syntaxhighlight>
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.6; # Or TclOO package for 8.5
 
oo::class create Caesar {
Line 3,557 ⟶ 6,839:
string map $decryptMap $text
}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">set caesar [Caesar new 3]
set txt "The five boxing wizards jump quickly."
set enc [$caesar encrypt $txt]
Line 3,565 ⟶ 6,847:
puts "Original message = $txt"
puts "Encrypted message = $enc"
puts "Decrypted message = $dec"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,572 ⟶ 6,854:
Decrypted message = The five boxing wizards jump quickly.
</pre>
 
=={{header|True BASIC}}==
{{works with|QBasic}}
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">LET dec$ = ""
LET tipo$ = "cleartext "
 
PRINT "If decrypting enter 'd' -- else press enter ";
INPUT dec$
PRINT "Enter offset ";
INPUT llave
 
IF dec$ = "d" THEN
LET llave = 26 - llave
LET tipo$ = "ciphertext "
END IF
 
PRINT "Enter "; tipo$;
INPUT cadena$
 
LET cadena$ = UCASE$(cadena$)
LET longitud = LEN(cadena$)
 
FOR i = 1 TO longitud
!LET iTemp = ASC(MID$(cadena$,i,1)) 'QBasic
LET itemp = ORD((cadena$)[i:i+1-1][1:1]) !'True BASIC
IF iTemp > 64 AND iTemp < 91 THEN
!LET iTemp = ((iTemp - 65) + llave) MOD 26 'QBasic
LET iTemp = MOD(((iTemp - 65) + llave), 26) !'True BASIC
PRINT CHR$(iTemp + 65);
ELSE
PRINT CHR$(iTemp);
END IF
NEXT i
END</syntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
text="THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
PRINT "text orginal ",text
Line 3,597 ⟶ 6,915:
 
DECODED = EXCHANGE (encoded,secret2abc)
PRINT "encoded decoded ",decoded</langsyntaxhighlight>
{{out}}
<pre>
Line 3,604 ⟶ 6,922:
encoded decoded THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
</pre>
 
=={{header|TXR}}==
The strategy here, one of many possible ones, is to build, at run time,the arguments to be passed to deffilter to construct a pair of filters <code>enc</code> and <code>dec</code> for encoding and decoding. Filters are specified as tuples of strings.
<langsyntaxhighlight lang="txr">@(next :args)
@(cases)
@{key /[0-9]+/}
Line 3,629 ⟶ 6,946:
encoded: @{text :filter enc}
decoded: @{text :filter dec}
@(end)</langsyntaxhighlight>
{{out}}
<pre>$ ./txr caesar.txr 12 'Hello, world!'
Line 3,638 ⟶ 6,955:
decoded: Jgnnq, yqtnf!
</pre>
 
=={{header|TypeScript}}==
<langsyntaxhighlight lang="javascript">function replace(input: string, key: number) : string {
return input.replace(/([a-z])/g,
($1) => String.fromCharCode(($1.charCodeAt(0) + key + 26 - 97) % 26 + 97)
Line 3,653 ⟶ 6,969:
 
console.log('Enciphered: ' + encoded);
console.log('Deciphered: ' + decoded);</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|bash}}
I added a <tt>tr</tt> function to make this "pure" bash. In practice, you'd remove that function and use the external <tt>tr</tt> utility.
<langsyntaxhighlight lang="bash">caesar() {
local OPTIND
local encrypt n=0
Line 3,713 ⟶ 7,028:
echo "original: $txt"
echo "encrypted: $enc"
echo "decrypted: $dec"</langsyntaxhighlight>
{{out}}
<pre>
Line 3,719 ⟶ 7,034:
encrypted: Ymj knaj gtcnsl bnefwix ozru vznhpqd.
decrypted: The five boxing wizards jump quickly.</pre>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">decl string mode
while (not (or (= mode "encode") (= mode "decode")))
out "encode/decode: " console
Line 3,748 ⟶ 7,062:
end if
end for
out endl console</langsyntaxhighlight>
 
=={{header|Ursala}}==
The reification operator (<code>-:</code>) generates efficient code for applications like this given a table of inputs and outputs, which is obtained in this case by zipping the alphabet with itself rolled the right number of times, done separately for the upper and lower case letters and then combined.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 3,762 ⟶ 7,075:
#show+ # exhaustive test
 
test = ("n". <.enc"n",dec"n"+ enc"n"> plaintext)*= nrange/1 25</langsyntaxhighlight>
{{out}}
<pre style="overflow: auto; height: 6em;">
Line 3,815 ⟶ 7,128:
sgd ehud anwhmf vhyzqcr itlo pthbjkx SGD EHUD ANWHMF VHYZQCR ITLO PTHBJKX
the five boxing wizards jump quickly THE FIVE BOXING WIZARDS JUMP QUICKLY</pre>
=={{header|Vala}}==
This is a port of the C# code present in this page.
<syntaxhighlight lang="vala">static void println(string str) {
stdout.printf("%s\r\n", str);
}
 
static unichar encrypt_char(unichar ch, int code) {
if (!ch.isalpha()) return ch;
 
unichar offset = ch.isupper() ? 'A' : 'a';
return (unichar)((ch + code - offset) % 26 + offset);
}
 
static string encrypt(string input, int code) {
var builder = new StringBuilder();
 
unichar c;
for (int i = 0; input.get_next_char(ref i, out c);) {
builder.append_unichar(encrypt_char(c, code));
}
 
return builder.str;
}
 
static string decrypt(string input, int code) {
return encrypt(input, 26 - code);
}
 
const string test_case = "The quick brown fox jumped over the lazy dog";
 
void main() {
println(test_case);
println(encrypt(test_case, -1));
println(decrypt(encrypt(test_case, -1), -1));
}</syntaxhighlight>
 
{{out}}
<pre style="overflow: auto; height: 6em;">
The quick brown fox jumped over the lazy dog
Sgd pthbj aqnvm enw itlodc nudq sgd kvyx cnf
The quick brown fox jumped over the lwzy dog
</pre>
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
Option Explicit
 
Sub Main_Caesar()
Dim ch As String
ch = Caesar_Cipher("CAESAR: Who is it in the press that calls on me? I hear a tongue, shriller than all the music, Cry 'Caesar!' Speak; Caesar is turn'd to hear.", 14)
Debug.Print ch
Debug.Print Caesar_Cipher(ch, -14)
End Sub
 
Function Caesar_Cipher(sText As String, lngNumber As Long) As String
Dim Tbl, strGlob As String, strTemp As String, i As Long, bytAscii As Byte
Const MAJ As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Const NB_LETTERS As Byte = 26
Const DIFFASCIIMAJ As Byte = 65 - NB_LETTERS
Const DIFFASCIIMIN As Byte = 97 - NB_LETTERS
strTemp = sText
If lngNumber < NB_LETTERS And lngNumber > NB_LETTERS * -1 Then
strGlob = String(NB_LETTERS * 4, " ")
LSet strGlob = MAJ & MAJ & MAJ
Tbl = Split(StrConv(strGlob, vbUnicode), Chr(0))
For i = 1 To Len(strTemp)
If Mid(strTemp, i, 1) Like "[a-zA-Z]" Then
bytAscii = Asc(Mid(strTemp, i, 1))
If Mid(strTemp, i, 1) = Tbl(bytAscii - DIFFASCIIMAJ) Then
Mid(strTemp, i) = Tbl(bytAscii - DIFFASCIIMAJ + lngNumber)
Else
Mid(strTemp, i) = LCase(Tbl(bytAscii - DIFFASCIIMIN + lngNumber))
End If
End If
Next i
End If
Caesar_Cipher = strTemp
End Function
</syntaxhighlight>
 
{{out}}
<pre>QOSGOF: Kvc wg wh wb hvs dfsgg hvoh qozzg cb as? W vsof o hcbuis, gvfwzzsf hvob ozz hvs aigwq, Qfm 'Qosgof!' Gdsoy; Qosgof wg hifb'r hc vsof.
CAESAR: Who is it in the press that calls on me? I hear a tongue, shriller than all the music, Cry 'Caesar!' Speak; Caesar is turn'd to hear.</pre>
=={{header|VBScript}}==
Note that a left rotation has an equivalent right rotation so all rotations are converted to the equivalent right rotation prior to translation.
<syntaxhighlight lang="vb">
str = "IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES."
 
Wscript.Echo str
Wscript.Echo Rotate(str,5)
Wscript.Echo Rotate(Rotate(str,5),-5)
 
'Rotate (Caesar encrypt/decrypt) test <numpos> positions.
' numpos < 0 - rotate left
' numpos > 0 - rotate right
'Left rotation is converted to equivalent right rotation
 
Function Rotate (text, numpos)
 
dim dic: set dic = CreateObject("Scripting.Dictionary")
dim ltr: ltr = Split("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")
dim rot: rot = (26 + numpos Mod 26) Mod 26 'convert all to right rotation
dim ch
dim i
 
for i = 0 to ubound(ltr)
dic(ltr(i)) = ltr((rot+i) Mod 26)
next
 
Rotate = ""
 
for i = 1 to Len(text)
ch = Mid(text,i,1)
if dic.Exists(ch) Then
Rotate = Rotate & dic(ch)
else
Rotate = Rotate & ch
end if
next
 
End Function
</syntaxhighlight>
{{out}}
<pre>
D:\script>Caesar.vbs
IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES.
NY BFX YMJ GJXY TK YNRJX, NY BFX YMJ BTWXY TK YNRJX.
IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES.
</pre>
=={{header|Vedit macro language}}==
This implementation ciphers/deciphers a highlighted block of text in-place in current edit buffer.
<langsyntaxhighlight lang="vedit">#10 = Get_Num("Enter the key: positive to cipher, negative to de-cipher: ", STATLINE)
 
Goto_Pos(Block_Begin)
Line 3,828 ⟶ 7,270:
Char(1)
}
}</langsyntaxhighlight>
 
{{out}} with key 13:
Line 3,835 ⟶ 7,277:
Encrypted text: Dhvpx oebja Sbk whzcf bire gur ynml Qbt.
Decrypted text: Quick brown Fox jumps over the lazy Dog.
</pre>
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Module1
 
Function Encrypt(ch As Char, code As Integer) As Char
If Not Char.IsLetter(ch) Then
Return ch
End If
 
Dim offset = AscW(If(Char.IsUpper(ch), "A"c, "a"c))
Dim test = (AscW(ch) + code - offset) Mod 26 + offset
Return ChrW(test)
End Function
 
Function Encrypt(input As String, code As Integer) As String
Return New String(input.Select(Function(ch) Encrypt(ch, code)).ToArray())
End Function
 
Function Decrypt(input As String, code As Integer) As String
Return Encrypt(input, 26 - code)
End Function
 
Sub Main()
Dim str = "Pack my box with five dozen liquor jugs."
 
Console.WriteLine(str)
str = Encrypt(str, 5)
Console.WriteLine("Encrypted: {0}", str)
str = Decrypt(str, 5)
Console.WriteLine("Decrypted: {0}", str)
End Sub
 
End Module</syntaxhighlight>
{{out}}
<pre>Pack my box with five dozen liquor jugs.
Encrypted: Ufhp rd gtc bnym knaj itejs qnvztw ozlx.
Decrypted: Pack my box with five dozen liquor jugs.</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
import rand
 
const (
lo_abc = 'abcdefghijklmnopqrstuvwxyz'
up_abc = 'ABCDEFGHIJKLMNIPQRSTUVWXYZ'
)
 
fn main() {
key := rand.int_in_range(2, 25) or {13}
encrypted := caesar_encrypt('The five boxing wizards jump quickly', key)
println(encrypted)
println(caesar_decrypt(encrypted, key))
}
 
fn caesar_encrypt(str string, key int) string {
offset := key % 26
if offset == 0 {return str}
mut nchr := u8(0)
mut chr_arr := []u8{}
for chr in str {
if chr.ascii_str() in up_abc.split('') {
nchr = chr + u8(offset)
if nchr > u8(90) {nchr -= 26}
}
else if chr.ascii_str() in lo_abc.split('') {
nchr = chr + u8(offset)
if nchr > u8(122) {nchr -= 26}
}
else {nchr = chr}
chr_arr << nchr
}
return chr_arr.bytestr()
}
fn caesar_decrypt(str string, key int) string {
return caesar_encrypt(str, 26 - key)
}
</syntaxhighlight>
 
{{out}}
<pre>
Jxu vylu renydw mypqhti zkcf gkysabo
The five boxing wizards jump quickly
</pre>
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@let {
; this function only replaces letters and keeps case
ceasar &[s n] !!s.replace &"[a-z]"gi &[x] [
Line 3,855 ⟶ 7,381:
]
!!ceasar "abc $%^ ABC" 10
}</langsyntaxhighlight>
Returns:
<pre>"klm $%^ KLM"</pre>
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="wren">class Caesar {
static encrypt(s, key) {
var offset = key % 26
if (offset == 0) return s
var chars = List.filled(s.count, 0)
for (i in 0...s.count) {
var c = s[i].bytes[0]
var d = c
if (c >= 65 && c <= 90) { // 'A' to 'Z'
d = c + offset
if (d > 90) d = d - 26
} else if (c >= 97 && c <= 122) { // 'a' to 'z'
d = c + offset
if (d > 122) d = d - 26
}
chars[i] = d
}
return chars.reduce("") { |acc, c| acc + String.fromByte(c) }
}
 
static decrypt(s, key) { encrypt(s, 26 - key) }
}
 
var encoded = Caesar.encrypt("Bright vixens jump; dozy fowl quack.", 8)
System.print(encoded)
System.print(Caesar.decrypt(encoded, 8))</syntaxhighlight>
 
{{out}}
<pre>
Jzqopb dqfmva rcux; lwhg nwet yciks.
Bright vixens jump; dozy fowl quack.
</pre>
 
=={{header|X86 Assembly}}==
{{trans|C custom implementation}}
{{works with|GCC|7.3.0 - Ubuntu 18.04 64-bit}}
<syntaxhighlight lang="asm"> # Author: Ettore Forigo - Hexwell
 
.intel_syntax noprefix
 
.text
.globl main
main:
.PROLOGUE:
push rbp
mov rbp, rsp
sub rsp, 32
mov QWORD PTR [rbp-32], rsi # argv
.BODY:
mov BYTE PTR [rbp-1], 0 # shift = 0
 
.I_LOOP_INIT:
mov BYTE PTR [rbp-2], 0 # i = 0
jmp .I_LOOP_CONDITION # I_LOOP_CONDITION
.I_LOOP_BODY:
movzx edx, BYTE PTR[rbp-1] # shift
mov eax, edx # shift
sal eax, 2 # shift << 2 == i * 4
add eax, edx # shift * 4 + shift = shift * 5
add eax, eax # shift * 5 + shift * 5 = shift * 10
mov ecx, eax # shift * 10
mov rax, QWORD PTR [rbp-32] # argv
add rax, 8 # argv + 1
mov rdx, QWORD PTR [rax] # argv[1]
movzx eax, BYTE PTR [rbp-2] # i
add rax, rdx # argv[1] + i
movzx eax, BYTE PTR [rax] # argv[1][i]
add eax, ecx # shift * 10 + argv[1][i]
sub eax, 48 # shift * 10 + argv[1][i] - '0'
mov BYTE PTR [rbp-1], al # shift = shift * 10 + argv[1][i] - '0'
.I_LOOP_INCREMENT:
movzx eax, BYTE PTR [rbp-2] # i
add eax, 1 # i + 1
mov BYTE PTR [rbp-2], al # i++
.I_LOOP_CONDITION:
mov rax, QWORD PTR [rbp-32] # argv
add rax, 8 # argv + 1
mov rax, QWORD PTR [rax] # argv[1]
movzx edx, BYTE PTR [rbp-2] # i
add rax, rdx # argv[1] + i
movzx rax, BYTE PTR [rax] # argv[1][i]
test al, al # argv[1][i]?
jne .I_LOOP_BODY # I_LOOP_BODY
 
.CAESAR_LOOP_INIT:
mov BYTE PTR [rbp-2], 0 # i = 0
jmp .CAESAR_LOOP_CONDITION # CAESAR_LOOP_CONDITION
.CAESAR_LOOP_BODY:
mov rax, QWORD PTR [rbp-32] # argv
add rax, 16 # argv + 2
mov rdx, QWORD PTR [rax] # argv[2]
movzx eax, BYTE PTR [rbp-2] # i
add rax, rdx # argv[2] + i
mov rbx, rax # argv[2] + i
movzx eax, BYTE PTR [rax] # argv[2][i]
cmp al, 32 # argv[2][i] == ' '
je .CAESAR_LOOP_INCREMENT # CAESAR_LOOP_INCREMENT
movzx edx, BYTE PTR [rbx] # argv[2][i]
mov ecx, edx # argv[2][i]
movzx edx, BYTE PTR [rbp-1] # shift
add edx, ecx # argv[2][i] + shift
sub edx, 97 # argv[2][i] + shift - 'a'
mov BYTE PTR [rbx], dl # argv[2][i] = argv[2][i] + shift - 'a'
movzx eax, BYTE PTR [rbx] # argv[2][i]
cmp al, 25 # argv[2][i] <=> 25
jle .CAESAR_RESTORE_ASCII # <= CAESAR_RESTORE_ASCII
movzx edx, BYTE PTR [rbx] # argv[2][i]
sub edx, 26 # argv[2][i] - 26
mov BYTE PTR [rbx], dl # argv[2][i] = argv[2][i] - 26
.CAESAR_RESTORE_ASCII:
movzx edx, BYTE PTR [rbx] # argv[2][i]
add edx, 97 # argv[2][i] + 'a'
mov BYTE PTR [rbx], dl # argv[2][i] = argv[2][i] + 'a'
.CAESAR_LOOP_INCREMENT:
movzx eax, BYTE PTR [rbp-2] # i
add eax, 1 # i + 1
mov BYTE PTR [rbp-2], al # i++
.CAESAR_LOOP_CONDITION:
mov rax, QWORD PTR [rbp-32] # argv
add rax, 16 # argv + 2
mov rdx, QWORD PTR [rax] # argv[2]
movzx eax, BYTE PTR [rbp-2] # i
add rax, rdx # argv[2] + i
movzx eax, BYTE PTR [rax] # argv[2][i]
test al, al # argv[2][i]?
jne .CAESAR_LOOP_BODY # CAESAR_LOOP_BODY
 
mov rax, QWORD PTR [rbp-32] # argv
add rax, 16 # argv + 2
mov rax, QWORD PTR [rax] # argv[2]
mov rdi, rax # argv[2]
call puts # puts(argv[2])
 
.RETURN:
mov eax, 0 # 0
leave
ret # return 0</syntaxhighlight>
Usage:
<syntaxhighlight lang="bash">$ gcc caesar.S -o caesar
$ ./caesar 10 abc
klm
$ ./caesar 16 klm
abc</syntaxhighlight>
=={{header|XBasic}}==
{{trans|Modula-2}}
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">
PROGRAM "caesarcipher"
VERSION "0.0001"
 
DECLARE FUNCTION Entry()
INTERNAL FUNCTION Encrypt$(p$, key%%)
INTERNAL FUNCTION Decrypt$(p$, key%%)
 
FUNCTION Entry()
txt$ = "The five boxing wizards jump quickly"
key%% = 3
PRINT "Original: "; txt$
enc$ = Encrypt$(txt$, key%%)
PRINT "Encrypted: "; enc$
PRINT "Decrypted: "; Decrypt$(enc$, key%%)
END FUNCTION
 
FUNCTION Encrypt$(p$, key%%)
e$ = p$ ' In order to avoid iterative concatenations
FOR i = 0 TO LEN(p$) - 1
t@@ = p${i} ' or (slower) t@@ = ASC(p$, i + 1)
SELECT CASE TRUE
CASE (t@@ >= 'A') AND (t@@ <= 'Z'):
t@@ = t@@ + key@@
IF t&& > 'Z' THEN
t@@ = t@@ - 26
END IF
CASE (t@@ >= 'a') AND (t@@ <= 'z'):
t@@ = t@@ + key%%
IF t@@ > 'z' THEN
t@@ = t@@ - 26
END IF
END SELECT
e${i} = t@@
NEXT i
END FUNCTION e$
 
FUNCTION Decrypt$(p$, key%%)
e$ = p$ ' In order to avoid iterative concatenations
FOR i = 0 TO LEN(p$) - 1
t@@ = p${i} ' or (slower) t@@ = ASC(p$, i + 1)
SELECT CASE TRUE
CASE (t@@ >= 'A') AND (t@@ <= 'Z'):
t@@ = t@@ - key%%
IF t@@ < 'A' THEN
t@@ = t@@ + 26
END IF
CASE (t@@ >= 'a') AND (t@@ <= 'z'):
t@@ = t@@ - key%%
IF t@@ < 'a' THEN
t@@ = t@@ + 26
END IF
END SELECT
e${i} = t@@
NEXT i
END FUNCTION e$
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Original: The five boxing wizards jump quickly
Encrypted: Wkh ilyh eralqj zlcdugv mxps txlfnob
Decrypted: The five boxing wizards jump quickly
</pre>
=={{header|XBS}}==
<syntaxhighlight lang="xbs">set letters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"::split();
 
func caesar(text,shift:number=1){
set res:string="";
for(i=0;?text-1;1){
set t=text::at(i);
set n=(letters::find(t::upper())+shift)%?letters;
while(n<0){
n=?letters+n;
}
set l=letters[n];
(t::upper()==t)|=>l=l::lower()
res+=l;
}
send res;
}
 
func decode(text,shift:number=1){
set res:string="";
for(i=0;?text-1;1){
set t=text::at(i);
set n=(letters::find(t::upper())-shift)%?letters;
while(n<0){
n=?letters+n;
}
set l=letters[n];
(t::upper()==t)|=>l=l::lower()
res+=l;
}
send res;
}
 
set e=caesar("Hi",20);
set d=decode(e,20);
 
log(e);
log(d);</syntaxhighlight>
{{out}}
<pre>
Bc
Hi
</pre>
=={{header|XLISP}}==
<langsyntaxhighlight lang="lisp">(defun caesar-encode (text key)
(defun encode (ascii-code)
(defun rotate (character alphabet)
Line 3,875 ⟶ 7,656:
 
(defun caesar-decode (text key)
(caesar-encode text (- 26 key)))</langsyntaxhighlight>
Test it in a REPL:
<langsyntaxhighlight lang="lisp">[1] (define caesar-test (caesar-encode "CAESAR: Who is it in the press that calls on me? I hear a tongue, shriller than all the music, Cry 'Caesar!' Speak; Caesar is turn'd to hear." 14))
 
CAESAR-TEST
Line 3,885 ⟶ 7,666:
[3] (caesar-decode caesar-test 14)
 
"CAESAR: Who is it in the press that calls on me? I hear a tongue, shriller than all the music, Cry 'Caesar!' Speak; Caesar is turn'd to hear."</langsyntaxhighlight>
 
=={{header|XPL0}}==
To decrypt a message use the negative value of the encrypting key.
Usage: caesar key <infile.txt >outfile.xxx
 
<langsyntaxhighlight XPL0lang="xpl0">code ChIn=7, ChOut=8, IntIn=10;
int Key, C;
[Key:= IntIn(8);
Line 3,903 ⟶ 7,683:
ChOut(0, C);
until C=$1A; \EOF
]</langsyntaxhighlight>
 
Example outfile.xxx:
Line 3,909 ⟶ 7,689:
SDFN PB ERA ZLWK ILYH GRCHQ OLTXRU MXJV.
</pre>
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
REM *** By changing the key and pattern, an encryption system that is difficult to break can be achieved. ***
 
text$ = "You are encouraged to solve this task according to the task description, using any language you may know."
=={{header|zkl}}==
key$ = "desoxirribonucleic acid" // With a single character you get a Caesar encryption. With more characters the key is much more difficult to discover.
<lang zkl>var [const] letters=
CIPHER = 1 : DECIPHER = -1
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
 
print text$ : print
fcn caesarCodec(str,n,encode=True){
encrypted$ = criptex$(text$, key$, CIPHER)
if(not encode) n=26-n;
a = open("cryptedText.txt", "w") : if a then print #a encrypted$ : close #a end if
m:=n+26; sz:=26-n;
print encrypted$ : print
print criptex$(encrypted$, key$, DECIPHER)
 
sub criptex$(text$, key$, mode)
local i, k, delta, longtext, longPattern, longkey, pattern$, res$
pattern$ = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 .,;:()-"
longPattern = len(pattern$)
longtext = len(text$)
longkey = len(key$)
for i = 1 to longtext
k = k + 1 : if k > longkey k = 1
delta = instr(pattern$, mid$(text$, i, 1))
delta = delta + (mode * instr(pattern$, mid$(key$, k, 1)))
if delta > longPattern then
delta = delta - longPattern
elseif delta < 1 then
delta = longPattern + delta
end if
res$ = res$ + mid$(pattern$, delta, 1)
next i
 
return res$
end sub</syntaxhighlight>
{{out}}
<pre>You are encouraged to solve this task according to the task description, using any language you may know.
 
3tNhyAwknprCPumlng4urbwsqOtqCzAB,IoNneflfhsgrrk(MDqCzwbvpGF;pjBfkjsCmssnhSBAFp,pBT;xfwjnbjn:CtNhKjQktpDKo
 
You are encouraged to solve this task according to the task description, using any language you may know.</pre>
=={{header|Zig}}==
<syntaxhighlight lang="zig">
const std = @import("std");
const stdout = @import("std").io.getStdOut().writer();
 
pub fn rot(txt: []u8, key: u8) void {
for (txt, 0..txt.len) |c, i| {
if (std.ascii.isLower(c)) {
txt[i] = (c - 'a' + key) % 26 + 'a';
} else if (std.ascii.isUpper(c)) {
txt[i] = (c - 'A' + key) % 26 + 'A';
}
}
}
 
pub fn main() !void {
const key = 3;
var txt = "The five boxing wizards jump quickly".*;
 
try stdout.print("Original: {s}\n", .{txt});
rot(&txt, key);
try stdout.print("Encrypted: {s}\n", .{txt});
rot(&txt, 26 - key);
try stdout.print("Decrypted: {s}\n", .{txt});
}
</syntaxhighlight>
{{out}}
<pre>
Original: The five boxing wizards jump quickly
Encrypted: Wkh ilyh eralqj zlcdugv mxps txlfnob
Decrypted: The five boxing wizards jump quickly
</pre>
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">fcn caesarCodec(str,n,encode=True){
var [const] letters=["a".."z"].chain(["A".."Z"]).pump(String); // static
if(not encode) n=26 - n;
m,sz := n + 26, 26 - n;
ltrs:=String(letters[n,sz],letters[0,n],letters[m,sz],letters[26,n]);
str.translate(letters,ltrs)
str.apply('wrap(c){ try{ ltrs[letters.index(c)] } catch{ c } });
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">text:="The five boxing wizards jump quickly";
N:=3;
code:=caesarCodec(text,N);
println("text = ",text);
println("encoded(%d) = %s".fmt(N,code));
println("decoded = ",caesarCodec(code,N,False));</langsyntaxhighlight>
{{out}}
<pre>
Line 3,933 ⟶ 7,786:
</pre>
 
=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
module Caesar;
const
size = 25;
 
type
Operation = (code,decode);
 
procedure C_D(s:string;k:integer;op: Operation): string;
var
i,key: integer;
resp: string;
n,c: char;
begin
resp := "";
if op = Operation.decode then key := k else key := (26 - k) end;
for i := 0 to len(s) - 1 do
c := cap(s[i]);
if (c >= 'A') & (c <= 'Z') then
resp := resp +
string(char(integer('A') + ((integer(c) - integer('A') + key )) mod 26));
else
resp := resp + string(c)
end;
end;
return resp
end C_D;
 
procedure {public} Cipher(s:string;k:integer):string;
var
i: integer;
resp: string;
n,c: char;
begin
return C_D(s,k,Operation.code)
end Cipher;
 
procedure {public} Decipher(s:string;k:integer):string;
var
i: integer;
resp: string;
n,c: char;
begin
return C_D(s,k,Operation.decode)
end Decipher;
 
var
txt,cipher,decipher: string;
 
begin
txt := "HI";cipher := Caesar.Cipher(txt,2);decipher := Caesar.Decipher(cipher,2);
writeln(txt," -c-> ",cipher," -d-> ",decipher);
txt := "ZA";cipher := Caesar.Cipher(txt,2);decipher := Caesar.Decipher(cipher,2);
writeln(txt," -c-> ",cipher," -d-> ",decipher);
txt := "The five boxing wizards jump quickly";
cipher := Caesar.Cipher(txt,2);decipher := Caesar.Decipher(cipher,2);
writeln(txt," -c-> ",cipher," -d-> ",decipher)
end Caesar.
</syntaxhighlight>
{{Out}}
<pre>
HI -c-> FG -d-> HI
ZA -c-> XY -d-> ZA
The five boxing wizards jump quickly -c-> RFC DGTC ZMVGLE UGXYPBQ HSKN OSGAIJW -d-> THE FIVE BOXING WIZARDS JUMP QUICKLY
</pre>
=={{header|ZX Spectrum Basic}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="zxbasic">10 LET t$="PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS"
20 PRINT t$''
30 LET key=RND*25+1
Line 3,948 ⟶ 7,867:
1050 NEXT i
1060 RETURN
</syntaxhighlight>
</lang>
{{trans|Yabasic}}
<syntaxhighlight lang="zxbasic">10 LET t$="Wonderful ZX Spectrum."
20 LET c$="a":REM more characters, more difficult for decript
30 LET CIFRA=1: LET DESCIFRA=-1
40 PRINT t$''
50 LET modo=CIFRA: GO SUB 1000
60 PRINT r$''
70 LET t$=r$: LET modo=DESCIFRA: GO SUB 1000
80 PRINT r$''
90 STOP
1000 REM Criptex
1010 LET p$="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 .,;:()-"
1020 LET longPatron=LEN p$
1030 LET longTexto=LEN t$
1040 LET longClave=LEN c$
1045 LET k=0: LET r$=""
1050 FOR i=1 TO longTexto
1060 LET k=k+1: IF k>longClave THEN LET k=1
1070 LET x$=t$(i)
1080 FOR j=1 TO longPatron
1090 IF x$=p$(j) THEN LET delta=j: GO TO 1110
1100 NEXT j
1110 LET x$=c$(k)
1120 FOR j=1 TO longPatron
1130 IF x$=p$(j) THEN LET delta=delta+modo*j: GO TO 1150
1140 NEXT j
1150 IF delta>longPatron THEN LET delta=delta-longPatron: GO TO 1170
1160 IF delta<1 THEN LET delta=longPatron+delta
1170 LET r$=r$+p$(delta)
1180 NEXT i
1190 RETURN </syntaxhighlight>
{{omit from|GUISS}}
890

edits