Caesar cipher: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1: Line 1:
{{task|Encryption}}
[[Category:String manipulation]]
[[Category:String manipulation]]
{{task|Encryption}}




Line 23: Line 23:
* [[Vigenère Cipher/Cryptanalysis]]
* [[Vigenère Cipher/Cryptanalysis]]
<br><br>
<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}}==
=={{header|11l}}==
<syntaxhighlight lang=11l>F caesar(string, =key, decode = 0B)
<syntaxhighlight lang="11l">F caesar(string, =key, decode = 0B)
I decode
I decode
key = 26 - key
key = 26 - key
Line 51: Line 80:
The quick brown fox jumped over the lazy dogs
The quick brown fox jumped over the lazy dogs
</pre>
</pre>

=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
A good example of the use of TR instruction to translate a character.
A good example of the use of TR instruction to translate a character.
<syntaxhighlight lang=360asm>* Caesar cypher 04/01/2019
<syntaxhighlight lang="360asm">* Caesar cypher 04/01/2019
CAESARO PROLOG
CAESARO PROLOG
XPRNT PHRASE,L'PHRASE print phrase
XPRNT PHRASE,L'PHRASE print phrase
Line 90: Line 118:
THE FIVE BOXING WIZARDS JUMP QUICKLY
THE FIVE BOXING WIZARDS JUMP QUICKLY
</pre>
</pre>

=={{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|Action!}}==
=={{header|Action!}}==
<syntaxhighlight lang=Action!>CHAR FUNC Shift(CHAR c BYTE code)
<syntaxhighlight lang="action!">CHAR FUNC Shift(CHAR c BYTE code)
CHAR base
CHAR base


Line 183: Line 179:
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
</pre>
</pre>

=={{header|Ada}}==
=={{header|Ada}}==
<syntaxhighlight lang=Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;


procedure Caesar is
procedure Caesar is
Line 236: Line 231:
Ciphertext ----------->Wkh ilyh eralqj zlcdugv mxps txlfnob
Ciphertext ----------->Wkh ilyh eralqj zlcdugv mxps txlfnob
Decrypted Ciphertext ->The five boxing wizards jump quickly</pre>
Decrypted Ciphertext ->The five boxing wizards jump quickly</pre>

=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{trans|Ada|Note: This specimen retains the original [[#Ada|Ada]] coding style.}}
{{trans|Ada|Note: This specimen retains the original [[#Ada|Ada]] coding style.}}
Line 242: Line 236:
{{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].}}
{{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''.}}
{{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''.}}
<syntaxhighlight lang=algol68>#!/usr/local/bin/a68g --script #
<syntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #


program caesar: BEGIN
program caesar: BEGIN
Line 291: Line 285:
Decrypted Ciphertext ->The five boxing wizards jump quickly
Decrypted Ciphertext ->The five boxing wizards jump quickly
</pre>
</pre>

=={{header|APL}}==
=={{header|APL}}==
<syntaxhighlight lang=apl>
<syntaxhighlight lang="apl">
∇CAESAR[⎕]∇
∇CAESAR[⎕]∇
Line 322: Line 315:
Esl dyar: dpyargmlyj icwq qugraf dpmk TOODQ BZRD rm jmucp ayqc.
Esl dyar: dpyargmlyj icwq qugraf dpmk TOODQ BZRD rm jmucp ayqc.
</pre>
</pre>

=={{header|AppleScript}}==
=={{header|AppleScript}}==


<syntaxhighlight lang=applescript>(* Only non-accented English letters are altered here. *)
<syntaxhighlight lang="applescript">(* Only non-accented English letters are altered here. *)


on caesarDecipher(txt, |key|)
on caesarDecipher(txt, |key|)
Line 355: Line 347:
{{output}}
{{output}}


<syntaxhighlight lang=applescript>"Text: 'ROMANES EUNT DOMUS!
<syntaxhighlight lang="applescript">"Text: 'ROMANES EUNT DOMUS!
The quick brown fox jumps over the lazy dog.'
The quick brown fox jumps over the lazy dog.'
Key: 9
Key: 9
Line 363: Line 355:
ROMANES EUNT DOMUS!
ROMANES EUNT DOMUS!
The quick brown fox jumps over the lazy dog."</syntaxhighlight>
The quick brown fox jumps over the lazy dog."</syntaxhighlight>

=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang=ApplesoftBasic>100 INPUT ""; T$
<syntaxhighlight lang="applesoftbasic">100 INPUT ""; T$


110 LET K% = RND(1) * 25 + 1
110 LET K% = RND(1) * 25 + 1
Line 428: Line 419:
DECODED WITH CAESAR 25
DECODED WITH CAESAR 25
PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS</pre>
PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS</pre>

=={{header|Arc}}==
=={{header|Arc}}==
<syntaxhighlight lang=Arc>
<syntaxhighlight lang="arc">
(= rot (fn (L N)
(= rot (fn (L N)
(if
(if
Line 454: Line 444:


{{Out}}
{{Out}}
<syntaxhighlight lang=arc>
<syntaxhighlight lang="arc">
(caesar "The quick brown fox jumps over the lazy dog.")
(caesar "The quick brown fox jumps over the lazy dog.")
"Gur dhvpx oebja sbk whzcf bire gur ynml qbt."
"Gur dhvpx oebja sbk whzcf bire gur ynml qbt."
</syntaxhighlight>
</syntaxhighlight>

=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM Assembly>
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program caresarcode.s */
/* program caresarcode.s */
Line 636: Line 625:


</syntaxhighlight>
</syntaxhighlight>

=={{header|Arturo}}==
=={{header|Arturo}}==
{{trans|11l}}
{{trans|11l}}
<syntaxhighlight lang=rebol>ia: to :integer `a`
<syntaxhighlight lang="rebol">ia: to :integer `a`
iA: to :integer `A`
iA: to :integer `A`
lowAZ: `a`..`z`
lowAZ: `a`..`z`
Line 668: Line 656:
Encoded : Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozrd
Encoded : Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozrd
Decoded : The quick brown fox jumped over the lazy dogs</pre>
Decoded : The quick brown fox jumped over the lazy dogs</pre>

=={{header|Astro}}==
=={{header|Astro}}==
<syntaxhighlight lang=python>fun caesar(s, k, decode: false):
<syntaxhighlight lang="python">fun caesar(s, k, decode: false):
if decode:
if decode:
k = 26 - k
k = 26 - k
Line 683: Line 670:


print(message, encrypted, decrypted, sep: '\n')</syntaxhighlight>
print(message, encrypted, decrypted, sep: '\n')</syntaxhighlight>

=={{header|AutoHotkey}}==
=={{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
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
<syntaxhighlight lang="autohotkey">n=2
s=HI
s=HI
t:=&s
t:=&s
Line 693: Line 679:
MsgBox % o</syntaxhighlight>
MsgBox % o</syntaxhighlight>
This next one is much more sane and handles input very well, including case.
This next one is much more sane and handles input very well, including case.
<syntaxhighlight lang=AutoHotkey>Caesar(string, n){
<syntaxhighlight lang="autohotkey">Caesar(string, n){
Loop Parse, string
Loop Parse, string
{
{
Line 708: Line 694:
{{out}}<pre>j k
{{out}}<pre>j k
Bc</pre>
Bc</pre>

=={{header|AutoIt}}==
=={{header|AutoIt}}==


The Ceasar Funktion can enrcypt and decrypt, standart is Encryption, to Decrypt set third parameter to False
The Ceasar Funktion can enrcypt and decrypt, standart is Encryption, to Decrypt set third parameter to False
<syntaxhighlight lang=autoit>
<syntaxhighlight lang="autoit">
$Caesar = Caesar("Hi", 2, True)
$Caesar = Caesar("Hi", 2, True)
MsgBox(0, "Caesar", $Caesar)
MsgBox(0, "Caesar", $Caesar)
Line 746: Line 731:
EndFunc ;==>Caesar
EndFunc ;==>Caesar
</syntaxhighlight>
</syntaxhighlight>

=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang=awk>
<syntaxhighlight lang="awk">
#!/usr/bin/awk -f
#!/usr/bin/awk -f


Line 799: Line 783:
clear: MY HOVERCRAFT IS FULL OF EELS.
clear: MY HOVERCRAFT IS FULL OF EELS.
</pre>
</pre>

=={{header|Babel}}==
=={{header|Babel}}==


<syntaxhighlight lang=babel>((main
<syntaxhighlight lang="babel">((main
{"The quick brown fox jumps over the lazy dog.\n"
{"The quick brown fox jumps over the lazy dog.\n"
dup <<
dup <<
Line 859: Line 842:
Kyv hlztb sifne wfo aldgj fmvi kyv crqp ufx.
Kyv hlztb sifne wfo aldgj fmvi kyv crqp ufx.
The quick brown fox jumps over the lazy dog.</pre>
The quick brown fox jumps over the lazy dog.</pre>

=={{header|BaCon}}==
=={{header|BaCon}}==
<syntaxhighlight lang=qbasic>CONST lc$ = "abcdefghijklmnopqrstuvwxyz"
<syntaxhighlight lang="qbasic">CONST lc$ = "abcdefghijklmnopqrstuvwxyz"
CONST uc$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
CONST uc$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"


Line 894: Line 876:
Decrypted: The quick brown fox jumps over the lazy dog.
Decrypted: The quick brown fox jumps over the lazy dog.
</pre>
</pre>

=={{header|bash}}==
=={{header|bash}}==
Caesar cipher bash implementation
Caesar cipher bash implementation
{{works with|GNU bash, version 4}}
{{works with|GNU bash, version 4}}


<syntaxhighlight lang=bash>
<syntaxhighlight lang="bash">
caesar_cipher() {
caesar_cipher() {


Line 952: Line 933:
Hello World!
Hello World!
</pre>
</pre>

=={{header|BASIC256}}==
=={{header|BASIC256}}==
<syntaxhighlight lang=text>
<syntaxhighlight lang="text">
# Caeser Cipher
# Caeser Cipher
# basic256 1.1.4.0
# basic256 1.1.4.0
Line 996: Line 976:
MY HOVERCRAFT IS FULL OF EELS.
MY HOVERCRAFT IS FULL OF EELS.
</pre>
</pre>

=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<syntaxhighlight lang=bbcbasic> plaintext$ = "Pack my box with five dozen liquor jugs"
<syntaxhighlight lang="bbcbasic"> plaintext$ = "Pack my box with five dozen liquor jugs"
PRINT plaintext$
PRINT plaintext$
Line 1,025: Line 1,004:
Zkmu wi lyh gsdr psfo nyjox vsaeyb teqc
Zkmu wi lyh gsdr psfo nyjox vsaeyb teqc
Pack my box with five dozen liquor jugs</pre>
Pack my box with five dozen liquor jugs</pre>

=={{header|Beads}}==
=={{header|Beads}}==
<syntaxhighlight lang=Beads>beads 1 program 'Caesar cipher'
<syntaxhighlight lang="beads">beads 1 program 'Caesar cipher'
calc main_init
calc main_init
var str = "The five boxing wizards (🤖) jump quickly."
var str = "The five boxing wizards (🤖) jump quickly."
Line 1,065: Line 1,043:
Decrypted: The five boxing wizards (🤖) jump quickly.
Decrypted: The five boxing wizards (🤖) jump quickly.
</pre>
</pre>

=={{header|Befunge}}==
=={{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.
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: Line 1,048:
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.
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.


<syntaxhighlight lang=befunge>65+>>>>10p100p1>:v:+>#*,#g1#0-#0:#!<<
<syntaxhighlight lang="befunge">65+>>>>10p100p1>:v:+>#*,#g1#0-#0:#!<<
"`"::_@#!`\*84:<~<$<^+"A"%*2+9<v"{"\`
"`"::_@#!`\*84:<~<$<^+"A"%*2+9<v"{"\`
**-"A"-::0\`\55*`+#^_\0g+"4"+4^>\`*48</syntaxhighlight>
**-"A"-::0\`\55*`+#^_\0g+"4"+4^>\`*48</syntaxhighlight>
Line 1,081: Line 1,058:
The decrypter is essentially identical, except for a change of sign on the last line.
The decrypter is essentially identical, except for a change of sign on the last line.


<syntaxhighlight lang=befunge>65+>>>>10p100p1>:v:+>#*,#g1#0-#0:#!<<
<syntaxhighlight lang="befunge">65+>>>>10p100p1>:v:+>#*,#g1#0-#0:#!<<
"`"::_@#!`\*84:<~<$<^+"A"%*2+9<v"{"\`
"`"::_@#!`\*84:<~<$<^+"A"%*2+9<v"{"\`
**-"A"-::0\`\55*`+#^_\0g-"4"+4^>\`*48</syntaxhighlight>
**-"A"-::0\`\55*`+#^_\0g-"4"+4^>\`*48</syntaxhighlight>
Line 1,088: Line 1,065:
<pre>ESPBFTNVMCZHYQZIUFXAPOZGPCESPWLKJOZRD
<pre>ESPBFTNVMCZHYQZIUFXAPOZGPCESPWLKJOZRD
THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGS</pre>
THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGS</pre>

=={{header|BQN}}==
=={{header|BQN}}==
<syntaxhighlight lang=bqn>o ← @‿'A'‿@‿'a'‿@ ⋄ m ← 5⥊↕2 ⋄ p ← m⊏∞‿26
<syntaxhighlight lang="bqn">o ← @‿'A'‿@‿'a'‿@ ⋄ m ← 5⥊↕2 ⋄ p ← m⊏∞‿26
Rot ← {i←⊑"A[a{"⍋𝕩 ⋄ i⊑o+p|(𝕨×m)+𝕩-o}⎉0</syntaxhighlight>
Rot ← {i←⊑"A[a{"⍋𝕩 ⋄ i⊑o+p|(𝕨×m)+𝕩-o}⎉0</syntaxhighlight>


Example:
Example:


<syntaxhighlight lang=bqn>3 Rot "We're no strangers to love // You know the rules and so do I"</syntaxhighlight>
<syntaxhighlight lang="bqn">3 Rot "We're no strangers to love // You know the rules and so do I"</syntaxhighlight>
<pre>"Zh'uh qr vwudqjhuv wr oryh // Brx nqrz wkh uxohv dqg vr gr L"</pre>
<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])
([https://mlochbaum.github.io/BQN/try.html#code=byDihpAgQOKAvydBJ+KAv0DigL8nYSfigL9AIOKLhCBtIOKGkCA14qWK4oaVMiDii4QgcCDihpAgbeKKj+KInuKAvzI2ClJvdCDihpAge2nihpDiipEiQVtheyLijYvwnZWpIOKLhCBp4oqRbytwfCjwnZWow5dtKSvwnZWpLW994o6JMAoKMyBSb3QgIldlJ3JlIG5vIHN0cmFuZ2VycyB0byBsb3ZlIC8vIFlvdSBrbm93IHRoZSBydWxlcyBhbmQgc28gZG8gSSIK online REPL])

=={{header|Brainf***}}==
=={{header|Brainf***}}==
<syntaxhighlight lang=bf> Author: Ettore Forigo | Hexwell
<syntaxhighlight lang="bf"> Author: Ettore Forigo | Hexwell


+ start the key input loop
+ start the key input loop
Line 1,322: Line 1,297:
Input:
Input:
<!-- Using whitespace syntax highlighting to show the spaces, used by the program to separate arguments -->
<!-- Using whitespace syntax highlighting to show the spaces, used by the program to separate arguments -->
<syntaxhighlight lang=whitespace>10 abc </syntaxhighlight>
<syntaxhighlight lang="whitespace">10 abc </syntaxhighlight>
Output:
Output:
<pre>klm</pre>
<pre>klm</pre>
Input:
Input:
<syntaxhighlight lang=whitespace>16 klm </syntaxhighlight>
<syntaxhighlight lang="whitespace">16 klm </syntaxhighlight>
Output:
Output:
<pre>abc</pre>
<pre>abc</pre>

=={{header|C}}==
=={{header|C}}==
<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 1,383: Line 1,357:
return 0;
return 0;
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Linq;


Line 1,429: Line 1,402:
Encrypted: Ufhp rd gtc bnym knaj itejs qnvztw ozlx.
Encrypted: Ufhp rd gtc bnym knaj itejs qnvztw ozlx.
Decrypted: Pack my box with five dozen liquor jugs.</pre>
Decrypted: Pack my box with five dozen liquor jugs.</pre>

=={{header|C++}}==
=={{header|C++}}==
<syntaxhighlight lang=Cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <iostream>
#include <iostream>
#include <algorithm>
#include <algorithm>
Line 1,494: Line 1,466:
===={{works with|C++-11}}====
===={{works with|C++-11}}====


<syntaxhighlight lang=Cpp>/* caesar cipher */
<syntaxhighlight lang="cpp">/* caesar cipher */


#include <string>
#include <string>
Line 1,560: Line 1,532:
Decrypted: This is a line of plain text, 50 characters long.
Decrypted: This is a line of plain text, 50 characters long.
</pre>
</pre>

=={{header|Clojure}}==
=={{header|Clojure}}==
Readable version:
Readable version:
<syntaxhighlight lang=Clojure>(defn encrypt-character [offset c]
<syntaxhighlight lang="clojure">(defn encrypt-character [offset c]
(if (Character/isLetter c)
(if (Character/isLetter c)
(let [v (int c)
(let [v (int c)
Line 1,594: Line 1,565:


Terser version using replace:
Terser version using replace:
<syntaxhighlight lang=Clojure>(defn encode [k s]
<syntaxhighlight lang="clojure">(defn encode [k s]
(let [f #(take 26 (drop %3 (cycle (range (int %1) (inc (int %2))))))
(let [f #(take 26 (drop %3 (cycle (range (int %1) (inc (int %2))))))
a #(map char (concat (f \a \z %) (f \A \Z %)))]
a #(map char (concat (f \a \z %) (f \A \Z %)))]
Line 1,608: Line 1,579:
=> "The Quick Brown Fox jumped over the lazy dog"
=> "The Quick Brown Fox jumped over the lazy dog"
</pre>
</pre>

=={{header|COBOL}}==
=={{header|COBOL}}==
COBOL-85 ASCII or EBCIDIC
COBOL-85 ASCII or EBCIDIC
<syntaxhighlight lang=COBOL>
<syntaxhighlight lang="cobol">
identification division.
identification division.
program-id. caesar.
program-id. caesar.
Line 1,658: Line 1,628:


{{works with|OpenCOBOL|2.0}}
{{works with|OpenCOBOL|2.0}}
<syntaxhighlight lang=cobol> >>SOURCE FORMAT IS FREE
<syntaxhighlight lang="cobol"> >>SOURCE FORMAT IS FREE
PROGRAM-ID. caesar-cipher.
PROGRAM-ID. caesar-cipher.


Line 1,752: Line 1,722:
Decrypted: The quick brown fox jumps over the lazy dog.
Decrypted: The quick brown fox jumps over the lazy dog.
</pre>
</pre>

=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<syntaxhighlight lang=coffeescript>cipher = (msg, rot) ->
<syntaxhighlight lang="coffeescript">cipher = (msg, rot) ->
msg.replace /([a-z|A-Z])/g, ($1) ->
msg.replace /([a-z|A-Z])/g, ($1) ->
c = $1.charCodeAt(0)
c = $1.charCodeAt(0)
Line 1,770: Line 1,739:
dcDc %^&*()
dcDc %^&*()
</pre>
</pre>

=={{header|Commodore BASIC}}==
=={{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.
Very generic implementation. Please note that in Commodore BASIC, SHIFT-typed letters (to generate either graphic symbols in upper-case mode, or capital letters in lower-case mode) do '''not''' translate to PETSCII characters 97 through 122, but instead to characters 193 through 218.


<syntaxhighlight lang=gwbasic>1 rem caesar cipher
<syntaxhighlight lang="gwbasic">1 rem caesar cipher
2 rem rosetta code
2 rem rosetta code
10 print chr$(147);chr$(14);
10 print chr$(147);chr$(14);
Line 1,847: Line 1,815:
&#9608;
&#9608;
</pre>
</pre>

=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
====Main version====
====Main version====
<syntaxhighlight lang=lisp>(defun encipher-char (ch key)
<syntaxhighlight lang="lisp">(defun encipher-char (ch key)
(let* ((c (char-code ch)) (la (char-code #\a)) (ua (char-code #\A))
(let* ((c (char-code ch)) (la (char-code #\a)) (ua (char-code #\A))
(base (cond ((<= la c (char-code #\z)) la)
(base (cond ((<= la c (char-code #\z)) la)
Line 1,873: Line 1,840:
Encrypted: Wkh ilyh eralqj zlcdugv mxps txlfnob
Encrypted: Wkh ilyh eralqj zlcdugv mxps txlfnob
Decrypted: The five boxing wizards jump quickly</pre>
Decrypted: The five boxing wizards jump quickly</pre>
<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
(defun caesar-encipher (s k)
(defun caesar-encipher (s k)
(map 'string #'(lambda (c) (z c k)) s))
(map 'string #'(lambda (c) (z c k)) s))
Line 1,894: Line 1,861:
1. Program
1. Program


<syntaxhighlight lang=lisp>(defconstant +a+ "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz")
<syntaxhighlight lang="lisp">(defconstant +a+ "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz")
(defun caesar (txt offset)
(defun caesar (txt offset)
Line 1,911: Line 1,878:
(caesar "Nir Pnrfne zbevghev gr fnyhgnag" -13)
(caesar "Nir Pnrfne zbevghev gr fnyhgnag" -13)
Ave Caesar morituri te salutant</pre>
Ave Caesar morituri te salutant</pre>

=={{header|Crystal}}==
=={{header|Crystal}}==
<syntaxhighlight lang=crystal>class String
<syntaxhighlight lang="crystal">class String
ALPHABET = ("A".."Z").to_a
ALPHABET = ("A".."Z").to_a


Line 1,925: Line 1,891:
decrypted = encrypted.caesar_cipher(-5)
decrypted = encrypted.caesar_cipher(-5)
</syntaxhighlight>
</syntaxhighlight>

=={{header|Cubescript}}==
=={{header|Cubescript}}==
<syntaxhighlight lang=cubescript>alias modn [ mod (+ (mod $arg1 $arg2) $arg2) $arg2 ]
<syntaxhighlight lang="cubescript">alias modn [ mod (+ (mod $arg1 $arg2) $arg2) $arg2 ]
//Cubescript's built-in mod will fail on negative numbers
//Cubescript's built-in mod will fail on negative numbers


Line 1,987: Line 1,952:


Usage:
Usage:
<syntaxhighlight lang=text>>>> cipher "The Quick Brown Fox Jumps Over The Lazy Dog." 5
<syntaxhighlight lang="text">>>> cipher "The Quick Brown Fox Jumps Over The Lazy Dog." 5
> Ymj Vznhp Gwtbs Ktc Ozrux Tajw Ymj Qfed Itl.
> Ymj Vznhp Gwtbs Ktc Ozrux Tajw Ymj Qfed Itl.
>>> decipher "Ymj Vznhp Gwtbs Ktc Ozrux Tajw Ymj Qfed Itl." 5
>>> decipher "Ymj Vznhp Gwtbs Ktc Ozrux Tajw Ymj Qfed Itl." 5
> The Quick Brown Fox Jumps Over The Lazy Dog.</syntaxhighlight>
> The Quick Brown Fox Jumps Over The Lazy Dog.</syntaxhighlight>

=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang=d>import std.stdio, std.traits;
<syntaxhighlight lang="d">import std.stdio, std.traits;


S rot(S)(in S s, in int key) pure nothrow @safe
S rot(S)(in S s, in int key) pure nothrow @safe
Line 2,020: Line 1,984:
Decrypted: The five boxing wizards jump quickly</pre>
Decrypted: The five boxing wizards jump quickly</pre>
Simpler in-place version (same output):
Simpler in-place version (same output):
<syntaxhighlight lang=d>import std.stdio, std.ascii;
<syntaxhighlight lang="d">import std.stdio, std.ascii;


void inplaceRot(char[] txt, in int key) pure nothrow {
void inplaceRot(char[] txt, in int key) pure nothrow {
Line 2,042: Line 2,006:


A version that uses the standard library (same output):
A version that uses the standard library (same output):
<syntaxhighlight lang=d>import std.stdio, std.ascii, std.string, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.ascii, std.string, std.algorithm;


string rot(in string s, in int key) pure nothrow @safe {
string rot(in string s, in int key) pure nothrow @safe {
Line 2,059: Line 2,023:
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Dart}}==
=={{header|Dart}}==
<syntaxhighlight lang=dart>class Caesar {
<syntaxhighlight lang="dart">class Caesar {
int _key;
int _key;


Line 2,146: Line 2,109:
"Dro Aesmu Lbygx Pyh Tewzc Yfob Dro Vkji Nyq." decrypts to:
"Dro Aesmu Lbygx Pyh Tewzc Yfob Dro Vkji Nyq." decrypts to:
"The Quick Brown Fox Jumps Over The Lazy Dog."</pre>
"The Quick Brown Fox Jumps Over The Lazy Dog."</pre>

=={{header|Delphi}}==
=={{header|Delphi}}==
See [[#Pascal]].
See [[#Pascal]].

=={{header|Dyalect}}==
=={{header|Dyalect}}==


{{trans|C#}}
{{trans|C#}}


<syntaxhighlight lang=dyalect>func Char.Encrypt(code) {
<syntaxhighlight lang="dyalect">func Char.Encrypt(code) {
if !this.IsLetter() {
if !this.IsLetter() {
return this
return this
Line 2,186: Line 2,147:
Encrypted: Ufhp rd gtc bnym knaj itejs qnvztw ozlx.
Encrypted: Ufhp rd gtc bnym knaj itejs qnvztw ozlx.
Decrypted: Pack my box with five dozen liquor jugs.</pre>
Decrypted: Pack my box with five dozen liquor jugs.</pre>

=={{header|EDSAC order code}}==
=={{header|EDSAC order code}}==
The EDSAC had only upper-case letters, which were represented by 5-bit codes.
The EDSAC had only upper-case letters, which were represented by 5-bit codes.
Line 2,200: Line 2,160:
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.
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).
The message must be terminated by a blank row of tape (represented by '.' in EdsacPC).
<syntaxhighlight lang=edsac>
<syntaxhighlight lang="edsac">
[Caesar cipher for Rosetta Code.
[Caesar cipher for Rosetta Code.
EDSAC program, Initial Orders 2.]
EDSAC program, Initial Orders 2.]
Line 2,429: Line 2,389:
ENTER MESSAGE
ENTER MESSAGE
</pre>
</pre>

=={{header|Eiffel}}==
=={{header|Eiffel}}==
<syntaxhighlight lang=eiffel>
<syntaxhighlight lang="eiffel">
class
class
APPLICATION
APPLICATION
Line 2,492: Line 2,451:
Decoded string (after encoding and decoding): The tiny tiger totally taunted the tall Till.
Decoded string (after encoding and decoding): The tiny tiger totally taunted the tall Till.
</pre>
</pre>

=={{header|Ela}}==
=={{header|Ela}}==


<syntaxhighlight lang=ela>open number char monad io string
<syntaxhighlight lang="ela">open number char monad io string


chars = "ABCDEFGHIJKLMOPQRSTUVWXYZ"
chars = "ABCDEFGHIJKLMOPQRSTUVWXYZ"
Line 2,530: Line 2,488:
Encoded string: "JGOOQ! VJKU KU C UGETGV PGUUCIG!"
Encoded string: "JGOOQ! VJKU KU C UGETGV PGUUCIG!"
Decoded string: "HELLO! THIS IS A SECRET MESSAGE!"</pre>
Decoded string: "HELLO! THIS IS A SECRET MESSAGE!"</pre>

=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<syntaxhighlight lang=elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import system'math;
import system'math;
import extensions;
import extensions;
Line 2,614: Line 2,571:
Decrypted text:Pack my box with five dozen liquor jugs.
Decrypted text:Pack my box with five dozen liquor jugs.
</pre>
</pre>

=={{header|Elixir}}==
=={{header|Elixir}}==
<syntaxhighlight lang=elixir>defmodule Caesar_cipher do
<syntaxhighlight lang="elixir">defmodule Caesar_cipher do
defp set_map(map, range, key) do
defp set_map(map, range, key) do
org = Enum.map(range, &List.to_string [&1])
org = Enum.map(range, &List.to_string [&1])
Line 2,641: Line 2,597:
Decrypted: The five boxing wizards jump quickly
Decrypted: The five boxing wizards jump quickly
</pre>
</pre>

=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang=Erlang>
<syntaxhighlight lang="erlang">
%% Ceasar cypher in Erlang for the rosetta code wiki.
%% Ceasar cypher in Erlang for the rosetta code wiki.
%% Implemented by J.W. Luiten
%% Implemented by J.W. Luiten
Line 2,679: Line 2,634:


</syntaxhighlight>
</syntaxhighlight>
Command: <syntaxhighlight lang=Erlang>ceasar:main("The five boxing wizards jump quickly", 3).</syntaxhighlight>
Command: <syntaxhighlight lang="erlang">ceasar:main("The five boxing wizards jump quickly", 3).</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,686: Line 2,641:
"The five boxing wizards jump quickly"
"The five boxing wizards jump quickly"
</pre>
</pre>

=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang=ERRE>
<syntaxhighlight lang="erre">
PROGRAM CAESAR
PROGRAM CAESAR


Line 2,725: Line 2,679:
Pack my box with five dozen liquor jugs
Pack my box with five dozen liquor jugs
</pre>
</pre>

=={{header|Euphoria}}==
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.0}}
{{works with|Euphoria|4.0.0}}
<syntaxhighlight lang=Euphoria>
<syntaxhighlight lang="euphoria">
--caesar cipher for Rosetta Code wiki
--caesar cipher for Rosetta Code wiki
--User:Lnettnay
--User:Lnettnay
Line 2,791: Line 2,744:
"The Quick Brown Fox Jumps Over The Lazy Dog."
"The Quick Brown Fox Jumps Over The Lazy Dog."
</pre>
</pre>

=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang=fsharp>module caesar =
<syntaxhighlight lang="fsharp">module caesar =
open System
open System


Line 2,815: Line 2,767:
val it : string = "The quick brown fox jumps over the lazy dog."
val it : string = "The quick brown fox jumps over the lazy dog."
</pre>
</pre>

=={{header|Factor}}==
=={{header|Factor}}==
{{works with|Factor|0.97}}
{{works with|Factor|0.97}}
{{trans|F#}}
{{trans|F#}}
<syntaxhighlight lang=factor>USING: io kernel locals math sequences unicode.categories ;
<syntaxhighlight lang="factor">USING: io kernel locals math sequences unicode.categories ;
IN: rosetta-code.caesar-cipher
IN: rosetta-code.caesar-cipher


Line 2,842: Line 2,793:
Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr.
Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr.
</pre>
</pre>

=={{header|Fantom}}==
=={{header|Fantom}}==


Shifts upper/lower case letters, leaves other characters as they are.
Shifts upper/lower case letters, leaves other characters as they are.


<syntaxhighlight lang=fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 2,919: Line 2,869:
Decode: Encrypt - With ! Case,
Decode: Encrypt - With ! Case,
</pre>
</pre>

=={{header|Fhidwfe}}==
=={{header|Fhidwfe}}==
only encodes letters
only encodes letters
<syntaxhighlight lang=Fhidwfe>
<syntaxhighlight lang="fhidwfe">
lowers = ['a','z']
lowers = ['a','z']
uppers = ['A','Z']
uppers = ['A','Z']
Line 2,966: Line 2,915:
//this compiles with only 6 warnings!
//this compiles with only 6 warnings!
</syntaxhighlight>
</syntaxhighlight>

=={{header|Forth}}==
=={{header|Forth}}==
<syntaxhighlight lang=forth>: ceasar ( c n -- c )
<syntaxhighlight lang="forth">: ceasar ( c n -- c )
over 32 or [char] a -
over 32 or [char] a -
dup 0 26 within if
dup 0 26 within if
Line 2,987: Line 2,935:
3 ceasar-inverse test 2@ ceasar-string
3 ceasar-inverse test 2@ ceasar-string
test 2@ cr type</syntaxhighlight>
test 2@ cr type</syntaxhighlight>

=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortan 90 and later}}
{{works with|Fortan 90 and later}}
<syntaxhighlight lang=fortran>program Caesar_Cipher
<syntaxhighlight lang="fortran">program Caesar_Cipher
implicit none
implicit none


Line 3,037: Line 2,984:
Encrypted message = Wkh ilyh eralgj zlcdugv mxps txlfnob
Encrypted message = Wkh ilyh eralgj zlcdugv mxps txlfnob
Decrypted message = The five boxing wizards jump quickly</pre>
Decrypted message = The five boxing wizards jump quickly</pre>

=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Sub Encrypt(s As String, key As Integer)
Sub Encrypt(s As String, key As Integer)
Line 3,087: Line 3,033:
Decrypted : Bright vixens jump; dozy fowl quack.
Decrypted : Bright vixens jump; dozy fowl quack.
</pre>
</pre>

=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=cb96008082bc0d8278224cd2a5ec74d3 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=cb96008082bc0d8278224cd2a5ec74d3 Click this link to run this code]'''
<syntaxhighlight lang=gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim byKey As Byte = 3 'The key (Enter 26 to get the same output as input)
Dim byKey As Byte = 3 'The key (Enter 26 to get the same output as input)
Dim byCount As Byte 'Counter
Dim byCount As Byte 'Counter
Line 3,115: Line 3,060:
Wkh ilyh eralqj zlcdugv mxps txlfnob
Wkh ilyh eralqj zlcdugv mxps txlfnob
</pre>
</pre>

=={{header|GAP}}==
=={{header|GAP}}==
<syntaxhighlight lang=gap>CaesarCipher := function(s, n)
<syntaxhighlight lang="gap">CaesarCipher := function(s, n)
local r, c, i, lower, upper;
local r, c, i, lower, upper;
lower := "abcdefghijklmnopqrstuvwxyz";
lower := "abcdefghijklmnopqrstuvwxyz";
Line 3,143: Line 3,087:
CaesarCipher("Vgg cphvi wzdibn vmz wjmi amzz viy zlpvg di ydbidot viy mdbcon.", 5);
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."</syntaxhighlight>
# "All human beings are born free and equal in dignity and rights."</syntaxhighlight>

=={{header|GFA Basic}}==
=={{header|GFA Basic}}==
<syntaxhighlight lang=basic>
<syntaxhighlight lang="basic">
'
'
' Caesar cypher
' Caesar cypher
Line 3,183: Line 3,126:
ENDFUNC
ENDFUNC
</syntaxhighlight>
</syntaxhighlight>

=={{header|Go}}==
=={{header|Go}}==
Obvious solution with explicit testing for character ranges:
Obvious solution with explicit testing for character ranges:
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 3,246: Line 3,188:
}</syntaxhighlight>
}</syntaxhighlight>
Data driven version using functions designed for case conversion. (And for method using % operator, see [[Vigen%C3%A8re_cipher#Go]].)
Data driven version using functions designed for case conversion. (And for method using % operator, see [[Vigen%C3%A8re_cipher#Go]].)
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 3,318: Line 3,260:
Key 26 invalid
Key 26 invalid
</pre>
</pre>

=={{header|Groovy}}==
=={{header|Groovy}}==
Java style:
Java style:
<syntaxhighlight lang=groovy>def caesarEncode(​cipherKey, text) {
<syntaxhighlight lang="groovy">def caesarEncode(​cipherKey, text) {
def builder = new StringBuilder()
def builder = new StringBuilder()
text.each { character ->
text.each { character ->
Line 3,336: Line 3,277:


Functional style:
Functional style:
<syntaxhighlight lang=groovy>def caesarEncode(cipherKey, text) {
<syntaxhighlight lang="groovy">def caesarEncode(cipherKey, text) {
text.chars.collect { c ->
text.chars.collect { c ->
int off = c.isUpperCase() ? 'A' : 'a'
int off = c.isUpperCase() ? 'A' : 'a'
Line 3,345: Line 3,286:


Ninja style:
Ninja style:
<syntaxhighlight lang=groovy>def caesarEncode(k, text) {
<syntaxhighlight lang="groovy">def caesarEncode(k, text) {
(text as int[]).collect { it==' ' ? ' ' : (((it & 0x1f) + k - 1) % 26 + 1 | it & 0xe0) as char }.join()
(text as int[]).collect { it==' ' ? ' ' : (((it & 0x1f) + k - 1) % 26 + 1 | it & 0xe0) as char }.join()
}
}
Line 3,351: Line 3,292:
Using built in 'tr' function and a replacement alphabet:
Using built in 'tr' function and a replacement alphabet:
<syntaxhighlight lang=groovy>def caesarEncode(k, text) {
<syntaxhighlight lang="groovy">def caesarEncode(k, text) {
text.tr('a-zA-Z', ((('a'..'z')*2)[k..(k+25)] + (('A'..'Z')*2)[k..(k+25)]).join())
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) }</syntaxhighlight>
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</syntaxhighlight>
and the same with closures for somewhat better readability:
and the same with closures for somewhat better readability:
<syntaxhighlight lang=groovy>def caesarEncode(k, text) {
<syntaxhighlight lang="groovy">def caesarEncode(k, text) {
def c = { (it*2)[k..(k+25)].join() }
def c = { (it*2)[k..(k+25)].join() }
text.tr('a-zA-Z', c('a'..'z') + c('A'..'Z'))
text.tr('a-zA-Z', c('a'..'z') + c('A'..'Z'))
Line 3,362: Line 3,303:
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</syntaxhighlight>
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</syntaxhighlight>
Test code:
Test code:
<syntaxhighlight lang=groovy>
<syntaxhighlight lang="groovy">
def plainText = "The Quick Brown Fox jumped over the lazy dog"
def plainText = "The Quick Brown Fox jumped over the lazy dog"
def cipherKey = 12
def cipherKey = 12
Line 3,379: Line 3,320:
cypherText(12): Ftq Cguow Ndaiz Raj vgybqp ahqd ftq xmlk pas
cypherText(12): Ftq Cguow Ndaiz Raj vgybqp ahqd ftq xmlk pas
decodedText(12): The Quick Brown Fox jumped over the lazy dog</pre>
decodedText(12): The Quick Brown Fox jumped over the lazy dog</pre>

=={{header|Haskell}}==
=={{header|Haskell}}==
<syntaxhighlight lang=haskell>module Caesar (caesar, uncaesar) where
<syntaxhighlight lang="haskell">module Caesar (caesar, uncaesar) where


import Data.Char
import Data.Char
Line 3,409: Line 3,349:
Similarly, but allowing for negative cipher keys, and using isAlpha, isUpper, negate:
Similarly, but allowing for negative cipher keys, and using isAlpha, isUpper, negate:


<syntaxhighlight lang=haskell>import Data.Bool (bool)
<syntaxhighlight lang="haskell">import Data.Bool (bool)
import Data.Char (chr, isAlpha, isUpper, ord)
import Data.Char (chr, isAlpha, isUpper, ord)


Line 3,438: Line 3,378:


Or with proper error handling:
Or with proper error handling:
<syntaxhighlight lang=haskell>{-# LANGUAGE LambdaCase #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE LambdaCase #-}
module Main where
module Main where


Line 3,470: Line 3,410:
where b' = fromIntegral $ ord b
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c</syntaxhighlight>
c' = fromIntegral $ ord c</syntaxhighlight>

=={{header|Hoon}}==
=={{header|Hoon}}==
<syntaxhighlight lang=Hoon>|%
<syntaxhighlight lang="hoon">|%
++ enc
++ enc
|= [msg=tape key=@ud]
|= [msg=tape key=@ud]
Line 3,481: Line 3,420:
(enc msg (sub 26 key))
(enc msg (sub 26 key))
--</syntaxhighlight>
--</syntaxhighlight>

=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Strictly speaking a Ceasar Cipher is a shift of 3 (the default in this case).
Strictly speaking a Ceasar Cipher is a shift of 3 (the default in this case).
<syntaxhighlight lang=Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
ctext := caesar(ptext := map("The quick brown fox jumped over the lazy dog"))
ctext := caesar(ptext := map("The quick brown fox jumped over the lazy dog"))
dtext := caesar(ctext,,"decrypt")
dtext := caesar(ctext,,"decrypt")
Line 3,505: Line 3,443:
Encphered text = "wkh txlfn eurzq ira mxpshg ryhu wkh odcb grj"
Encphered text = "wkh txlfn eurzq ira mxpshg ryhu wkh odcb grj"
Decphered text = "the quick brown fox jumped over the lazy dog"</pre>
Decphered text = "the quick brown fox jumped over the lazy dog"</pre>

=={{header|IS-BASIC}}==
=={{header|IS-BASIC}}==
<syntaxhighlight lang=IS-BASIC>100 PROGRAM "CaesarCi.bas"
<syntaxhighlight lang="is-basic">100 PROGRAM "CaesarCi.bas"
110 STRING M$*254
110 STRING M$*254
120 INPUT PROMPT "String: ":M$
120 INPUT PROMPT "String: ":M$
Line 3,548: Line 3,485:
490 LET M$=T$
490 LET M$=T$
500 END DEF</syntaxhighlight>
500 END DEF</syntaxhighlight>

=={{header|J}}==
=={{header|J}}==
If we assume that the task also requires us to leave non-alphabetic characters alone:
If we assume that the task also requires us to leave non-alphabetic characters alone:
<syntaxhighlight lang=j>cndx=: [: , 65 97 +/ 26 | (i.26)&+
<syntaxhighlight lang="j">cndx=: [: , 65 97 +/ 26 | (i.26)&+
caesar=: (cndx 0)}&a.@u:@cndx@[ {~ a.i.]</syntaxhighlight>
caesar=: (cndx 0)}&a.@u:@cndx@[ {~ a.i.]</syntaxhighlight>
Example use:<syntaxhighlight lang=j> 2 caesar 'This simple "monoalphabetic substitution cipher" provides almost no security, ...'
Example use:<syntaxhighlight lang="j"> 2 caesar 'This simple "monoalphabetic substitution cipher" provides almost no security, ...'
Vjku ukorng "oqpqcnrjcdgvke uwduvkvwvkqp ekrjgt" rtqxkfgu cnoquv pq ugewtkva, ...</syntaxhighlight>
Vjku ukorng "oqpqcnrjcdgvke uwduvkvwvkqp ekrjgt" rtqxkfgu cnoquv pq ugewtkva, ...</syntaxhighlight>
If we instead assume the task only requires we treat upper case characters:
If we instead assume the task only requires we treat upper case characters:
<syntaxhighlight lang=j>CAESAR=:1 :'(26|m&+)&.((26{.64}.a.)&i.)'</syntaxhighlight>
<syntaxhighlight lang="j">CAESAR=:1 :'(26|m&+)&.((26{.64}.a.)&i.)'</syntaxhighlight>
Example use:<syntaxhighlight lang=j> 20 CAESAR 'HI'
Example use:<syntaxhighlight lang="j"> 20 CAESAR 'HI'
BC</syntaxhighlight>
BC</syntaxhighlight>

=={{header|Janet}}==
=={{header|Janet}}==
<syntaxhighlight lang=janet>
<syntaxhighlight lang="janet">
(def alphabet "abcdefghijklmnopqrstuvwxyz")
(def alphabet "abcdefghijklmnopqrstuvwxyz")


Line 3,599: Line 3,534:
"thequickbrownfoxjumpsoverthelazydog"
"thequickbrownfoxjumpsoverthelazydog"
</pre>
</pre>

=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<syntaxhighlight lang=java5>public class Cipher {
<syntaxhighlight lang="java5">public class Cipher {
public static void main(String[] args) {
public static void main(String[] args) {


Line 3,637: Line 3,571:
The quick brown fox Jumped over the lazy Dog
The quick brown fox Jumped over the lazy Dog
</pre>
</pre>

=={{header|JavaScript}}==
=={{header|JavaScript}}==


===ES5===
===ES5===


<syntaxhighlight lang=javascript>function caesar (text, shift) {
<syntaxhighlight lang="javascript">function caesar (text, shift) {
return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/./g, function(a) {
return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/./g, function(a) {
return String.fromCharCode(65+(a.charCodeAt(0)-65+shift)%26);
return String.fromCharCode(65+(a.charCodeAt(0)-65+shift)%26);
Line 3,665: Line 3,598:
===ES6===
===ES6===


<syntaxhighlight lang=javascript>var caesar = (text, shift) => text
<syntaxhighlight lang="javascript">var caesar = (text, shift) => text
.toUpperCase()
.toUpperCase()
.replace(/[^A-Z]/g, '')
.replace(/[^A-Z]/g, '')
Line 3,674: Line 3,607:
Or, allowing encoding and decoding of both lower and upper case:
Or, allowing encoding and decoding of both lower and upper case:


<syntaxhighlight lang=JavaScript>((key, strPlain) => {
<syntaxhighlight lang="javascript">((key, strPlain) => {


// Int -> String -> String
// Int -> String -> String
Line 3,720: Line 3,653:
{{Out}}
{{Out}}
<pre>Mebsy, Mockbo foxxo, o fsno o fsxco ? , -> , Curio, Cesare venne, e vide e vinse ?</pre>
<pre>Mebsy, Mockbo foxxo, o fsno o fsxco ? , -> , Curio, Cesare venne, e vide e vinse ?</pre>

=={{header|jq}}==
=={{header|jq}}==
{{trans|Wren}}
{{trans|Wren}}
{{works with|jq}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
'''Works with gojq, the Go implementation of jq'''
<syntaxhighlight lang=jq>def encrypt(key):
<syntaxhighlight lang="jq">def encrypt(key):
. as $s
. as $s
| explode as $xs
| explode as $xs
Line 3,762: Line 3,694:
Bright vixens jump; dozy fowl quack.
Bright vixens jump; dozy fowl quack.
</pre>
</pre>


=={{header|Jsish}}==
=={{header|Jsish}}==
From Typescript entry.
From Typescript entry.
<syntaxhighlight lang=javascript>/* Caesar cipher, in Jsish */
<syntaxhighlight lang="javascript">/* Caesar cipher, in Jsish */
"use strict";
"use strict";


Line 3,803: Line 3,733:
<pre>prompt$ jsish -u caesarCipher.jsi
<pre>prompt$ jsish -u caesarCipher.jsi
[PASS] caesarCipher.jsi</pre>
[PASS] caesarCipher.jsi</pre>

=={{header|Julia}}==
=={{header|Julia}}==
===updated version for Julia 1.x | Rename isalpha to isletter #27077 | https://github.com/JuliaLang/julia/pull/27077===
===updated version for Julia 1.x | Rename isalpha to isletter #27077 | https://github.com/JuliaLang/julia/pull/27077===


<syntaxhighlight lang=julia>
<syntaxhighlight lang="julia">
# Caeser cipher
# Caeser cipher
# Julia 1.5.4
# Julia 1.5.4
Line 3,845: Line 3,774:
"Zntvp Rapelcgvba"
"Zntvp Rapelcgvba"
</pre>
</pre>

=={{header|K}}==
=={{header|K}}==


Assumes lowercase letters, and no punctuation.
Assumes lowercase letters, and no punctuation.


<syntaxhighlight lang=k>
<syntaxhighlight lang="k">
s:"there is a tide in the affairs of men"
s:"there is a tide in the affairs of men"
caesar:{ :[" "=x; x; {x!_ci 97+!26}[y]@_ic[x]-97]}'
caesar:{ :[" "=x; x; {x!_ci 97+!26}[y]@_ic[x]-97]}'
Line 3,856: Line 3,784:
"uifsf jt b ujef jo uif bggbjst pg nfo"
"uifsf jt b ujef jo uif bggbjst pg nfo"
</syntaxhighlight>
</syntaxhighlight>

=={{header|Kotlin}}==
=={{header|Kotlin}}==
<syntaxhighlight lang=scala>// version 1.0.5-2
<syntaxhighlight lang="scala">// version 1.0.5-2


object Caesar {
object Caesar {
Line 3,899: Line 3,826:
Bright vixens jump; dozy fowl quack.
Bright vixens jump; dozy fowl quack.
</pre>
</pre>

=={{header|LabVIEW}}==
=={{header|LabVIEW}}==
For readability, input is in all caps.<br/>{{VI snippet}}<br/>[[File:LabVIEW_Caesar_cipher.png]]
For readability, input is in all caps.<br/>{{VI snippet}}<br/>[[File:LabVIEW_Caesar_cipher.png]]

=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
The caesar function encodes and decodes texts containing exclusively the set [ABCDEFGHIJKLMNOPQRSTUVWXZ].
The caesar function encodes and decodes texts containing exclusively the set [ABCDEFGHIJKLMNOPQRSTUVWXZ].
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
{def caesar
{def caesar


Line 3,976: Line 3,901:


</syntaxhighlight>
</syntaxhighlight>

=={{header|langur}}==
=={{header|langur}}==
Using the built-in rotate() function on a number over a range, a number outside of the range will pass through unaltered.
Using the built-in rotate() function on a number over a range, a number outside of the range will pass through unaltered.


<syntaxhighlight lang=langur>val .rot = f(.s, .key) {
<syntaxhighlight lang="langur">val .rot = f(.s, .key) {
cp2s map(f(.c) rotate(rotate(.c, .key, 'a'..'z'), .key, 'A'..'Z'), s2cp .s)
cp2s map(f(.c) rotate(rotate(.c, .key, 'a'..'z'), .key, 'A'..'Z'), s2cp .s)
}
}
Line 3,995: Line 3,919:
encrypted: X nrfzh yoltk clu grjmba lsbo pljbqefkd.
encrypted: X nrfzh yoltk clu grjmba lsbo pljbqefkd.
decrypted: A quick brown fox jumped over something.</pre>
decrypted: A quick brown fox jumped over something.</pre>

=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang=lb>key = 7
<syntaxhighlight lang="lb">key = 7


Print "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Print "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 4,021: Line 3,944:
Next i
Next i
End Function</syntaxhighlight>
End Function</syntaxhighlight>

=={{header|LiveCode}}==
=={{header|LiveCode}}==
<syntaxhighlight lang=LiveCode>function caesarCipher rot phrase
<syntaxhighlight lang="livecode">function caesarCipher rot phrase
local rotPhrase, lowerLetters, upperLetters
local rotPhrase, lowerLetters, upperLetters
put "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" into lowerLetters
put "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" into lowerLetters
Line 4,039: Line 3,961:
return rotPhrase
return rotPhrase
end caesarCipher</syntaxhighlight>
end caesarCipher</syntaxhighlight>

=={{header|Logo}}==
=={{header|Logo}}==
{{trans|Common Lisp}}
{{trans|Common Lisp}}
{{works with|UCB Logo}}
{{works with|UCB Logo}}
<syntaxhighlight lang=logo>; some useful constants
<syntaxhighlight lang="logo">; some useful constants
make "lower_a ascii "a
make "lower_a ascii "a
make "lower_z ascii "z
make "lower_z ascii "z
Line 4,082: Line 4,003:
Encrypted: Wkh ilyh eralqj zlcdugv mxps txlfnob
Encrypted: Wkh ilyh eralqj zlcdugv mxps txlfnob
Recovered: The five boxing wizards jump quickly</pre>
Recovered: The five boxing wizards jump quickly</pre>

=={{header|Lua}}==
=={{header|Lua}}==


<syntaxhighlight lang=Lua>local function encrypt(text, key)
<syntaxhighlight lang="lua">local function encrypt(text, key)
return text:gsub("%a", function(t)
return text:gsub("%a", function(t)
local base = (t:lower() == t and string.byte('a') or string.byte('A'))
local base = (t:lower() == t and string.byte('a') or string.byte('A'))
Line 4,119: Line 4,039:


'''Fast version'''
'''Fast version'''
<syntaxhighlight lang=Lua>local memo = {}
<syntaxhighlight lang="lua">local memo = {}


local function make_table(k)
local function make_table(k)
Line 4,151: Line 4,071:
return string.char(unpack(res_t))
return string.char(unpack(res_t))
end</syntaxhighlight>
end</syntaxhighlight>

=={{header|M2000 Interpreter}}==
=={{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.
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>
<syntaxhighlight lang="m2000 interpreter">
a$="THIS IS MY TEXT TO ENCODE WITH CAESAR CIPHER"
a$="THIS IS MY TEXT TO ENCODE WITH CAESAR CIPHER"
Function Cipher$(a$, N) {
Function Cipher$(a$, N) {
Line 4,174: Line 4,093:


</syntaxhighlight>
</syntaxhighlight>

=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang=Maple>
<syntaxhighlight lang="maple">
> StringTools:-Encode( "The five boxing wizards jump quickly", encoding = alpharot[3] );
> StringTools:-Encode( "The five boxing wizards jump quickly", encoding = alpharot[3] );
"Wkh ilyh eralqj zlcdugv mxps txlfnob"
"Wkh ilyh eralqj zlcdugv mxps txlfnob"
Line 4,184: Line 4,102:
</syntaxhighlight>
</syntaxhighlight>
(The symbol % refers the the last (non-NULL) value computed.)
(The symbol % refers the the last (non-NULL) value computed.)

=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica>cypher[mesg_String,n_Integer]:=StringReplace[mesg,Flatten[Thread[Rule[#,RotateLeft[#,n]]]&/@CharacterRange@@@{{"a","z"},{"A","Z"}}]]</syntaxhighlight>
<syntaxhighlight lang="mathematica">cypher[mesg_String,n_Integer]:=StringReplace[mesg,Flatten[Thread[Rule[#,RotateLeft[#,n]]]&/@CharacterRange@@@{{"a","z"},{"A","Z"}}]]</syntaxhighlight>
{{out}}
{{out}}
<pre>cypher["The five boxing wizards jump quickly",3]
<pre>cypher["The five boxing wizards jump quickly",3]
-> Wkh ilyh eralqj zlcdugv mxps txlfnob</pre>
-> Wkh ilyh eralqj zlcdugv mxps txlfnob</pre>

=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang=Matlab> function s = cipherCaesar(s, key)
<syntaxhighlight lang="matlab"> function s = cipherCaesar(s, key)
s = char( mod(s - 'A' + key, 25 ) + 'A');
s = char( mod(s - 'A' + key, 25 ) + 'A');
end;
end;
Line 4,199: Line 4,115:
end; </syntaxhighlight>
end; </syntaxhighlight>
Here is a test:
Here is a test:
<syntaxhighlight lang=Matlab> decipherCaesar(cipherCaesar('ABC',4),4)
<syntaxhighlight lang="matlab"> decipherCaesar(cipherCaesar('ABC',4),4)
ans = ABC </syntaxhighlight>
ans = ABC </syntaxhighlight>

=={{header|Microsoft Small Basic}}==
=={{header|Microsoft Small Basic}}==
<syntaxhighlight lang=Microsoft Small Basic>
<syntaxhighlight lang="microsoft small basic">
TextWindow.Write("Enter a 1-25 number key (-ve number to decode): ")
TextWindow.Write("Enter a 1-25 number key (-ve number to decode): ")
key = TextWindow.ReadNumber()
key = TextWindow.ReadNumber()
Line 4,241: Line 4,156:
Press any key to continue...
Press any key to continue...
</pre>
</pre>

=={{header|MiniScript}}==
=={{header|MiniScript}}==
<syntaxhighlight lang=MiniScript>caesar = function(s, key)
<syntaxhighlight lang="miniscript">caesar = function(s, key)
chars = s.values
chars = s.values
for i in chars.indexes
for i in chars.indexes
Line 4,259: Line 4,173:
<pre>Olssv dvysk!
<pre>Olssv dvysk!
Hello world!</pre>
Hello world!</pre>

=={{header|ML}}==
=={{header|ML}}==
==={{header|mLite}}===
==={{header|mLite}}===
In this implementation, the offset can be positive or negative and is wrapped around if greater than 25 or less than -25.
In this implementation, the offset can be positive or negative and is wrapped around if greater than 25 or less than -25.
<syntaxhighlight lang=ocaml>fun readfile () = readfile []
<syntaxhighlight lang="ocaml">fun readfile () = readfile []
| x = let val ln = readln ()
| x = let val ln = readln ()
in if eof ln then
in if eof ln then
Line 4,308: Line 4,221:
Output:
Output:
<pre>Ocz xvo nvo ji ocz hvo</pre>
<pre>Ocz xvo nvo ji ocz hvo</pre>

=={{header|Modula-2}}==
=={{header|Modula-2}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=modula2>MODULE CaesarCipher;
<syntaxhighlight lang="modula2">MODULE CaesarCipher;
FROM Conversions IMPORT IntToStr;
FROM Conversions IMPORT IntToStr;
FROM Terminal IMPORT WriteString, WriteLn, ReadChar;
FROM Terminal IMPORT WriteString, WriteLn, ReadChar;
Line 4,388: Line 4,300:
ReadChar;
ReadChar;
END CaesarCipher.</syntaxhighlight>
END CaesarCipher.</syntaxhighlight>

=={{header|Modula-3}}==
=={{header|Modula-3}}==
This implementation distinguishes between "encoding" and "encryption."
This implementation distinguishes between "encoding" and "encryption."
Line 4,396: Line 4,307:
It also illustrates the use of exceptions in Modula-3.
It also illustrates the use of exceptions in Modula-3.


<syntaxhighlight lang=modula3>MODULE Caesar EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE Caesar EXPORTS Main;


IMPORT IO, IntSeq, Text;
IMPORT IO, IntSeq, Text;
Line 4,488: Line 4,399:
whencaesarsetofftogaul
whencaesarsetofftogaul
</pre>
</pre>

=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<syntaxhighlight lang=Nanoquery>def caesar_encode(plaintext, shift)
<syntaxhighlight lang="nanoquery">def caesar_encode(plaintext, shift)
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercase = "abcdefghijklmnopqrstuvwxyz"
lowercase = "abcdefghijklmnopqrstuvwxyz"
Line 4,525: Line 4,435:
return plaintext
return plaintext
end</syntaxhighlight>
end</syntaxhighlight>

=={{header|NetRexx}}==
=={{header|NetRexx}}==
The cipher code in this sample is also used in the [[Rot-13#NetRexx|Rot-13&nbsp;&ndash;&nbsp;NetRexx]] task.
The cipher code in this sample is also used in the [[Rot-13#NetRexx|Rot-13&nbsp;&ndash;&nbsp;NetRexx]] task.
<syntaxhighlight lang=NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */


options replace format comments java crossref savelog symbols nobinary
options replace format comments java crossref savelog symbols nobinary
Line 4,712: Line 4,621:
HI
HI
</pre>
</pre>

=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Python}}
{{trans|Python}}
<syntaxhighlight lang=nim>import strutils
<syntaxhighlight lang="nim">import strutils


proc caesar(s: string, k: int, decode = false): string =
proc caesar(s: string, k: int, decode = false): string =
Line 4,729: Line 4,637:
echo enc
echo enc
echo caesar(enc, 11, decode = true)</syntaxhighlight>
echo caesar(enc, 11, decode = true)</syntaxhighlight>

=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Works with oo2c version2
Works with oo2c version2
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
MODULE Caesar;
MODULE Caesar;
IMPORT
IMPORT
Line 4,799: Line 4,706:
The five boxing wizards jump quickly =e=> Wkh ilyh eralqj zlcdugv mxps txlfnob =d=> The five boxing wizards jump quickly
The five boxing wizards jump quickly =e=> Wkh ilyh eralqj zlcdugv mxps txlfnob =d=> The five boxing wizards jump quickly
</pre>
</pre>

=={{header|Objeck}}==
=={{header|Objeck}}==
<syntaxhighlight lang=objeck>
<syntaxhighlight lang="objeck">
class Caesar {
class Caesar {
function : native : Encode(enc : String, offset : Int) ~ String {
function : native : Encode(enc : String, offset : Int) ~ String {
Line 4,837: Line 4,743:
the quick brown fox jumped over the lazy dog
the quick brown fox jumped over the lazy dog
</pre>
</pre>

=={{header|OCaml}}==
=={{header|OCaml}}==
<syntaxhighlight lang=ocaml>let islower c =
<syntaxhighlight lang="ocaml">let islower c =
c >= 'a' && c <= 'z'
c >= 'a' && c <= 'z'


Line 4,864: Line 4,769:
c
c
) str</syntaxhighlight>
) str</syntaxhighlight>
<syntaxhighlight lang=ocaml>let () =
<syntaxhighlight lang="ocaml">let () =
let key = 3 in
let key = 3 in
let orig = "The five boxing wizards jump quickly" in
let orig = "The five boxing wizards jump quickly" in
Line 4,878: Line 4,783:
The five boxing wizards jump quickly
The five boxing wizards jump quickly
equal: true</pre>
equal: true</pre>

=={{header|Oforth}}==
=={{header|Oforth}}==


<syntaxhighlight lang=Oforth>: ceasar(c, key)
<syntaxhighlight lang="oforth">: ceasar(c, key)
c dup isLetter ifFalse: [ return ]
c dup isLetter ifFalse: [ return ]
isUpper ifTrue: [ 'A' ] else: [ 'a' ] c key + over - 26 mod + ;
isUpper ifTrue: [ 'A' ] else: [ 'a' ] c key + over - 26 mod + ;
Line 4,896: Line 4,800:
Pack my box with five dozen liquor jugs.
Pack my box with five dozen liquor jugs.
</pre>
</pre>

=={{header|OOC}}==
=={{header|OOC}}==
<syntaxhighlight lang=ooc>main: func (args: String[]) {
<syntaxhighlight lang="ooc">main: func (args: String[]) {
shift := args[1] toInt()
shift := args[1] toInt()
if (args length != 3) {
if (args length != 3) {
Line 4,922: Line 4,825:
$ ./caesar -9 "Yet another, fairly original sentence!"
$ ./caesar -9 "Yet another, fairly original sentence!"
Pvk refkyvi, wrzicp fizxzerc jvekvetv!</pre>
Pvk refkyvi, wrzicp fizxzerc jvekvetv!</pre>

=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<syntaxhighlight lang=parigp>enc(s,n)={
<syntaxhighlight 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)),
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)))))
Vec(Vecsmall(s)))))
};
};
dec(s,n)=enc(s,-n);</syntaxhighlight>
dec(s,n)=enc(s,-n);</syntaxhighlight>

=={{header|Pascal}}==
=={{header|Pascal}}==
<syntaxhighlight lang=pascal>Program CaesarCipher(output);
<syntaxhighlight lang="pascal">Program CaesarCipher(output);


procedure encrypt(var message: string; key: integer);
procedure encrypt(var message: string; key: integer);
Line 4,975: Line 4,876:
Decrypted message: The five boxing wizards jump quickly
Decrypted message: The five boxing wizards jump quickly
>: </pre>
>: </pre>

=={{header|Perl}}==
=={{header|Perl}}==


<syntaxhighlight lang=Perl>sub caesar {
<syntaxhighlight lang="perl">sub caesar {
my ($message, $key, $decode) = @_;
my ($message, $key, $decode) = @_;
$key = 26 - $key if $decode;
$key = 26 - $key if $decode;
Line 4,995: Line 4,895:
enc: DRO PSFO LYHSXQ GSJKBNC TEWZ AESMUVI
enc: DRO PSFO LYHSXQ GSJKBNC TEWZ AESMUVI
dec: THE FIVE BOXING WIZARDS JUMP QUICKLY</pre>
dec: THE FIVE BOXING WIZARDS JUMP QUICKLY</pre>

=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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,026: Line 4,925:
Back to back they faced each other, drew their swords and shot each other. %^&*()[
Back to back they faced each other, drew their swords and shot each other. %^&*()[
</pre>
</pre>

=={{header|PHP}}==
=={{header|PHP}}==
<syntaxhighlight lang=php><?php
<syntaxhighlight lang="php"><?php
function caesarEncode( $message, $key ){
function caesarEncode( $message, $key ){
$plaintext = strtolower( $message );
$plaintext = strtolower( $message );
Line 5,052: Line 4,950:
Or, using PHP's '''strtr()''' built-in function
Or, using PHP's '''strtr()''' built-in function


<syntaxhighlight lang=php><?php
<syntaxhighlight lang="php"><?php


function caesarEncode($message, $key) {
function caesarEncode($message, $key) {
Line 5,064: Line 4,962:
{{out}}
{{out}}
<pre>FTQ CGUOW NDAIZ RAJ VGYBQP AHQD FTQ XMLK PAS</pre>
<pre>FTQ CGUOW NDAIZ RAJ VGYBQP AHQD FTQ XMLK PAS</pre>

=={{header|Picat}}==
=={{header|Picat}}==
<syntaxhighlight lang=Picat>main =>
<syntaxhighlight lang="picat">main =>
S = "All human beings are born free and equal in dignity and rights.",
S = "All human beings are born free and equal in dignity and rights.",
println(S),
println(S),
Line 5,096: Line 4,993:
Fqq mzrfs gjnslx fwj gtws kwjj fsi jvzfq ns inlsnyd fsi wnlmyx.
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>
All human beings are born free and equal in dignity and rights.</pre>

=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp>(setq *Letters (apply circ (mapcar char (range 65 90))))
<syntaxhighlight lang="picolisp">(setq *Letters (apply circ (mapcar char (range 65 90))))


(de caesar (Str Key)
(de caesar (Str Key)
Line 5,114: Line 5,010:
: (caesar @ (- 26 7))
: (caesar @ (- 26 7))
-> "THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGSBACK"</pre>
-> "THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGSBACK"</pre>

=={{header|Pike}}==
=={{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.
Pike has built in support for substitution cryptos in the Crypto module. It's possible to set the desired alphabet, but the default a-z matches the Caesar range.
<syntaxhighlight lang=Pike>object c = Crypto.Substitution()->set_rot_key(2);
<syntaxhighlight lang="pike">object c = Crypto.Substitution()->set_rot_key(2);
string msg = "The quick brown fox jumped over the lazy dogs";
string msg = "The quick brown fox jumped over the lazy dogs";
string msg_s2 = c->encrypt(msg);
string msg_s2 = c->encrypt(msg);
Line 5,133: Line 5,028:
The quick brown fox jumped over the lazy dogs
The quick brown fox jumped over the lazy dogs
</pre>
</pre>

=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang=pli>caesar: procedure options (main);
<syntaxhighlight lang="pli">caesar: procedure options (main);
declare cypher_string character (52) static initial
declare cypher_string character (52) static initial
((2)'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
((2)'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
Line 5,161: Line 5,055:
Decyphered text= THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG
Decyphered text= THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG
</pre>
</pre>

=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang=Powershell># Author: M. McNabb
<syntaxhighlight lang="powershell"># Author: M. McNabb
function Get-CaesarCipher
function Get-CaesarCipher
{
{
Line 5,254: Line 5,147:
Vsxo drboo;
Vsxo drboo;
</pre>
</pre>

=={{header|Prolog}}==
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}
{{Works with|SWI-Prolog}}
{{libheader|clpfd}}
{{libheader|clpfd}}
<syntaxhighlight lang=Prolog>:- use_module(library(clpfd)).
<syntaxhighlight lang="prolog">:- use_module(library(clpfd)).


caesar :-
caesar :-
Line 5,298: Line 5,190:
true .
true .
</pre>
</pre>

=={{header|PureBasic}}==
=={{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.
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=PureBasic>Procedure.s CC_encrypt(plainText.s, key, reverse = 0)
<syntaxhighlight lang="purebasic">Procedure.s CC_encrypt(plainText.s, key, reverse = 0)
;if reverse <> 0 then reverse the encryption (decrypt)
;if reverse <> 0 then reverse the encryption (decrypt)
If reverse: reverse = 26: key = 26 - key: EndIf
If reverse: reverse = 26: key = 26 - key: EndIf
Line 5,344: Line 5,235:
===Alternate solution===
===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.
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.
<syntaxhighlight lang=PureBasic>Procedure.s CC_encrypt(text.s, key, reverse = 0)
<syntaxhighlight lang="purebasic">Procedure.s CC_encrypt(text.s, key, reverse = 0)
;if reverse <> 0 then reverse the encryption (decrypt)
;if reverse <> 0 then reverse the encryption (decrypt)
Protected i, *letter.Character, *resultLetter.Character, result.s = Space(Len(text))
Protected i, *letter.Character, *resultLetter.Character, result.s = Space(Len(text))
Line 5,365: Line 5,256:
ProcedureReturn result
ProcedureReturn result
EndProcedure</syntaxhighlight>
EndProcedure</syntaxhighlight>

=={{header|Python}}==
=={{header|Python}}==
<syntaxhighlight lang=Python>def caesar(s, k, decode = False):
<syntaxhighlight lang="python">def caesar(s, k, decode = False):
if decode: k = 26 - k
if decode: k = 26 - k
return "".join([chr((ord(i) - 65 + k) % 26 + 65)
return "".join([chr((ord(i) - 65 + k) % 26 + 65)
Line 5,384: Line 5,274:
Alternate solution
Alternate solution
{{works with|Python|2.x}} (for 3.x change <code>string.maketrans</code> to <code>str.maketrans</code>)
{{works with|Python|2.x}} (for 3.x change <code>string.maketrans</code> to <code>str.maketrans</code>)
<syntaxhighlight lang=python>import string
<syntaxhighlight lang="python">import string
def caesar(s, k, decode = False):
def caesar(s, k, decode = False):
if decode: k = 26 - k
if decode: k = 26 - k
Line 5,408: Line 5,298:
Variant with memoization of translation tables
Variant with memoization of translation tables
{{works with|Python|3.x}}
{{works with|Python|3.x}}
<syntaxhighlight lang=python>import string
<syntaxhighlight lang="python">import string
def caesar(s, k = 13, decode = False, *, memo={}):
def caesar(s, k = 13, decode = False, *, memo={}):
if decode: k = 26 - k
if decode: k = 26 - k
Line 5,421: Line 5,311:


A compact alternative solution
A compact alternative solution
<syntaxhighlight lang=python>
<syntaxhighlight lang="python">
from string import ascii_uppercase as abc
from string import ascii_uppercase as abc


Line 5,437: Line 5,327:
THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGS
THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOGS
</pre>
</pre>


=={{header|QBasic}}==
=={{header|QBasic}}==
{{works with|QBasic}}
{{works with|QBasic}}
Line 5,444: Line 5,332:
{{works with|True BASIC}} Note that TrueBasic uses '!' for comments
{{works with|True BASIC}} Note that TrueBasic uses '!' for comments
{{trans|BASIC256}}
{{trans|BASIC256}}
<syntaxhighlight lang=QBasic>LET dec$ = ""
<syntaxhighlight lang="qbasic">LET dec$ = ""
LET tipo$ = "cleartext "
LET tipo$ = "cleartext "


Line 5,476: Line 5,364:
NEXT i
NEXT i
END</syntaxhighlight>
END</syntaxhighlight>

=={{header|Quackery}}==
=={{header|Quackery}}==
<syntaxhighlight lang=Quackery> [ dup upper != ] is lower? ( c --> b )
<syntaxhighlight lang="quackery"> [ dup upper != ] is lower? ( c --> b )


[ dup lower != ] is upper? ( c --> b )
[ dup lower != ] is upper? ( c --> b )
Line 5,507: Line 5,394:
Cbob ifybkqbo eljfkbp fa nrla slirkq zobarkq.
Cbob ifybkqbo eljfkbp fa nrla slirkq zobarkq.
Fere libenter homines id quod volunt credunt.</pre>
Fere libenter homines id quod volunt credunt.</pre>

=={{header|R}}==
=={{header|R}}==
This is a generalization of the Rot-13 solution for R at: http://rosettacode.org/wiki/Rot-13#R .
This is a generalization of the Rot-13 solution for R at: http://rosettacode.org/wiki/Rot-13#R .
<syntaxhighlight lang=R>
<syntaxhighlight lang="r">
# based on Rot-13 solution: http://rosettacode.org/wiki/Rot-13#R
# based on Rot-13 solution: http://rosettacode.org/wiki/Rot-13#R
ceasar <- function(x, key)
ceasar <- function(x, key)
Line 5,553: Line 5,439:
[1] "Decrypted Text: The five boxing wizards jump quickly."
[1] "Decrypted Text: The five boxing wizards jump quickly."
</pre>
</pre>

=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang=racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
Line 5,584: Line 5,469:
"The five boxing wizards jump quickly."
"The five boxing wizards jump quickly."
</pre>
</pre>

=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang=raku line>my @alpha = 'A' .. 'Z';
<syntaxhighlight lang="raku" line>my @alpha = 'A' .. 'Z';
sub encrypt ( $key where 1..25, $plaintext ) {
sub encrypt ( $key where 1..25, $plaintext ) {
$plaintext.trans( @alpha Z=> @alpha.rotate($key) );
$plaintext.trans( @alpha Z=> @alpha.rotate($key) );
Line 5,608: Line 5,492:
THE FIVE BOXING WIZARDS JUMP QUICKLY
THE FIVE BOXING WIZARDS JUMP QUICKLY
OK</pre>
OK</pre>

=={{header|Red}}==
=={{header|Red}}==
<syntaxhighlight lang=red>
<syntaxhighlight lang="red">
Red ["Ceasar Cipher"]
Red ["Ceasar Cipher"]


Line 5,646: Line 5,529:
>>
>>
</pre>
</pre>

=={{header|Retro}}==
=={{header|Retro}}==
Retro provides a number of classical cyphers in the '''crypto'''' library. This implementation is from the library.
Retro provides a number of classical cyphers in the '''crypto'''' library. This implementation is from the library.
<syntaxhighlight lang=Retro>{{
<syntaxhighlight lang="retro">{{
variable offset
variable offset
: rotate ( cb-c ) tuck - @offset + 26 mod + ;
: rotate ( cb-c ) tuck - @offset + 26 mod + ;
Line 5,663: Line 5,545:
"THEYBROKEOURCIPHEREVERYONECANREADTHIS" 3 ceaser ( returns encrypted string )
"THEYBROKEOURCIPHEREVERYONECANREADTHIS" 3 ceaser ( returns encrypted string )
23 ceaser ( returns decrypted string )</syntaxhighlight>
23 ceaser ( returns decrypted string )</syntaxhighlight>

=={{header|REXX}}==
=={{header|REXX}}==
===only Latin letters===
===only Latin letters===
This version conforms to the task's restrictions.
This version conforms to the task's restrictions.
<syntaxhighlight lang=rexx>/*REXX program supports the Caesar cypher for the Latin alphabet only, no punctuation */
<syntaxhighlight lang="rexx">/*REXX program supports the Caesar cypher for the Latin alphabet only, no punctuation */
/*──────────── or blanks allowed, all lowercase Latin letters are treated as uppercase.*/
/*──────────── or blanks allowed, all lowercase Latin letters are treated as uppercase.*/
parse arg key .; arg . p /*get key & uppercased text to be used.*/
parse arg key .; arg . p /*get key & uppercased text to be used.*/
Line 5,700: Line 5,581:
This version allows upper and lowercase Latin alphabet as well as all the
This version allows upper and lowercase Latin alphabet as well as all the
characters on the standard (computer) keyboard including blanks.
characters on the standard (computer) keyboard including blanks.
<syntaxhighlight lang=rexx>/*REXX program supports the Caesar cypher for most keyboard characters including blanks.*/
<syntaxhighlight lang="rexx">/*REXX program supports the Caesar cypher for most keyboard characters including blanks.*/
parse arg key p /*get key and the text to be cyphered. */
parse arg key p /*get key and the text to be cyphered. */
say 'Caesar cypher key:' key /*echo the Caesar cypher key to console*/
say 'Caesar cypher key:' key /*echo the Caesar cypher key to console*/
Line 5,729: Line 5,610:
uncyphered: Batman's hood is called a "cowl" (old meaning).
uncyphered: Batman's hood is called a "cowl" (old meaning).
</pre>
</pre>

=={{header|Ring}}==
=={{header|Ring}}==
<syntaxhighlight lang=ring>
<syntaxhighlight lang="ring">
# Project : Caesar cipher
# Project : Caesar cipher


Line 5,803: Line 5,683:
pack my box with five dozen liquor jugs
pack my box with five dozen liquor jugs
</pre>
</pre>

=={{header|Ruby}}==
=={{header|Ruby}}==
<syntaxhighlight lang=ruby>class String
<syntaxhighlight lang="ruby">class String
ALFABET = ("A".."Z").to_a
ALFABET = ("A".."Z").to_a


Line 5,818: Line 5,697:
decrypted = encypted.caesar_cipher(-3)
decrypted = encypted.caesar_cipher(-3)
</syntaxhighlight>
</syntaxhighlight>

=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<syntaxhighlight lang=runbasic>input "Gimme a ofset:";ofst ' set any offset you like
<syntaxhighlight lang="runbasic">input "Gimme a ofset:";ofst ' set any offset you like


a$ = "Pack my box with five dozen liquor jugs"
a$ = "Pack my box with five dozen liquor jugs"
Line 5,846: Line 5,724:
Encrypted: Zkmu wi lyh gsdr psfo nyjox vsaeyb teqc
Encrypted: Zkmu wi lyh gsdr psfo nyjox vsaeyb teqc
Decrypted: Pack my box with five dozen liquor jugs</pre>
Decrypted: Pack my box with five dozen liquor jugs</pre>

=={{header|Rust}}==
=={{header|Rust}}==
This example shows proper error handling. It skips non-ASCII characters.
This example shows proper error handling. It skips non-ASCII characters.
<syntaxhighlight lang=rust>use std::io::{self, Write};
<syntaxhighlight lang="rust">use std::io::{self, Write};
use std::fmt::Display;
use std::fmt::Display;
use std::{env, process};
use std::{env, process};
Line 5,885: Line 5,762:
process::exit(code);
process::exit(code);
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Scala}}==
=={{header|Scala}}==
<syntaxhighlight lang=scala>object Caesar {
<syntaxhighlight lang="scala">object Caesar {
private val alphaU='A' to 'Z'
private val alphaU='A' to 'Z'
private val alphaL='a' to 'z'
private val alphaL='a' to 'z'
Line 5,899: Line 5,775:
private def rot(a:IndexedSeq[Char], c:Char, key:Int)=a((c-a.head+key+a.size)%a.size)
private def rot(a:IndexedSeq[Char], c:Char, key:Int)=a((c-a.head+key+a.size)%a.size)
}</syntaxhighlight>
}</syntaxhighlight>
<syntaxhighlight lang=scala>val text="The five boxing wizards jump quickly"
<syntaxhighlight lang="scala">val text="The five boxing wizards jump quickly"
println("Plaintext => " + text)
println("Plaintext => " + text)
val encoded=Caesar.encode(text, 3)
val encoded=Caesar.encode(text, 3)
Line 5,912: Line 5,788:
This version first creates non shifted and shifted character sequences
This version first creates non shifted and shifted character sequences
and then encodes and decodes by indexing between those sequences.
and then encodes and decodes by indexing between those sequences.
<syntaxhighlight lang=scala>class Caeser(val key: Int) {
<syntaxhighlight lang="scala">class Caeser(val key: Int) {
@annotation.tailrec
@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)
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,925: Line 5,801:
}</syntaxhighlight>
}</syntaxhighlight>


<syntaxhighlight lang=scala>val text = "The five boxing wizards jump quickly"
<syntaxhighlight lang="scala">val text = "The five boxing wizards jump quickly"
val myCaeser = new Caeser(3)
val myCaeser = new Caeser(3)
val encoded = text.map(c => myCaeser.encode(c))
val encoded = text.map(c => myCaeser.encode(c))
Line 5,936: Line 5,812:
Ciphertext => Wkh ilyh eralqj zlcdugv mxps txlfnob
Ciphertext => Wkh ilyh eralqj zlcdugv mxps txlfnob
Decrypted => The five boxing wizards jump quickly</pre>
Decrypted => The five boxing wizards jump quickly</pre>

=={{header|Scheme}}==
=={{header|Scheme}}==


<syntaxhighlight lang=scheme>;
<syntaxhighlight lang="scheme">;
; Works with R7RS-compatible Schemes (e.g. Chibi).
; Works with R7RS-compatible Schemes (e.g. Chibi).
; Also current versions of Chicken, Gauche and Kawa.
; Also current versions of Chicken, Gauche and Kawa.
Line 5,972: Line 5,847:
Gur dhvpx oebja sbk whzcf bire gur ynml qbt.
Gur dhvpx oebja sbk whzcf bire gur ynml qbt.
</pre>
</pre>

=={{header|sed}}==
=={{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.
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.
<syntaxhighlight lang=sed>#!/bin/sed -rf
<syntaxhighlight lang="sed">#!/bin/sed -rf
# Input: <number 0..25>\ntext to encode
# Input: <number 0..25>\ntext to encode


Line 6,024: Line 5,898:
Error: Key must be <= 25
Error: Key must be <= 25
</pre>
</pre>

=={{header|Seed7}}==
=={{header|Seed7}}==
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const func string: rot (in string: stri, in integer: encodingKey) is func
const func string: rot (in string: stri, in integer: encodingKey) is func
Line 6,061: Line 5,934:
Decrypted: The five boxing wizards jump quickly
Decrypted: The five boxing wizards jump quickly
</pre>
</pre>

=={{header|SequenceL}}==
=={{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.
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.
<syntaxhighlight lang=sequencel>import <Utilities/Sequence.sl>;
<syntaxhighlight lang="sequencel">import <Utilities/Sequence.sl>;
import <Utilities/Conversion.sl>;
import <Utilities/Conversion.sl>;


Line 6,103: Line 5,975:
Decrypted: Pack my box with five dozen liquor jugs."
Decrypted: Pack my box with five dozen liquor jugs."
</pre>
</pre>

=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<syntaxhighlight lang=ruby>func caesar(msg, key, decode=false) {
<syntaxhighlight lang="ruby">func caesar(msg, key, decode=false) {
decode && (key = (26 - key));
decode && (key = (26 - key));
msg.gsub(/([A-Z])/i, {|c| ((c.uc.ord - 65 + key) % 26) + 65 -> chr});
msg.gsub(/([A-Z])/i, {|c| ((c.uc.ord - 65 + key) % 26) + 65 -> chr});
Line 6,126: Line 5,997:
dec: THE FIVE BOXING WIZARDS JUMP QUICKLY
dec: THE FIVE BOXING WIZARDS JUMP QUICKLY
</pre>
</pre>

=={{header|Sinclair ZX81 BASIC}}==
=={{header|Sinclair ZX81 BASIC}}==
Works with 1k of RAM. A negative key decodes.
Works with 1k of RAM. A negative key decodes.
<syntaxhighlight lang=basic> 10 INPUT KEY
<syntaxhighlight lang="basic"> 10 INPUT KEY
20 INPUT T$
20 INPUT T$
30 LET C$=""
30 LET C$=""
Line 6,152: Line 6,022:
{{out}}
{{out}}
<pre>GALLIA EST OMNIS DIVISA IN PARTES TRES</pre>
<pre>GALLIA EST OMNIS DIVISA IN PARTES TRES</pre>

=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
well, I'm lucky: the standard library already contains a rot:n method!
well, I'm lucky: the standard library already contains a rot:n method!
<syntaxhighlight lang=Smalltalk>'THE QUICK BROWN FOX' rot:3 -> 'WKH TXLFN EURZQ IRA' </syntaxhighlight>
<syntaxhighlight lang="smalltalk">'THE QUICK BROWN FOX' rot:3 -> 'WKH TXLFN EURZQ IRA' </syntaxhighlight>
but if it wasn't, here is an implementation for other smalltalks:
but if it wasn't, here is an implementation for other smalltalks:
<syntaxhighlight lang=smalltalk>
<syntaxhighlight lang="smalltalk">
!CharacterArray methodsFor:'encoding'!
!CharacterArray methodsFor:'encoding'!
rot:n
rot:n
Line 6,179: Line 6,048:


</syntaxhighlight>
</syntaxhighlight>

=={{header|SSEM}}==
=={{header|SSEM}}==
ASCII didn't exit in 1948, and the task specification explicitly says we only need to convert Roman capitals; so we adopt a simpler encoding, representing the letters of the alphabet from <tt>A</tt>=0 to <tt>Z</tt>=25.
ASCII didn't exit in 1948, and the task specification explicitly says we only need to convert Roman capitals; so we adopt a simpler encoding, representing the letters of the alphabet from <tt>A</tt>=0 to <tt>Z</tt>=25.
Line 6,186: Line 6,054:


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.
This is in fact a general solution that will work equally well with alphabets of more or fewer than 26 characters: simply replace the constant 26 in storage address 18 with 22 for Hebrew, 24 for Greek, 28 for Arabic, 33 for Russian, etc.
<syntaxhighlight lang=ssem>00101000000000100000000000000000 0. -20 to c
<syntaxhighlight lang="ssem">00101000000000100000000000000000 0. -20 to c
11001000000000010000000000000000 1. Sub. 19
11001000000000010000000000000000 1. Sub. 19
10101000000001100000000000000000 2. c to 21
10101000000001100000000000000000 2. c to 21
Line 6,205: Line 6,073:
11010000000000000000000000000000 17. 11
11010000000000000000000000000000 17. 11
01011000000000000000000000000000 18. 26</syntaxhighlight>
01011000000000000000000000000000 18. 26</syntaxhighlight>

=={{header|Stata}}==
=={{header|Stata}}==


<syntaxhighlight lang=stata>function caesar(s, k) {
<syntaxhighlight lang="stata">function caesar(s, k) {
u = ascii(s)
u = ascii(s)
i = selectindex(u:>=65 :& u:<=90)
i = selectindex(u:>=65 :& u:<=90)
Line 6,219: Line 6,086:
caesar("layout", 20)
caesar("layout", 20)
fusion</syntaxhighlight>
fusion</syntaxhighlight>

=={{header|Swift}}==
=={{header|Swift}}==
<syntaxhighlight lang=swift>
<syntaxhighlight lang="swift">
func usage(_ e:String) {
func usage(_ e:String) {
print("error: \(e)")
print("error: \(e)")
Line 6,305: Line 6,171:
main()
main()
</syntaxhighlight>
</syntaxhighlight>

=={{header|Tcl}}==
=={{header|Tcl}}==
<syntaxhighlight lang=tcl>package require Tcl 8.6; # Or TclOO package for 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.6; # Or TclOO package for 8.5


oo::class create Caesar {
oo::class create Caesar {
Line 6,331: Line 6,196:
}</syntaxhighlight>
}</syntaxhighlight>
Demonstrating:
Demonstrating:
<syntaxhighlight lang=tcl>set caesar [Caesar new 3]
<syntaxhighlight lang="tcl">set caesar [Caesar new 3]
set txt "The five boxing wizards jump quickly."
set txt "The five boxing wizards jump quickly."
set enc [$caesar encrypt $txt]
set enc [$caesar encrypt $txt]
Line 6,344: Line 6,209:
Decrypted message = The five boxing wizards jump quickly.
Decrypted message = The five boxing wizards jump quickly.
</pre>
</pre>

=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<syntaxhighlight lang=tuscript>$$ MODE TUSCRIPT
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
text="THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
text="THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"
PRINT "text orginal ",text
PRINT "text orginal ",text
Line 6,376: Line 6,240:
encoded decoded THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
encoded decoded THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
</pre>
</pre>

=={{header|TXR}}==
=={{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.
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.
<syntaxhighlight lang=txr>@(next :args)
<syntaxhighlight lang="txr">@(next :args)
@(cases)
@(cases)
@{key /[0-9]+/}
@{key /[0-9]+/}
Line 6,410: Line 6,273:
decoded: Jgnnq, yqtnf!
decoded: Jgnnq, yqtnf!
</pre>
</pre>

=={{header|TypeScript}}==
=={{header|TypeScript}}==
<syntaxhighlight lang=javascript>function replace(input: string, key: number) : string {
<syntaxhighlight lang="javascript">function replace(input: string, key: number) : string {
return input.replace(/([a-z])/g,
return input.replace(/([a-z])/g,
($1) => String.fromCharCode(($1.charCodeAt(0) + key + 26 - 97) % 26 + 97)
($1) => String.fromCharCode(($1.charCodeAt(0) + key + 26 - 97) % 26 + 97)
Line 6,426: Line 6,288:
console.log('Enciphered: ' + encoded);
console.log('Enciphered: ' + encoded);
console.log('Deciphered: ' + decoded);</syntaxhighlight>
console.log('Deciphered: ' + decoded);</syntaxhighlight>

=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|bash}}
{{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.
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.
<syntaxhighlight lang=bash>caesar() {
<syntaxhighlight lang="bash">caesar() {
local OPTIND
local OPTIND
local encrypt n=0
local encrypt n=0
Line 6,491: Line 6,352:
encrypted: Ymj knaj gtcnsl bnefwix ozru vznhpqd.
encrypted: Ymj knaj gtcnsl bnefwix ozru vznhpqd.
decrypted: The five boxing wizards jump quickly.</pre>
decrypted: The five boxing wizards jump quickly.</pre>

=={{header|Ursa}}==
=={{header|Ursa}}==
<syntaxhighlight lang=ursa>decl string mode
<syntaxhighlight lang="ursa">decl string mode
while (not (or (= mode "encode") (= mode "decode")))
while (not (or (= mode "encode") (= mode "decode")))
out "encode/decode: " console
out "encode/decode: " console
Line 6,521: Line 6,381:
end for
end for
out endl console</syntaxhighlight>
out endl console</syntaxhighlight>

=={{header|Ursala}}==
=={{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.
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.
<syntaxhighlight lang=Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat


Line 6,587: Line 6,446:
sgd ehud anwhmf vhyzqcr itlo pthbjkx SGD EHUD ANWHMF VHYZQCR ITLO PTHBJKX
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>
the five boxing wizards jump quickly THE FIVE BOXING WIZARDS JUMP QUICKLY</pre>

=={{header|Vala}}==
=={{header|Vala}}==
This is a port of the C# code present in this page.
This is a port of the C# code present in this page.
<syntaxhighlight lang=Vala>static void println(string str) {
<syntaxhighlight lang="vala">static void println(string str) {
stdout.printf("%s\r\n", str);
stdout.printf("%s\r\n", str);
}
}
Line 6,630: Line 6,488:
The quick brown fox jumped over the lwzy dog
The quick brown fox jumped over the lwzy dog
</pre>
</pre>

=={{header|VBA}}==
=={{header|VBA}}==


<syntaxhighlight lang=vb>
<syntaxhighlight lang="vb">
Option Explicit
Option Explicit


Line 6,673: Line 6,530:
<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.
<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>
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}}==
=={{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.
Note that a left rotation has an equivalent right rotation so all rotations are converted to the equivalent right rotation prior to translation.
<syntaxhighlight lang=vb>
<syntaxhighlight lang="vb">
str = "IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES."
str = "IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES."


Line 6,720: Line 6,576:
IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES.
IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES.
</pre>
</pre>

=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
This implementation ciphers/deciphers a highlighted block of text in-place in current edit buffer.
This implementation ciphers/deciphers a highlighted block of text in-place in current edit buffer.
<syntaxhighlight lang=vedit>#10 = Get_Num("Enter the key: positive to cipher, negative to de-cipher: ", STATLINE)
<syntaxhighlight lang="vedit">#10 = Get_Num("Enter the key: positive to cipher, negative to de-cipher: ", STATLINE)


Goto_Pos(Block_Begin)
Goto_Pos(Block_Begin)
Line 6,741: Line 6,596:
Decrypted text: Quick brown Fox jumps over the lazy Dog.
Decrypted text: Quick brown Fox jumps over the lazy Dog.
</pre>
</pre>

=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<syntaxhighlight lang=vbnet>Module Module1
<syntaxhighlight lang="vbnet">Module Module1


Function Encrypt(ch As Char, code As Integer) As Char
Function Encrypt(ch As Char, code As Integer) As Char
Line 6,779: Line 6,633:
Encrypted: Ufhp rd gtc bnym knaj itejs qnvztw ozlx.
Encrypted: Ufhp rd gtc bnym knaj itejs qnvztw ozlx.
Decrypted: Pack my box with five dozen liquor jugs.</pre>
Decrypted: Pack my box with five dozen liquor jugs.</pre>

=={{header|Wortel}}==
=={{header|Wortel}}==
<syntaxhighlight lang=wortel>@let {
<syntaxhighlight lang="wortel">@let {
; this function only replaces letters and keeps case
; this function only replaces letters and keeps case
ceasar &[s n] !!s.replace &"[a-z]"gi &[x] [
ceasar &[s n] !!s.replace &"[a-z]"gi &[x] [
Line 6,801: Line 6,654:
Returns:
Returns:
<pre>"klm $%^ KLM"</pre>
<pre>"klm $%^ KLM"</pre>

=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<syntaxhighlight lang=ecmascript>class Caesar {
<syntaxhighlight lang="ecmascript">class Caesar {
static encrypt(s, key) {
static encrypt(s, key) {
var offset = key % 26
var offset = key % 26
Line 6,836: Line 6,688:
Bright vixens jump; dozy fowl quack.
Bright vixens jump; dozy fowl quack.
</pre>
</pre>

=={{header|X86 Assembly}}==
=={{header|X86 Assembly}}==
{{trans|C custom implementation}}
{{trans|C custom implementation}}
{{works with|GCC|7.3.0 - Ubuntu 18.04 64-bit}}
{{works with|GCC|7.3.0 - Ubuntu 18.04 64-bit}}
<syntaxhighlight lang=asm> # Author: Ettore Forigo - Hexwell
<syntaxhighlight lang="asm"> # Author: Ettore Forigo - Hexwell


.intel_syntax noprefix
.intel_syntax noprefix
Line 6,943: Line 6,794:
ret # return 0</syntaxhighlight>
ret # return 0</syntaxhighlight>
Usage:
Usage:
<syntaxhighlight lang=bash>$ gcc caesar.S -o caesar
<syntaxhighlight lang="bash">$ gcc caesar.S -o caesar
$ ./caesar 10 abc
$ ./caesar 10 abc
klm
klm
$ ./caesar 16 klm
$ ./caesar 16 klm
abc</syntaxhighlight>
abc</syntaxhighlight>

=={{header|XBasic}}==
=={{header|XBasic}}==
{{trans|Modula-2}}
{{trans|Modula-2}}
{{works with|Windows XBasic}}
{{works with|Windows XBasic}}
<syntaxhighlight lang=xbasic>
<syntaxhighlight lang="xbasic">
PROGRAM "caesarcipher"
PROGRAM "caesarcipher"
VERSION "0.0001"
VERSION "0.0001"
Line 7,016: Line 6,866:
Decrypted: The five boxing wizards jump quickly
Decrypted: The five boxing wizards jump quickly
</pre>
</pre>

=={{header|XBS}}==
=={{header|XBS}}==
<syntaxhighlight lang=xbs>set letters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"::split();
<syntaxhighlight lang="xbs">set letters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"::split();


func caesar(text,shift:number=1){
func caesar(text,shift:number=1){
Line 7,060: Line 6,909:
Hi
Hi
</pre>
</pre>

=={{header|XLISP}}==
=={{header|XLISP}}==
<syntaxhighlight lang=lisp>(defun caesar-encode (text key)
<syntaxhighlight lang="lisp">(defun caesar-encode (text key)
(defun encode (ascii-code)
(defun encode (ascii-code)
(defun rotate (character alphabet)
(defun rotate (character alphabet)
Line 7,079: Line 6,927:
(caesar-encode text (- 26 key)))</syntaxhighlight>
(caesar-encode text (- 26 key)))</syntaxhighlight>
Test it in a REPL:
Test it in a REPL:
<syntaxhighlight 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))
<syntaxhighlight 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
CAESAR-TEST
Line 7,088: Line 6,936:


"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."</syntaxhighlight>
"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."</syntaxhighlight>

=={{header|XPL0}}==
=={{header|XPL0}}==
To decrypt a message use the negative value of the encrypting key.
To decrypt a message use the negative value of the encrypting key.
Usage: caesar key <infile.txt >outfile.xxx
Usage: caesar key <infile.txt >outfile.xxx


<syntaxhighlight lang=XPL0>code ChIn=7, ChOut=8, IntIn=10;
<syntaxhighlight lang="xpl0">code ChIn=7, ChOut=8, IntIn=10;
int Key, C;
int Key, C;
[Key:= IntIn(8);
[Key:= IntIn(8);
Line 7,111: Line 6,958:
SDFN PB ERA ZLWK ILYH GRCHQ OLTXRU MXJV.
SDFN PB ERA ZLWK ILYH GRCHQ OLTXRU MXJV.
</pre>
</pre>

=={{header|Yabasic}}==
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic>
<syntaxhighlight lang="yabasic">
REM *** By changing the key and pattern, an encryption system that is difficult to break can be achieved. ***
REM *** By changing the key and pattern, an encryption system that is difficult to break can be achieved. ***


Line 7,155: Line 7,001:


You are encouraged to solve this task according to the task description, using any language you may know.</pre>
You are encouraged to solve this task according to the task description, using any language you may know.</pre>

=={{header|zkl}}==
=={{header|zkl}}==
<syntaxhighlight lang=zkl>fcn caesarCodec(str,n,encode=True){
<syntaxhighlight lang="zkl">fcn caesarCodec(str,n,encode=True){
var [const] letters=["a".."z"].chain(["A".."Z"]).pump(String); // static
var [const] letters=["a".."z"].chain(["A".."Z"]).pump(String); // static
if(not encode) n=26 - n;
if(not encode) n=26 - n;
Line 7,164: Line 7,009:
str.translate(letters,ltrs)
str.translate(letters,ltrs)
}</syntaxhighlight>
}</syntaxhighlight>
<syntaxhighlight lang=zkl>text:="The five boxing wizards jump quickly";
<syntaxhighlight lang="zkl">text:="The five boxing wizards jump quickly";
N:=3;
N:=3;
code:=caesarCodec(text,N);
code:=caesarCodec(text,N);
Line 7,176: Line 7,021:
decoded = The five boxing wizards jump quickly
decoded = The five boxing wizards jump quickly
</pre>
</pre>

=={{header|zonnon}}==
=={{header|zonnon}}==
<syntaxhighlight lang=zonnon>
<syntaxhighlight lang="zonnon">
module Caesar;
module Caesar;
const
const
Line 7,243: Line 7,087:
The five boxing wizards jump quickly -c-> RFC DGTC ZMVGLE UGXYPBQ HSKN OSGAIJW -d-> THE FIVE BOXING WIZARDS JUMP QUICKLY
The five boxing wizards jump quickly -c-> RFC DGTC ZMVGLE UGXYPBQ HSKN OSGAIJW -d-> THE FIVE BOXING WIZARDS JUMP QUICKLY
</pre>
</pre>

=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
{{trans|BBC BASIC}}
{{trans|BBC BASIC}}
<syntaxhighlight lang=zxbasic>10 LET t$="PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS"
<syntaxhighlight lang="zxbasic">10 LET t$="PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS"
20 PRINT t$''
20 PRINT t$''
30 LET key=RND*25+1
30 LET key=RND*25+1
Line 7,261: Line 7,104:
</syntaxhighlight>
</syntaxhighlight>
{{trans|Yabasic}}
{{trans|Yabasic}}
<syntaxhighlight lang=zxbasic>10 LET t$="Wonderful ZX Spectrum."
<syntaxhighlight lang="zxbasic">10 LET t$="Wonderful ZX Spectrum."
20 LET c$="a":REM more characters, more difficult for decript
20 LET c$="a":REM more characters, more difficult for decript
30 LET CIFRA=1: LET DESCIFRA=-1
30 LET CIFRA=1: LET DESCIFRA=-1