Caesar cipher: Difference between revisions

24,297 bytes added ,  16 days ago
 
(36 intermediate revisions by 24 users not shown)
Line 1:
{{task|Encryption}}
[[Category:String manipulation]]
{{task|Encryption}}
 
 
Line 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}}==
<langsyntaxhighlight lang="11l">F caesar(string, =key, decode = 0B)
I decode
key = 26 - key
Line 44 ⟶ 73:
V enc = caesar(msg, 11)
print(enc)
print(caesar(enc, 11, decode' 1B))</langsyntaxhighlight>
{{out}}
<pre>
Line 51 ⟶ 80:
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.
<langsyntaxhighlight lang="360asm">* Caesar cypher 04/01/2019
CAESARO PROLOG
XPRNT PHRASE,L'PHRASE print phrase
Line 83 ⟶ 111:
ORG
YREGS
END CAESARO</langsyntaxhighlight>
{{out}}
<pre>
Line 90 ⟶ 118:
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"
=={{header|8th}}==
/************************************/
<lang forth>\ Ensure the output char is in the correct range:
/* UnInitialized data */
: modulate \ char base -- char
/************************************/
tuck n:- 26 n:+ 26 n:mod n:+ ;
.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:
\ Symmetric Caesar cipher. Input is text and number of characters to advance
ldp x4,x5,[sp],16 // restaur registers
\ (or retreat, if negative). That value should be in the range 1..26
ldp x3,lr,[sp],16 // restaur registers
: caesar \ intext key -- outext
>r ret
/******************************************************************/
(
/* decrypt strings */
\ Ignore anything below '.' as punctuation:
/******************************************************************/
dup '. n:> if
/* x0 contains the address of the encrypted string1 */
\ Do the conversion
/* x1 contains the address of the decrypted string */
dup r@ n:+ swap
/* x2 contains the key (1-25) */
\ Wrap appropriately
decrypt:
'A 'Z between if 'A else 'a then modulate
stp x3,lr,[sp,-16]! // save registers
then
stp x4,x5,[sp,-16]! // save registers
) s:map rdrop ;
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:
"The five boxing wizards jump quickly!"
ldp x4,x5,[sp],16 // restaur registers
dup . cr
ldp x3,lr,[sp],16 // restaur registers
1 caesar dup . cr
ret
-1 caesar . cr
/***************************************************/
bye</lang>
/* ROUTINES INCLUDE */
{{out}}
/***************************************************/
.include "../includeARM64.inc"
 
</syntaxhighlight>
{{Out}}
<pre>
String :
The five boxing wizards jump quickly!
The quick brown fox jumps over the lazy dog.
Uif gjwf cpyjoh xjabset kvnq rvjdlmz!
Encrypted :
The five boxing wizards jump quickly!
Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald.
Decrypted :
The quick brown fox jumps over the lazy dog.
</pre>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">CHAR FUNC Shift(CHAR c BYTE code)
CHAR base
 
Line 165 ⟶ 364:
Test("The quick brown fox jumps over the lazy dog.",23)
Test("The quick brown fox jumps over the lazy dog.",5)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Caesar_cipher.png Screenshot from Atari 8-bit computer]
Line 183 ⟶ 382:
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
 
-- Base function to encrypt a character
type modulo26 is modulo 26;
function Cipher(Char_To_Encrypt: Character; Shift: Integer; Base: Character) return Character is
 
function modulo26 (Character Base_Pos : Character;constant Natural Output:= Character'Pos(Base) return modulo26 is;
begin
return modulo26 (Character'PosVal((Character)+Character'Pos(OutputChar_To_Encrypt) + Shift - Base_Pos) mod 26 + Base_Pos);
end modulo26Cipher;
 
-- Function to encrypt a character
function Character(Val: in modulo26; Output: Character)
function Encrypt_Char(Char_To_Encrypt: Character; Shift: Integer) return Character is
begin
case Char_To_Encrypt is
return Character'Val(Integer(Val)+Character'Pos(Output));
when 'A'..'Z' =>
end Character;
-- Encrypt uppercase letters
 
return Cipher (Char_To_Encrypt, Shift, 'A');
function crypt (Playn: String; Key: modulo26) return String is
Ciph: String(Playn 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 Playn'Range loop
end Decrypt_Char;
case Playn(I) is
when 'A' .. 'Z' =>
Ciph(I) := Character(modulo26(Playn(I)+Key), 'A');
when 'a' .. 'z' =>
Ciph(I) := Character(modulo26(Playn(I)+Key), 'a');
when others =>
Ciph(I) := Playn(I);
end case;
end loop;
return Ciph;
end crypt;
 
TextMessage: constant String := Ada.Text_IO.Get_Line;
KeyShift: modulo26Positive := 3; -- Default key from "Commentarii de Bello Gallico" shift cipher
-- Shift value (can be any positive integer)
 
Encrypted_Message: String(Message'Range);
begin -- encryption 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("Playn ------------>" & Text);
for I in Message'Range loop
Text := crypt(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 ->" & crypt(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 242 ⟶ 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 284 ⟶ 497:
printf(($gl$, "Decrypted Ciphertext ->" + encrypt(text, -key)))
 
END #caesar#</langsyntaxhighlight>
{{out}}
<pre>
Line 291 ⟶ 504:
Decrypted Ciphertext ->The five boxing wizards jump quickly
</pre>
 
=={{header|APL}}==
<langsyntaxhighlight lang="apl">
∇CAESAR[⎕]∇
Line 301 ⟶ 513:
[3] A←V
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 322 ⟶ 534:
Esl dyar: dpyargmlyj icwq qugraf dpmk TOODQ BZRD rm jmucp ayqc.
</pre>
 
=={{header|AppleScript}}==
 
<langsyntaxhighlight lang="applescript">(* Only non-accented English letters are altered here. *)
 
on caesarDecipher(txt, |key|)
Line 351 ⟶ 562:
set enciphered to caesarEncipher(txt, |key|)
set deciphered to caesarDecipher(enciphered, |key|)
return "Text: '" & txt & ("'" & linefeed & "Key: " & |key| & linefeed & linefeed) & (enciphered & linefeed & deciphered)</langsyntaxhighlight>
 
{{output}}
 
<langsyntaxhighlight lang="applescript">"Text: 'ROMANES EUNT DOMUS!
The quick brown fox jumps over the lazy dog.'
Key: 9
Line 362 ⟶ 573:
Cqn zdrlt kaxfw oxg sdvyb xena cqn ujih mxp.
ROMANES EUNT DOMUS!
The quick brown fox jumps over the lazy dog."</langsyntaxhighlight>
 
=={{header|Applesoft BASIC}}==
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">100 INPUT ""; T$
 
110 LET K% = RND(1) * 25 + 1
Line 406 ⟶ 616:
460 IF C > 90 THEN C = C - 26
470 LET C$ = CHR$(C + L)
480 RETURN</langsyntaxhighlight>
{{out}}
<pre>]RUN
Line 428 ⟶ 638:
DECODED WITH CAESAR 25
PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS</pre>
 
=={{header|Arc}}==
<syntaxhighlight lang="arc">
<lang Arc>
(= rot (fn (L N)
(if
Line 451 ⟶ 660:
(string output)
))
</syntaxhighlight>
</lang>
 
{{Out}}
<langsyntaxhighlight lang="arc">
(caesar "The quick brown fox jumps over the lazy dog.")
"Gur dhvpx oebja sbk whzcf bire gur ynml qbt."
</syntaxhighlight>
</lang>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program caresarcode.s */
Line 521 ⟶ 729:
iAdrszString1: .int szString1
iAdrszString2: .int szString2
iAdrszString3: .int szString2szString3
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
Line 635 ⟶ 843:
bx lr @ return
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
{{trans|11l}}
<langsyntaxhighlight lang="rebol">ia: to :integer `a`
iA: to :integer `A`
lowAZ: `a`..`z`
Line 661 ⟶ 868:
enc: caesar msg 11
print [" Encoded :" enc]
print [" Decoded :" caesar.decode enc 11]</langsyntaxhighlight>
 
{{out}}
Line 668 ⟶ 875:
Encoded : Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozrd
Decoded : The quick brown fox jumped over the lazy dogs</pre>
 
=={{header|Astro}}==
<langsyntaxhighlight lang="python">fun caesar(s, k, decode: false):
if decode:
k = 26 - k
Line 682 ⟶ 888:
let decrypted = caesar(enc, 11, decode: true)
 
print(message, encrypted, decrypted, sep: '\n')</langsyntaxhighlight>
 
=={{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 705 ⟶ 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 745 ⟶ 949:
Return $sLetters
EndFunc ;==>Caesar
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">
#!/usr/bin/awk -f
 
Line 791 ⟶ 994:
return s
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 799 ⟶ 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 853 ⟶ 1,055:
<- 0x60 cugt ->
0x7b cult
cand }))</langsyntaxhighlight>
 
{{out}}
Line 859 ⟶ 1,061:
Kyv hlztb sifne wfo aldgj fmvi kyv crqp ufx.
The quick brown fox jumps over the lazy dog.</pre>
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="qbasic">CONST lc$ = "abcdefghijklmnopqrstuvwxyz"
CONST uc$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
Line 881 ⟶ 1,082:
 
PRINT "Encrypted: ", en$
PRINT "Decrypted: ", Ceasar$(en$, 26-tokey)</langsyntaxhighlight>
{{out}}
<pre>
Line 894 ⟶ 1,095:
Decrypted: The quick brown fox jumps over the lazy dog.
</pre>
 
=={{header|bash}}==
Caesar cipher bash implementation
{{works with|GNU bash, version 4}}
 
<langsyntaxhighlight lang="bash">
caesar_cipher() {
 
Line 941 ⟶ 1,141:
}
 
</syntaxhighlight>
</lang>
{{in}}
 
<pre>
{{out}} (input: caesar_cipher -e 13 "Hello World!"):
caesar_cipher -e 13 "Hello World!"
</pre>
{{out}}
<pre>
Uryyb Jbeyq!
</pre>
 
{{in}}
{{out}} (input: caesar_cipher -d 13 "Uryyb Jbeyq!"):
<pre>
caesar_cipher -d 13 "Uryyb Jbeyq!"
</pre>
{{out}}
<pre>
Hello World!
</pre>
 
=={{header|BASIC256BASIC}}==
==={{header|BASIC256}}===
<lang>
<syntaxhighlight lang="text">
# Caeser Cipher
# basic256 1.1.4.0
Line 985 ⟶ 1,193:
next i
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 997 ⟶ 1,205:
</pre>
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> plaintext$ = "Pack my box with five dozen liquor jugs"
PRINT plaintext$
Line 1,020 ⟶ 1,228:
NEXT
= text$
</syntaxhighlight>
</lang>
{{out}}
<pre>Pack my box with five dozen liquor jugs
Zkmu wi lyh gsdr psfo nyjox vsaeyb teqc
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}}==
<langsyntaxhighlight Beadslang="beads">beads 1 program 'Caesar cipher'
calc main_init
var str = "The five boxing wizards (🤖) jump quickly."
Line 1,059 ⟶ 1,337:
) : str
// we could also just shift by 26-nshift, same as going in reverse
return Encrypt(input, -nshift)</langsyntaxhighlight>
{{out}}
<pre>Plain: The five boxing wizards (🤖) jump quickly.
Line 1,065 ⟶ 1,343:
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 1,071 ⟶ 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 1,081 ⟶ 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}}==
<langsyntaxhighlight lang="bqn">o ← @‿'A'‿@‿'a'‿@ ⋄ m ← 5⥊↕2 ⋄ p ← m⊏∞‿26
Rot ← {i←⊑"A[a{"⍋𝕩 ⋄ i⊑o+p|(𝕨×m)+𝕩-o}⎉0</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang="bqn">3 Rot "We're no strangers to love // You know the rules and so do I"</langsyntaxhighlight>
<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***}}==
<langsyntaxhighlight lang="bf"> Author: Ettore Forigo | Hexwell
 
+ start the key input loop
Line 1,317 ⟶ 1,592:
^
<< :c ^
]</langsyntaxhighlight>
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 </langsyntaxhighlight>
Output:
<pre>klm</pre>
Input:
<syntaxhighlight lang ="whitespace">16 klm </langsyntaxhighlight>
Output:
<pre>abc</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 1,382 ⟶ 1,656:
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 1,424 ⟶ 1,697:
}
}
}</langsyntaxhighlight>
{{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 1,475 ⟶ 1,747:
std::cout << input << std::endl ;
return 0 ;
}</langsyntaxhighlight>
{{out}}
<pre>Which text is to be encrypted ?
Line 1,494 ⟶ 1,766:
===={{works with|C++-11}}====
 
<langsyntaxhighlight Cpplang="cpp">/* caesar cipher */
 
#include <string>
Line 1,548 ⟶ 1,820:
return 0 ;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,560 ⟶ 1,832:
Decrypted: This is a line of plain text, 50 characters long.
</pre>
 
=={{header|Clojure}}==
Readable version:
<langsyntaxhighlight Clojurelang="clojure">(defn encrypt-character [offset c]
(if (Character/isLetter c)
(let [v (int c)
Line 1,585 ⟶ 1,856:
(print "Original text:" text "\n")
(print "Encryption:" enc "\n")
(print "Decryption:" (decrypt -1 enc) "\n"))</langsyntaxhighlight>
 
output:
Line 1,594 ⟶ 1,865:
 
Terser version using replace:
<langsyntaxhighlight Clojurelang="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 %)))]
Line 1,600 ⟶ 1,871:
 
(defn decode [k s]
(encode (- 26 k) s))</langsyntaxhighlight>
 
output:<pre>
Line 1,607 ⟶ 1,878:
(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
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
<lang COBOL>
identificationPROGRAM-ID. divisionCAESAR.
 
program-id. caesar.
dataDATA divisionDIVISION.
1WORKING-STORAGE msg pic x(50)SECTION.
01 MSG value "The quick brown fox jumped overPIC the lazy dog.".X(50)
VALUE "The quick brown fox jumped over the lazy dog.".
1 offset binary pic 9(4) value 7.
101 from-chars picOFFSET x PIC 9(524) VALUE 7 USAGE BINARY.
101 to FROM-charsCHARS picPIC xX(52).
101 tabl TO-CHARS PIC X(52).
01 TABL.
2 pic x(26) value "abcdefghijklmnopqrstuvwxyz".
2 pic x 02 PIC X(26) valueVALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".
2 pic x 02 PIC X(26) valueVALUE "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".
2 pic x 02 PIC X(26) valueVALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".
02 PIC X(26) VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
procedure division.
 
begin.
PROCEDURE display msgDIVISION.
perform encryptBEGIN.
displayDISPLAY msgMSG
performPERFORM decryptENCRYPT
displayDISPLAY msgMSG
stopPERFORM runDECRYPT
.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.
 
encryptDECRYPT.
moveMOVE tablTABL (1 + OFFSET:52) toTO fromFROM-charsCHARS
moveMOVE tablTABL (1 + offset:52) toTO toTO-charsCHARS
inspectINSPECT msgMSG convertingCONVERTING fromFROM-charsCHARS TO TO-CHARS.
to to-chars
.
 
END PROGRAM CAESAR.</syntaxhighlight>
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.
</lang>
{{out}}
<pre>
Line 1,657 ⟶ 1,938:
</pre>
 
{{works with|OpenCOBOL|2.0COBOL 2002}}
<langsyntaxhighlight cobollang="cobolfree"> >>SOURCE FORMAT IS FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. caesar-cipher.
 
Line 1,665 ⟶ 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.
 
END FUNCTION encrypt.
 
IDENTIFICATION DIVISION.
FUNCTION-ID. decrypt.
 
Line 1,727 ⟶ 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 1,754 ⟶ 2,033:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">cipher = (msg, rot) ->
msg.replace /([a-z|A-Z])/g, ($1) ->
c = $1.charCodeAt(0)
Line 1,763 ⟶ 2,042:
console.log cipher "Hello World", 2
console.log cipher "azAz %^&*()", 3</langsyntaxhighlight>
{{out}}
<pre>
Line 1,770 ⟶ 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.
 
<langsyntaxhighlight lang="gwbasic">1 rem caesar cipher
2 rem rosetta code
10 print chr$(147);chr$(14);
Line 1,821 ⟶ 2,099:
3035 cm$=cm$+mid$(ec$,c,1)
3040 next i
3050 return</langsyntaxhighlight>
 
{{Output}}
Line 1,847 ⟶ 2,125:
&#9608;
</pre>
 
=={{header|Common Lisp}}==
====Main version====
<langsyntaxhighlight 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 1,868 ⟶ 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>
<langsyntaxhighlight lang="lisp">
(defun caesar-encipher (s k)
(map 'string #'(lambda (c) (z c k)) s))
Line 1,883 ⟶ 2,160:
(when (<= 65 c 90) 65))))
(if b (code-char (+ (mod (+ (- c b) k) 26) b)) h))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,892 ⟶ 2,169:
 
====Alternate version====
1. NoteProgram
<pre>if caesar(txt offset) = cyphertext then caesar(cyphertext -offset) = txt</pre>
 
<syntaxhighlight lang="lisp">(defconstant +a+ "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz")
2. Program
 
<lang lisp>(defconstant +a+ "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz")
(defun caesar (txt offset)
(map 'string
#'(lambda (xc)
(if (find xc +a+)
(char +a+ (mod (+ (position xc +a+) (* 2 offset)) 52))
xc))
txt))</langsyntaxhighlight>
 
32. Execution
 
See 1.
 
{{out}}
Line 1,916 ⟶ 2,188:
(caesar "Nir Pnrfne zbevghev gr fnyhgnag" -13)
Ave Caesar morituri te salutant</pre>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="crystal">class String
ALPHABET = ("A".."Z").to_a
 
Line 1,929 ⟶ 2,200:
encrypted = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG".caesar_cipher(5)
decrypted = encrypted.caesar_cipher(-5)
</syntaxhighlight>
</lang>
 
=={{header|Cubescript}}==
<langsyntaxhighlight lang="cubescript">alias modn [ mod (+ (mod $arg1 $arg2) $arg2) $arg2 ]
//Cubescript's built-in mod will fail on negative numbers
 
Line 1,989 ⟶ 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 2,019 ⟶ 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 2,025 ⟶ 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 2,044 ⟶ 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 2,063 ⟶ 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 2,129 ⟶ 2,397:
trip(".-:/\"\\!");
trip("The Quick Brown Fox Jumps Over The Lazy Dog.");
}</langsyntaxhighlight>
{{out}}
<pre>JK
Line 2,151 ⟶ 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#}}
 
<langsyntaxhighlight lang="dyalect">func Char.Encrypt(code) {
if !this.IsLetter() {
return this
Line 2,184 ⟶ 2,450:
print("Encrypted: \(str)")
str = str.Decrypt(5)
print("Decrypted: \(str)")</langsyntaxhighlight>
 
{{out}}
Line 2,191 ⟶ 2,457:
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}}==
Line 2,205 ⟶ 2,489:
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).
<langsyntaxhighlight lang="edsac">
[Caesar cipher for Rosetta Code.
EDSAC program, Initial Orders 2.]
Line 2,421 ⟶ 2,705:
P F [acc = 0 on entry]
DGAZA!FREQUENS!LIBYCUM!DUXIT!KARTHAGO!TRIUMPHUM.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,436 ⟶ 2,720:
 
=={{header|Eiffel}}==
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 2,490 ⟶ 2,774:
end
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,497 ⟶ 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 2,527 ⟶ 2,810:
putStrLn ""
putStr "Decoded string: "
put $ decypher key cstr</langsyntaxhighlight>
 
{{out}}
Line 2,535 ⟶ 2,818:
Encoded string: "JGOOQ! VJKU KU C UGETGV PGUUCIG!"
Decoded string: "HELLO! THIS IS A SECRET MESSAGE!"</pre>
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import system'routines;
import system'math;
import extensions;
Line 2,550 ⟶ 2,832:
class Encrypting : Enumerator
{
int theKey_key;
Enumerator theEnumerator_enumerator;
constructor(int key, string text)
{
theKey_key := key;
theEnumerator_enumerator := text.enumerator();
}
bool next() => theEnumerator_enumerator;
reset() => theEnumerator_enumerator;
enumerable() => theEnumerator_enumerator;
get Value()
{
var ch := theEnumerator.get()*_enumerator;
var index := Letters.indexOf(0, ch);
Line 2,573 ⟶ 2,855:
if (-1 < index)
{
^ Letters[(theKey_key+index).mod:(26)]
}
else
Line 2,580 ⟶ 2,862:
if (-1 < index)
{
^ BigLetters[(theKey_key+index).mod:(26)]
}
else
Line 2,603 ⟶ 2,885:
console.printLine("Original text :",TestText);
var encryptedText := TestText.encrypt:(Key);
 
console.printLine("Encrypted text:",encryptedText);
 
var decryptedText := encryptedText.decrypt:(Key);
 
console.printLine("Decrypted text:",decryptedText);
 
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,621 ⟶ 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 2,638 ⟶ 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 2,646 ⟶ 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 2,683 ⟶ 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 2,691 ⟶ 3,076:
"The five boxing wizards jump quickly"
</pre>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM CAESAR
 
Line 2,723 ⟶ 3,107:
 
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,730 ⟶ 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 2,789 ⟶ 3,172:
printf(1,"%s\n",{text})
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,796 ⟶ 3,179:
"The Quick Brown Fox Jumps Over The Lazy Dog."
</pre>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">module caesar =
open System
 
Line 2,810 ⟶ 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 2,820 ⟶ 3,202:
val it : string = "The quick brown fox jumps over the lazy dog."
</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.97}}
{{trans|F#}}
<langsyntaxhighlight lang="factor">USING: io kernel locals math sequences unicode.categories ;
IN: rosetta-code.caesar-cipher
 
Line 2,841 ⟶ 3,222:
 
11 "Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr." decrypt print
11 "The quick brown fox jumped over the lazy dog." encrypt print</langsyntaxhighlight>
{{out}}
<pre>
Line 2,847 ⟶ 3,228:
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 2,905 ⟶ 3,285:
}
}
</syntaxhighlight>
</lang>
 
Example:
Line 2,924 ⟶ 3,304:
Decode: Encrypt - With ! Case,
</pre>
 
=={{header|Fhidwfe}}==
only encodes letters
<syntaxhighlight lang="fhidwfe">
<lang Fhidwfe>
lowers = ['a','z']
uppers = ['A','Z']
Line 2,970 ⟶ 3,349:
 
//this compiles with only 6 warnings!
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: ceasarcaesar ( c n -- c )
over 32 or [char] a -
dup 0 26 within if
Line 2,979 ⟶ 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 3,037 ⟶ 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}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub Encrypt(s As String, key As Integer)
Line 3,084 ⟶ 3,461:
Decrypt s, 8
Print "Decrypted : "; s
Sleep</langsyntaxhighlight>
 
{{out}}
Line 3,092 ⟶ 3,469:
Decrypted : Bright vixens jump; dozy fowl quack.
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=cb96008082bc0d8278224cd2a5ec74d3 Click this link to run this code]'''
<langsyntaxhighlight 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
Line 3,114 ⟶ 3,490:
Print sString & gb.NewLine & sCoded 'Print the result
 
End</langsyntaxhighlight>
Output:
<pre>
Line 3,120 ⟶ 3,496:
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 3,147 ⟶ 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 3,187 ⟶ 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 3,249 ⟶ 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 3,307 ⟶ 3,680:
fmt.Println(" Deciphered:", ck.decipher(ct))
}
}</langsyntaxhighlight>
{{out}} (either version)
<pre>
Line 3,323 ⟶ 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 3,338 ⟶ 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 3,347 ⟶ 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 3,378 ⟶ 3,750:
assert plainText == decodedText
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,384 ⟶ 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 3,402 ⟶ 3,773:
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c
</syntaxhighlight>
</lang>
 
And trying it out in GHCi:
Line 3,414 ⟶ 3,785:
Similarly, but allowing for negative cipher keys, and using isAlpha, isUpper, negate:
 
<langsyntaxhighlight lang="haskell">import Data.Bool (bool)
import Data.Char (chr, isAlpha, isUpper, ord)
 
Line 3,437 ⟶ 3,808:
cipher = caesar k
plain = "Curio, Cesare venne, e vide e vinse ? "
mapM_ putStrLn $ [cipher, uncaesar k . cipher] <*> [plain]</langsyntaxhighlight>
{{Out}}
<pre>Skhye, Suiqhu luddu, u lytu u lydiu ?
Line 3,443 ⟶ 3,814:
 
Or with proper error handling:
<langsyntaxhighlight lang="haskell">{-# LANGUAGE LambdaCase #-}
module Main where
 
Line 3,474 ⟶ 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}}==
<langsyntaxhighlight Hoonlang="hoon">|%
++ enc
|= [msg=tape key=@ud]
Line 3,485 ⟶ 3,855:
|= [msg=tape key=@ud]
(enc msg (sub 26 key))
--</langsyntaxhighlight>
 
=={{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 3,504 ⟶ 3,873:
"d"|"decrypt" : return map(text,(&lcase||&lcase)[k+:*&lcase],&lcase)
}
end</langsyntaxhighlight>
 
{{out}}
Line 3,510 ⟶ 3,879:
Encphered text = "wkh txlfn eurzq ira mxpshg ryhu wkh odcb grj"
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}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "CaesarCi.bas"
110 STRING M$*254
120 INPUT PROMPT "String: ":M$
Line 3,552 ⟶ 3,946:
480 NEXT
490 LET M$=T$
500 END DEF</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="janet">
(def alphabet "abcdefghijklmnopqrstuvwxyz")
 
Line 3,595 ⟶ 3,987:
(print cipher)
(print str)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,604 ⟶ 3,996:
"thequickbrownfoxjumpsoverthelazydog"
</pre>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">public class Cipher {
public static void main(String[] args) {
 
Line 3,636 ⟶ 4,027:
return encoded.toString();
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,642 ⟶ 4,033:
The quick brown fox Jumped over the lazy Dog
</pre>
 
=={{header|JavaScript}}==
 
===ES5===
 
<langsyntaxhighlight lang="javascript">function caesar (text, shift) {
return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/./g, function(a) {
return String.fromCharCode(65+((a.charCodeAt(0) - 65 + shift) % 26 + 26) % 26 + 65);
});
}
Line 3,657 ⟶ 4,047:
for (var i = 0; i<26; i++) {
console.log(i+': '+caesar(text,i));
}</langsyntaxhighlight>
 
{{output}}
Line 3,670 ⟶ 4,060:
===ES6===
 
<langsyntaxhighlight lang="javascript">var caesar = (text, shift) => text
.toUpperCase()
.replace(/[^A-Z]/g, '')
.replace(/./g, a =>
String.fromCharCode(65 + ((a.charCodeAt(0) - 65 + shift) % 26 + 26) % 26 + 65));</langsyntaxhighlight>
 
 
Or, allowing encoding and decoding of both lower and upper case:
 
<langsyntaxhighlight JavaScriptlang="javascript">((key, strPlain) => {
 
// Int -> String -> String
Line 3,721 ⟶ 4,111:
return [strCipher, ' -> ', strDecode];
 
})(114, 'Curio, Cesare venne, e vide e vinse ? ');</langsyntaxhighlight>
 
{{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'''
<langsyntaxhighlight lang="jq">def encrypt(key):
. as $s
| explode as $xs
Line 3,760 ⟶ 4,149:
(encrypt(8)
| ., decrypt(8) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,767 ⟶ 4,156:
Bright vixens jump; dozy fowl quack.
</pre>
 
 
=={{header|Jsish}}==
From Typescript entry.
<langsyntaxhighlight lang="javascript">/* Caesar cipher, in Jsish */
"use strict";
 
Line 3,803 ⟶ 4,190:
caesarCipher(caesarCipher(str, 3), -3) ==> The five boxing wizards jump quickly
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{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===
 
<langsyntaxhighlight lang="julia">
# Caeser cipher
# Julia 1.5.4
Line 3,845 ⟶ 4,231:
text = "Magic Encryption"; key = 13
csrcipher(text, key)
</syntaxhighlight>
</lang>
{{out}}
<pre>
"Zntvp Rapelcgvba"
</pre>
 
=={{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}}==
<langsyntaxhighlight lang="scala">// version 1.0.5-2
 
object Caesar {
Line 3,897 ⟶ 4,314:
val decoded = Caesar.decrypt(encoded, 8)
println(decoded)
}</langsyntaxhighlight>
 
{{out}}
Line 3,907 ⟶ 4,324:
=={{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].
<langsyntaxhighlight lang="scheme">
{def caesar
 
Line 3,980 ⟶ 4,396:
-> VENIVIDIVICI
 
</syntaxhighlight>
</lang>
 
=={{header|langur}}==
Using the built-in rotate() function on a number over a range, a number outside of the range will pass through unaltered.
 
<langsyntaxhighlight lang="langur">val .rot = ffn(.s, .key) {
cp2s map(ffn(.c) { rotate(rotate(.c, .key, 'a'..'z'), .key, 'A'..'Z') }, s2cp .s)
}
 
 
val .s = "A quick brown fox jumped over something."
Line 3,994 ⟶ 4,410:
writeln " original: ", .s
writeln "encrypted: ", .rot(.s, .key)
writeln "decrypted: ", .rot(.rot(.s, .key), -.key)</langsyntaxhighlight>
 
{{out}}
Line 4,002 ⟶ 4,418:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">key = 7
 
Print "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 4,025 ⟶ 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 4,043 ⟶ 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 4,081 ⟶ 4,495:
print sentence "|Encrypted:| :ciphertext
print sentence "|Recovered:| :recovered
bye</langsyntaxhighlight>
 
{{out}}
Line 4,087 ⟶ 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 4,120 ⟶ 4,533:
print("Decrypted text: ", decrypted)
end
</syntaxhighlight>
</lang>
 
 
'''Fast version'''
<langsyntaxhighlight Lualang="lua">local memo = {}
 
local function make_table(k)
Line 4,155 ⟶ 4,568:
end
return string.char(unpack(res_t))
end</langsyntaxhighlight>
 
=={{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">
<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$)
N=N mod 25 +1
\\ 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)-6539+Nn) mod 26 + 65
}
=Eval$(Mem)
}
B$=Cipher$(a$, 1210)
Print B$
Print Cipher$(B$,12-10)
 
n=1 ' n negative or positive or zero
</lang>
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 4,187 ⟶ 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">
<lang Microsoft Small Basic>
TextWindow.Write("Enter a 1-25 number key (-ve number to decode): ")
key = TextWindow.ReadNumber()
Line 4,232 ⟶ 4,646:
TextWindow.WriteLine(message)
TextWindow.WriteLine(caeser)
</syntaxhighlight>
</lang>
{{out}}
<pre>Enter a 1-25 number key (-ve number to decode): 10
Line 4,246 ⟶ 4,660:
Press any key to continue...
</pre>
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">caesar = function(s, key)
chars = s.values
for i in chars.indexes
Line 4,259 ⟶ 4,672:
 
print caesar("Hello world!", 7)
print caesar("Olssv dvysk!", 26-7)</langsyntaxhighlight>
 
{{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 4,308 ⟶ 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}}
<langsyntaxhighlight lang="modula2">MODULE CaesarCipher;
FROM Conversions IMPORT IntToStr;
FROM Terminal IMPORT WriteString, WriteLn, ReadChar;
Line 4,392 ⟶ 4,803:
 
ReadChar;
END CaesarCipher.</langsyntaxhighlight>
 
=={{header|Modula-3}}==
This implementation distinguishes between "encoding" and "encryption."
Line 4,401 ⟶ 4,811:
It also illustrates the use of exceptions in Modula-3.
 
<langsyntaxhighlight lang="modula3">MODULE Caesar EXPORTS Main;
 
IMPORT IO, IntSeq, Text;
Line 4,486 ⟶ 4,896:
Decode(buffer, message);
IO.Put(message); IO.PutChar('\n');
END Caesar.</langsyntaxhighlight>
 
{{out}}
Line 4,493 ⟶ 4,903:
whencaesarsetofftogaul
</pre>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">def caesar_encode(plaintext, shift)
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercase = "abcdefghijklmnopqrstuvwxyz"
Line 4,529 ⟶ 4,938:
 
return plaintext
end</langsyntaxhighlight>
 
=={{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 4,624 ⟶ 5,032:
 
method isFalse public static returns boolean
return \isTrue</langsyntaxhighlight>
 
<pre style="height: 60ex; overflow: scroll;">
Line 4,717 ⟶ 5,125:
HI
</pre>
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import strutils
 
proc caesar(s: string, k: int, decode = false): string =
Line 4,733 ⟶ 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 4,797 ⟶ 5,203:
 
END Caesar.
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,804 ⟶ 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 4,836 ⟶ 5,241:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,842 ⟶ 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 4,868 ⟶ 5,272:
else
c
) str</langsyntaxhighlight>
<langsyntaxhighlight lang="ocaml">let () =
let key = 3 in
let orig = "The five boxing wizards jump quickly" in
Line 4,877 ⟶ 5,281:
print_endline deciphered;
Printf.printf "equal: %b\n" (orig = deciphered)
;;</langsyntaxhighlight>
{{out}}
<pre>$ ocaml caesar.ml
Line 4,883 ⟶ 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 4,901 ⟶ 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 4,921 ⟶ 5,323:
str println()
}
}</langsyntaxhighlight>
{{out}}
<pre>$ ./caesar 8 "This should be a fairly original sentence."
Line 4,927 ⟶ 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 4,973 ⟶ 5,373:
writeln ('Decrypted message: ', message);
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>>: ./CaesarCipher
Line 4,980 ⟶ 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 4,994 ⟶ 5,393:
print "msg: $msg\nenc: $enc\ndec: $dec\n";
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,000 ⟶ 5,399:
enc: DRO PSFO LYHSXQ GSJKBNC TEWZ AESMUVI
dec: THE FIVE BOXING WIZARDS JUMP QUICKLY</pre>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
Line 5,023 ⟶ 5,421:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 5,031 ⟶ 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 5,051 ⟶ 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>
Line 5,057 ⟶ 5,454:
Or, using PHP's '''strtr()''' built-in function
 
<langsyntaxhighlight lang="php"><?php
 
function caesarEncode($message, $key) {
Line 5,065 ⟶ 5,462:
}
 
echo caesarEncode('THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG', 12), PHP_EOL;</langsyntaxhighlight>
 
{{out}}
<pre>FTQ CGUOW NDAIZ RAJ VGYBQP AHQD FTQ XMLK PAS</pre>
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">main =>
S = "All human beings are born free and equal in dignity and rights.",
println(S),
Line 5,094 ⟶ 5,490:
M.put(Lower[I],Lower[II])
end.
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,101 ⟶ 5,497:
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 5,119 ⟶ 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.
<langsyntaxhighlight Pikelang="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);
Line 5,129 ⟶ 5,523:
string decoded = c->decrypt(msg_s11);
 
write("%s\n%s\n%s\n%s\n", msg, msg_s2, msg_s11, decoded);</langsyntaxhighlight>
 
{{out}}
Line 5,138 ⟶ 5,532:
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 5,159 ⟶ 5,552:
put skip list ('Decyphered text=', text);
 
end caesar;</langsyntaxhighlight>
{{out}} with offset of 5:
<pre>
Line 5,166 ⟶ 5,559:
Decyphered text= THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG
</pre>
 
=={{header|PowerShell}}==
<langsyntaxhighlight Powershelllang="powershell"># Author: M. McNabb
function Get-CaesarCipher
{
Line 5,242 ⟶ 5,634:
$OutText = $null
}
}</langsyntaxhighlight>
Usage examples:
<pre>
Line 5,259 ⟶ 5,651:
Vsxo drboo;
</pre>
 
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}
{{libheader|clpfd}}
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(clpfd)).
 
caesar :-
Line 5,295 ⟶ 5,686:
 
% compute values of V1 and V2
label([A, V1, V2]).</langsyntaxhighlight>
{{out}}
<pre> ?- caesar.
Line 5,303 ⟶ 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 5,342 ⟶ 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 5,349 ⟶ 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 5,369 ⟶ 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 5,382 ⟶ 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 5,389 ⟶ 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 5,403 ⟶ 5,795:
enc = caesar(msg, 11)
print enc
print caesar(enc, 11, decode = True)</langsyntaxhighlight>
{{out}}
<pre>
Line 5,413 ⟶ 5,805:
Variant with memoization of translation tables
{{works with|Python|3.x}}
<langsyntaxhighlight lang="python">import string
def caesar(s, k = 13, decode = False, *, memo={}):
if decode: k = 26 - k
Line 5,423 ⟶ 5,815:
string.ascii_uppercase[k:] + string.ascii_uppercase[:k] +
string.ascii_lowercase[k:] + string.ascii_lowercase[:k])
return s.translate(table)</langsyntaxhighlight>
 
A compact alternative solution
<langsyntaxhighlight lang="python">
from string import ascii_uppercase as abc
 
Line 5,436 ⟶ 5,828:
print(caesar(msg, 11))
print(caesar(caesar(msg, 11), 11, True))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,442 ⟶ 5,834:
THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGS
</pre>
 
 
=={{header|QBasic}}==
{{works with|QBasic}}
Line 5,449 ⟶ 5,839:
{{works with|True BASIC}} Note that TrueBasic uses '!' for comments
{{trans|BASIC256}}
<langsyntaxhighlight QBasiclang="qbasic">LET dec$ = ""
LET tipo$ = "cleartext "
 
Line 5,480 ⟶ 5,870:
END IF
NEXT i
END</langsyntaxhighlight>
 
=={{header|Quackery}}==
<langsyntaxhighlight Quackerylang="quackery"> [ dup upper != ] is lower? ( c --> b )
 
[ dup lower != ] is upper? ( c --> b )
Line 5,505 ⟶ 5,894:
dup echo$ cr
23 caesar dup echo$ cr
23 decode caesar echo$ cr</Langsyntaxhighlight>
 
{{out}}
Line 5,512 ⟶ 5,901:
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 5,544 ⟶ 5,932:
 
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,560 ⟶ 5,948:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
Line 5,580 ⟶ 5,968:
(define (encrypt s) (caesar s 1))
(define (decrypt s) (caesar s -1))
</syntaxhighlight>
</lang>
Example:
<pre>
Line 5,589 ⟶ 5,977:
"The five boxing wizards jump quickly."
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" perl6line>my @alpha = 'A' .. 'Z';
sub encrypt ( $key where 1..25, $plaintext ) {
$plaintext.trans( @alpha Z=> @alpha.rotate($key) );
Line 5,607 ⟶ 5,994:
.say for $original, $en, $de;
 
say 'OK' if $original eq all( map { .&decrypt(.&encrypt($original)) }, 1..25 );</langsyntaxhighlight>
{{out}}
<pre>THE FIVE BOXING WIZARDS JUMP QUICKLY
Line 5,613 ⟶ 6,000:
THE FIVE BOXING WIZARDS JUMP QUICKLY
OK</pre>
 
=={{header|Red}}==
<langsyntaxhighlight lang="red">
Red ["Ceasar Cipher"]
 
Line 5,643 ⟶ 6,029:
encrypt: :caesar
decrypt: func spec-of :caesar [caesar src negate key]
</syntaxhighlight>
</lang>
<pre>
>> print encrypt "Ceasar Cipher" 4
Line 5,651 ⟶ 6,037:
>>
</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 5,667 ⟶ 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=Say Caesar(y,-key);' say ' uncypheredciphered:' zcode /* " " uncyphered ciphered text " " */
back=caesar(code,-key)
if z\==p then say "plain text doesn't match uncyphered cyphered text."
exitSay 0' 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. */
return translatebadpos=verify(stext,abc) substr(@ || @, ky, L), @)/* any illegal /*returncharacter in 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 */
key2=key+1
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>
Line 5,705 ⟶ 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 0 /*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, digits, 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) return translate(s, substr(@ || @, ky, L), @) /*return absolute value of the processedkey text.*/
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 */
If badpos\==0 Then
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>
Line 5,736 ⟶ 6,150:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Caesar cipher
 
Line 5,794 ⟶ 6,208:
next
return str
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,807 ⟶ 6,221:
decrypted again:
pack my box with five dozen liquor jugs
</pre>
=={{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}}==
<langsyntaxhighlight lang="ruby">class String
ALFABET = ("A".."Z").to_a
 
Line 5,822 ⟶ 6,275:
encypted = "THEYBROKEOURCIPHEREVERYONECANREADTHIS".caesar_cipher(3)
decrypted = encypted.caesar_cipher(-3)
</syntaxhighlight>
</lang>
 
=={{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 5,845 ⟶ 6,298:
cipher$ = cipher$;code$
next i
END FUNCTION</langsyntaxhighlight>
{{out}}
<pre>Gimme a ofset:?9
Line 5,851 ⟶ 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 5,889 ⟶ 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 5,903 ⟶ 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 5,917 ⟶ 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 5,928 ⟶ 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 5,941 ⟶ 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 5,971 ⟶ 6,421:
(display (string-map caesar msg))
(newline)
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,977 ⟶ 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 6,016 ⟶ 6,465:
/\n\n/! s/\n([^\n])/\1\n/
t loop
s/\n\n.*//</langsyntaxhighlight>
{{out}}
<pre>
Line 6,029 ⟶ 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 6,059 ⟶ 6,507:
writeln("Encrypted: " <& rot(testText, exampleKey));
writeln("Decrypted: " <& rot(rot(testText, exampleKey), 26 - exampleKey));
end func;</langsyntaxhighlight>
{{out}}
<pre>
Line 6,066 ⟶ 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 6,100 ⟶ 6,547:
"Input: \t" ++ args[1] ++ "\n" ++
"Encrypted:\t" ++ encrypted ++ "\n" ++
"Decrypted:\t" ++ decrypted;</langsyntaxhighlight>
{{out}}
<pre>
Line 6,108 ⟶ 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 6,123 ⟶ 6,569:
say "msg: #{msg}";
say "enc: #{enc}";
say "dec: #{dec}";</langsyntaxhighlight>
 
{{out}}
Line 6,131 ⟶ 6,577:
dec: THE FIVE BOXING WIZARDS JUMP QUICKLY
</pre>
 
=={{header|Sinclair ZX81 BASIC}}==
Works with 1k of RAM. A negative key decodes.
<langsyntaxhighlight lang="basic"> 10 INPUT KEY
20 INPUT T$
30 LET C$=""
Line 6,145 ⟶ 6,590:
100 LET C$=C$+L$
110 NEXT I
120 PRINT C$</langsyntaxhighlight>
{{in}}
<pre>12
Line 6,157 ⟶ 6,602:
{{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 6,183 ⟶ 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}}==
Line 6,191 ⟶ 6,699:
 
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.
<langsyntaxhighlight lang="ssem">00101000000000100000000000000000 0. -20 to c
11001000000000010000000000000000 1. Sub. 19
10101000000001100000000000000000 2. c to 21
Line 6,209 ⟶ 6,717:
00000000000001110000000000000000 16. Stop
11010000000000000000000000000000 17. 11
01011000000000000000000000000000 18. 26</langsyntaxhighlight>
 
=={{header|Stata}}==
 
<langsyntaxhighlight lang="stata">function caesar(s, k) {
u = ascii(s)
i = selectindex(u:>=65 :& u:<=90)
Line 6,223 ⟶ 6,730:
 
caesar("layout", 20)
fusion</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">
func usage(_ e:String) {
print("error: \(e)")
Line 6,309 ⟶ 6,815:
test()
main()
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.6; # Or TclOO package for 8.5
 
oo::class create Caesar {
Line 6,334 ⟶ 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 6,342 ⟶ 6,847:
puts "Original message = $txt"
puts "Encrypted message = $enc"
puts "Decrypted message = $dec"</langsyntaxhighlight>
{{out}}
<pre>
Line 6,349 ⟶ 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 6,374 ⟶ 6,915:
 
DECODED = EXCHANGE (encoded,secret2abc)
PRINT "encoded decoded ",decoded</langsyntaxhighlight>
{{out}}
<pre>
Line 6,381 ⟶ 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 6,406 ⟶ 6,946:
encoded: @{text :filter enc}
decoded: @{text :filter dec}
@(end)</langsyntaxhighlight>
{{out}}
<pre>$ ./txr caesar.txr 12 'Hello, world!'
Line 6,415 ⟶ 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 6,430 ⟶ 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 6,490 ⟶ 7,028:
echo "original: $txt"
echo "encrypted: $enc"
echo "decrypted: $dec"</langsyntaxhighlight>
{{out}}
<pre>
Line 6,496 ⟶ 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 6,525 ⟶ 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 6,539 ⟶ 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 6,592 ⟶ 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.
<langsyntaxhighlight Valalang="vala">static void println(string str) {
stdout.printf("%s\r\n", str);
}
Line 6,627 ⟶ 7,162:
println(encrypt(test_case, -1));
println(decrypt(encrypt(test_case, -1), -1));
}</langsyntaxhighlight>
 
{{out}}
Line 6,635 ⟶ 7,170:
The quick brown fox jumped over the lwzy dog
</pre>
 
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 6,673 ⟶ 7,207:
Caesar_Cipher = strTemp
End Function
</syntaxhighlight>
</lang>
 
{{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.
<langsyntaxhighlight lang="vb">
str = "IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES."
 
Line 6,717 ⟶ 7,250:
 
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,725 ⟶ 7,258:
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 6,738 ⟶ 7,270:
Char(1)
}
}</langsyntaxhighlight>
 
{{out}} with key 13:
Line 6,746 ⟶ 7,278:
Decrypted text: Quick brown Fox jumps over the lazy Dog.
</pre>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Function Encrypt(ch As Char, code As Integer) As Char
Line 6,779 ⟶ 7,310:
End Sub
 
End Module</langsyntaxhighlight>
{{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 6,803 ⟶ 7,381:
]
!!ceasar "abc $%^ ABC" 10
}</langsyntaxhighlight>
Returns:
<pre>"klm $%^ KLM"</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">class Caesar {
static encrypt(s, key) {
var offset = key % 26
Line 6,834 ⟶ 7,411:
var encoded = Caesar.encrypt("Bright vixens jump; dozy fowl quack.", 8)
System.print(encoded)
System.print(Caesar.decrypt(encoded, 8))</langsyntaxhighlight>
 
{{out}}
Line 6,845 ⟶ 7,422:
{{trans|C custom implementation}}
{{works with|GCC|7.3.0 - Ubuntu 18.04 64-bit}}
<langsyntaxhighlight lang="asm"> # Author: Ettore Forigo - Hexwell
 
.intel_syntax noprefix
Line 6,946 ⟶ 7,523:
mov eax, 0 # 0
leave
ret # return 0</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="bash">$ gcc caesar.S -o caesar
$ ./caesar 10 abc
klm
$ ./caesar 16 klm
abc</langsyntaxhighlight>
 
=={{header|XBasic}}==
{{trans|Modula-2}}
{{works with|Windows XBasic}}
<langsyntaxhighlight lang="xbasic">
PROGRAM "caesarcipher"
VERSION "0.0001"
Line 7,014 ⟶ 7,590:
END FUNCTION e$
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 7,021 ⟶ 7,597:
Decrypted: The five boxing wizards jump quickly
</pre>
 
=={{header|XBS}}==
<langsyntaxhighlight lang="xbs">set letters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"::split();
 
func caesar(text,shift:number=1){
Line 7,059 ⟶ 7,634:
 
log(e);
log(d);</langsyntaxhighlight>
{{out}}
<pre>
Line 7,065 ⟶ 7,640:
Hi
</pre>
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="lisp">(defun caesar-encode (text key)
(defun encode (ascii-code)
(defun rotate (character alphabet)
Line 7,082 ⟶ 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 7,092 ⟶ 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 7,110 ⟶ 7,683:
ChOut(0, C);
until C=$1A; \EOF
]</langsyntaxhighlight>
 
Example outfile.xxx:
Line 7,116 ⟶ 7,689:
SDFN PB ERA ZLWK ILYH GRCHQ OLTXRU MXJV.
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
<lang Yabasic>
REM *** By changing the key and pattern, an encryption system that is difficult to break can be achieved. ***
 
Line 7,153 ⟶ 7,725:
 
return res$
end sub</langsyntaxhighlight>
{{out}}
<pre>You are encouraged to solve this task according to the task description, using any language you may know.
Line 7,160 ⟶ 7,732:
 
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}}==
<langsyntaxhighlight 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;
Line 7,168 ⟶ 7,772:
ltrs:=String(letters[n,sz],letters[0,n],letters[m,sz],letters[26,n]);
str.translate(letters,ltrs)
}</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 7,183 ⟶ 7,787:
 
=={{header|zonnon}}==
<langsyntaxhighlight lang="zonnon">
module Caesar;
const
Line 7,241 ⟶ 7,845:
writeln(txt," -c-> ",cipher," -d-> ",decipher)
end Caesar.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 7,248 ⟶ 7,852:
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 7,264 ⟶ 7,867:
1050 NEXT i
1060 RETURN
</syntaxhighlight>
</lang>
{{trans|Yabasic}}
<langsyntaxhighlight 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
Line 7,295 ⟶ 7,898:
1170 LET r$=r$+p$(delta)
1180 NEXT i
1190 RETURN </langsyntaxhighlight>
{{omit from|GUISS}}
885

edits