Caesar cipher: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 25: Line 25:


=={{header|11l}}==
=={{header|11l}}==
<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 44: Line 44:
V enc = caesar(msg, 11)
V enc = caesar(msg, 11)
print(enc)
print(enc)
print(caesar(enc, 11, decode' 1B))</lang>
print(caesar(enc, 11, decode' 1B))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 54: Line 54:
=={{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.
<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 83: Line 83:
ORG
ORG
YREGS
YREGS
END CAESARO</lang>
END CAESARO</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 92: Line 92:


=={{header|8th}}==
=={{header|8th}}==
<lang forth>\ Ensure the output char is in the correct range:
<syntaxhighlight lang=forth>\ Ensure the output char is in the correct range:
: modulate \ char base -- char
: modulate \ char base -- char
tuck n:- 26 n:+ 26 n:mod n:+ ;
tuck n:- 26 n:+ 26 n:mod n:+ ;
Line 114: Line 114:
1 caesar dup . cr
1 caesar dup . cr
-1 caesar . cr
-1 caesar . cr
bye</lang>
bye</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 123: Line 123:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>CHAR FUNC Shift(CHAR c BYTE code)
<syntaxhighlight lang=Action!>CHAR FUNC Shift(CHAR c BYTE code)
CHAR base
CHAR base


Line 165: Line 165:
Test("The quick brown fox jumps over the lazy dog.",23)
Test("The quick brown fox jumps over the lazy dog.",23)
Test("The quick brown fox jumps over the lazy dog.",5)
Test("The quick brown fox jumps over the lazy dog.",5)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Caesar_cipher.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Caesar_cipher.png Screenshot from Atari 8-bit computer]
Line 185: Line 185:


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


procedure Caesar is
procedure Caesar is
Line 229: Line 229:
Ada.Text_IO.Put_Line("Decrypted Ciphertext ->" & crypt(Text, -Key));
Ada.Text_IO.Put_Line("Decrypted Ciphertext ->" & crypt(Text, -Key));


end Caesar;</lang>
end Caesar;</syntaxhighlight>
{{out}}
{{out}}
<pre>> ./caesar
<pre>> ./caesar
Line 242: Line 242:
{{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''.}}
<lang algol68>#!/usr/local/bin/a68g --script #
<syntaxhighlight lang=algol68>#!/usr/local/bin/a68g --script #


program caesar: BEGIN
program caesar: BEGIN
Line 284: Line 284:
printf(($gl$, "Decrypted Ciphertext ->" + encrypt(text, -key)))
printf(($gl$, "Decrypted Ciphertext ->" + encrypt(text, -key)))


END #caesar#</lang>
END #caesar#</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 293: Line 293:


=={{header|APL}}==
=={{header|APL}}==
<lang apl>
<syntaxhighlight lang=apl>
∇CAESAR[⎕]∇
∇CAESAR[⎕]∇
Line 301: Line 301:
[3] A←V
[3] A←V
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 325: Line 325:
=={{header|AppleScript}}==
=={{header|AppleScript}}==


<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 351: Line 351:
set enciphered to caesarEncipher(txt, |key|)
set enciphered to caesarEncipher(txt, |key|)
set deciphered to caesarDecipher(enciphered, |key|)
set deciphered to caesarDecipher(enciphered, |key|)
return "Text: '" & txt & ("'" & linefeed & "Key: " & |key| & linefeed & linefeed) & (enciphered & linefeed & deciphered)</lang>
return "Text: '" & txt & ("'" & linefeed & "Key: " & |key| & linefeed & linefeed) & (enciphered & linefeed & deciphered)</syntaxhighlight>


{{output}}
{{output}}


<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 362: Line 362:
Cqn zdrlt kaxfw oxg sdvyb xena cqn ujih mxp.
Cqn zdrlt kaxfw oxg sdvyb xena cqn ujih mxp.
ROMANES EUNT DOMUS!
ROMANES EUNT DOMUS!
The quick brown fox jumps over the lazy dog."</lang>
The quick brown fox jumps over the lazy dog."</syntaxhighlight>


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<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 406: Line 406:
460 IF C > 90 THEN C = C - 26
460 IF C > 90 THEN C = C - 26
470 LET C$ = CHR$(C + L)
470 LET C$ = CHR$(C + L)
480 RETURN</lang>
480 RETURN</syntaxhighlight>
{{out}}
{{out}}
<pre>]RUN
<pre>]RUN
Line 430: Line 430:


=={{header|Arc}}==
=={{header|Arc}}==
<lang Arc>
<syntaxhighlight lang=Arc>
(= rot (fn (L N)
(= rot (fn (L N)
(if
(if
Line 451: Line 451:
(string output)
(string output)
))
))
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
<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>
</lang>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<lang ARM Assembly>
<syntaxhighlight lang=ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program caresarcode.s */
/* program caresarcode.s */
Line 635: Line 635:
bx lr @ return
bx lr @ return


</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
{{trans|11l}}
{{trans|11l}}
<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 661: Line 661:
enc: caesar msg 11
enc: caesar msg 11
print [" Encoded :" enc]
print [" Encoded :" enc]
print [" Decoded :" caesar.decode enc 11]</lang>
print [" Decoded :" caesar.decode enc 11]</syntaxhighlight>


{{out}}
{{out}}
Line 670: Line 670:


=={{header|Astro}}==
=={{header|Astro}}==
<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 682: Line 682:
let decrypted = caesar(enc, 11, decode: true)
let decrypted = caesar(enc, 11, decode: true)


print(message, encrypted, decrypted, sep: '\n')</lang>
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
<lang AutoHotkey>n=2
<syntaxhighlight lang=AutoHotkey>n=2
s=HI
s=HI
t:=&s
t:=&s
While *t
While *t
o.=Chr(Mod(*t-65+n,26)+65),t+=2
o.=Chr(Mod(*t-65+n,26)+65),t+=2
MsgBox % o</lang>
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.
<lang AutoHotkey>Caesar(string, n){
<syntaxhighlight lang=AutoHotkey>Caesar(string, n){
Loop Parse, string
Loop Parse, string
{
{
Line 705: Line 705:
}
}


MsgBox % Caesar("h i", 2) "`n" Caesar("Hi", 20)</lang>
MsgBox % Caesar("h i", 2) "`n" Caesar("Hi", 20)</syntaxhighlight>
{{out}}<pre>j k
{{out}}<pre>j k
Bc</pre>
Bc</pre>
Line 712: Line 712:


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
<lang autoit>
<syntaxhighlight lang=autoit>
$Caesar = Caesar("Hi", 2, True)
$Caesar = Caesar("Hi", 2, True)
MsgBox(0, "Caesar", $Caesar)
MsgBox(0, "Caesar", $Caesar)
Line 745: Line 745:
Return $sLetters
Return $sLetters
EndFunc ;==>Caesar
EndFunc ;==>Caesar
</syntaxhighlight>
</lang>


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


Line 791: Line 791:
return s
return s
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 802: Line 802:
=={{header|Babel}}==
=={{header|Babel}}==


<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 853: Line 853:
<- 0x60 cugt ->
<- 0x60 cugt ->
0x7b cult
0x7b cult
cand }))</lang>
cand }))</syntaxhighlight>


{{out}}
{{out}}
Line 861: Line 861:


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


Line 881: Line 881:


PRINT "Encrypted: ", en$
PRINT "Encrypted: ", en$
PRINT "Decrypted: ", Ceasar$(en$, 26-tokey)</lang>
PRINT "Decrypted: ", Ceasar$(en$, 26-tokey)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 899: Line 899:
{{works with|GNU bash, version 4}}
{{works with|GNU bash, version 4}}


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


Line 941: Line 941:
}
}


</syntaxhighlight>
</lang>


{{out}} (input: caesar_cipher -e 13 "Hello World!"):
{{out}} (input: caesar_cipher -e 13 "Hello World!"):
Line 954: Line 954:


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<lang>
<syntaxhighlight lang=text>
# Caeser Cipher
# Caeser Cipher
# basic256 1.1.4.0
# basic256 1.1.4.0
Line 985: Line 985:
next i
next i
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 998: Line 998:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<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,020: Line 1,020:
NEXT
NEXT
= text$
= text$
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Pack my box with five dozen liquor jugs
<pre>Pack my box with five dozen liquor jugs
Line 1,027: Line 1,027:


=={{header|Beads}}==
=={{header|Beads}}==
<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,059: Line 1,059:
) : str
) : str
// we could also just shift by 26-nshift, same as going in reverse
// we could also just shift by 26-nshift, same as going in reverse
return Encrypt(input, -nshift)</lang>
return Encrypt(input, -nshift)</syntaxhighlight>
{{out}}
{{out}}
<pre>Plain: The five boxing wizards (🤖) jump quickly.
<pre>Plain: The five boxing wizards (🤖) jump quickly.
Line 1,071: Line 1,071:
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.


<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</lang>
**-"A"-::0\`\55*`+#^_\0g+"4"+4^>\`*48</syntaxhighlight>


{{out}}
{{out}}
Line 1,081: Line 1,081:
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.


<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</lang>
**-"A"-::0\`\55*`+#^_\0g-"4"+4^>\`*48</syntaxhighlight>


{{out}}
{{out}}
Line 1,090: Line 1,090:


=={{header|BQN}}==
=={{header|BQN}}==
<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</lang>
Rot ← {i←⊑"A[a{"⍋𝕩 ⋄ i⊑o+p|(𝕨×m)+𝕩-o}⎉0</syntaxhighlight>


Example:
Example:


<lang bqn>3 Rot "We're no strangers to love // You know the rules and so do I"</lang>
<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>


Line 1,101: Line 1,101:


=={{header|Brainf***}}==
=={{header|Brainf***}}==
<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,317: Line 1,317:
^
^
<< :c ^
<< :c ^
]</lang>
]</syntaxhighlight>
Usage:
Usage:
Give to the program the key and the word to encrypt, each followed by a space.<br>
Give to the program the key and the word to encrypt, each followed by a space.<br>
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 -->
<lang whitespace>10 abc </lang>
<syntaxhighlight lang=whitespace>10 abc </syntaxhighlight>
Output:
Output:
<pre>klm</pre>
<pre>klm</pre>
Input:
Input:
<lang whitespace>16 klm </lang>
<syntaxhighlight lang=whitespace>16 klm </syntaxhighlight>
Output:
Output:
<pre>abc</pre>
<pre>abc</pre>


=={{header|C}}==
=={{header|C}}==
<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,382: Line 1,382:
return 0;
return 0;
}</lang>
}</syntaxhighlight>


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


Line 1,424: Line 1,424:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Pack my box with five dozen liquor jugs.
<pre>Pack my box with five dozen liquor jugs.
Line 1,431: Line 1,431:


=={{header|C++}}==
=={{header|C++}}==
<lang Cpp>#include <string>
<syntaxhighlight lang=Cpp>#include <string>
#include <iostream>
#include <iostream>
#include <algorithm>
#include <algorithm>
Line 1,475: Line 1,475:
std::cout << input << std::endl ;
std::cout << input << std::endl ;
return 0 ;
return 0 ;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Which text is to be encrypted ?
<pre>Which text is to be encrypted ?
Line 1,494: Line 1,494:
===={{works with|C++-11}}====
===={{works with|C++-11}}====


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


#include <string>
#include <string>
Line 1,548: Line 1,548:
return 0 ;
return 0 ;
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,563: Line 1,563:
=={{header|Clojure}}==
=={{header|Clojure}}==
Readable version:
Readable version:
<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,585: Line 1,585:
(print "Original text:" text "\n")
(print "Original text:" text "\n")
(print "Encryption:" enc "\n")
(print "Encryption:" enc "\n")
(print "Decryption:" (decrypt -1 enc) "\n"))</lang>
(print "Decryption:" (decrypt -1 enc) "\n"))</syntaxhighlight>


output:
output:
Line 1,594: Line 1,594:


Terser version using replace:
Terser version using replace:
<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,600: Line 1,600:


(defn decode [k s]
(defn decode [k s]
(encode (- 26 k) s))</lang>
(encode (- 26 k) s))</syntaxhighlight>


output:<pre>
output:<pre>
Line 1,611: Line 1,611:
=={{header|COBOL}}==
=={{header|COBOL}}==
COBOL-85 ASCII or EBCIDIC
COBOL-85 ASCII or EBCIDIC
<lang COBOL>
<syntaxhighlight lang=COBOL>
identification division.
identification division.
program-id. caesar.
program-id. caesar.
Line 1,649: Line 1,649:
.
.
end program caesar.
end program caesar.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,658: Line 1,658:


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


Line 1,743: Line 1,743:
MOVE FUNCTION encrypt(decrypt-offset, str) TO decrypted-str
MOVE FUNCTION encrypt(decrypt-offset, str) TO decrypted-str
.
.
END FUNCTION decrypt.</lang>
END FUNCTION decrypt.</syntaxhighlight>


{{out}}
{{out}}
Line 1,754: Line 1,754:


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<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,763: Line 1,763:
console.log cipher "Hello World", 2
console.log cipher "Hello World", 2
console.log cipher "azAz %^&*()", 3</lang>
console.log cipher "azAz %^&*()", 3</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,775: Line 1,775:
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.


<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,821: Line 1,821:
3035 cm$=cm$+mid$(ec$,c,1)
3035 cm$=cm$+mid$(ec$,c,1)
3040 next i
3040 next i
3050 return</lang>
3050 return</syntaxhighlight>


{{Output}}
{{Output}}
Line 1,850: Line 1,850:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
====Main version====
====Main version====
<lang lisp>(defun encipher-char (ch key)
<syntaxhighlight lang=lisp>(defun encipher-char (ch key)
(let* ((c (char-code ch)) (la (char-code #\a)) (ua (char-code #\A))
(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,868: Line 1,868:
(format t " Original: ~a ~%" original-text)
(format t " Original: ~a ~%" original-text)
(format t "Encrypted: ~a ~%" cipher-text)
(format t "Encrypted: ~a ~%" cipher-text)
(format t "Decrypted: ~a ~%" recovered-text))</lang>
(format t "Decrypted: ~a ~%" recovered-text))</syntaxhighlight>
{{out}}
{{out}}
<pre> Original: The five boxing wizards jump quickly
<pre> Original: The five boxing wizards jump quickly
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>
<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,883: Line 1,883:
(when (<= 65 c 90) 65))))
(when (<= 65 c 90) 65))))
(if b (code-char (+ (mod (+ (- c b) k) 26) b)) h))
(if b (code-char (+ (mod (+ (- c b) k) 26) b)) h))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,894: Line 1,894:
1. Program
1. Program


<lang lisp>(defconstant +a+ "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz")
<syntaxhighlight lang=lisp>(defconstant +a+ "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz")
(defun caesar (txt offset)
(defun caesar (txt offset)
Line 1,902: Line 1,902:
(char +a+ (mod (+ (position c +a+) (* 2 offset)) 52))
(char +a+ (mod (+ (position c +a+) (* 2 offset)) 52))
c))
c))
txt))</lang>
txt))</syntaxhighlight>


2. Execution
2. Execution
Line 1,913: Line 1,913:


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


Line 1,924: Line 1,924:
encrypted = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG".caesar_cipher(5)
encrypted = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG".caesar_cipher(5)
decrypted = encrypted.caesar_cipher(-5)
decrypted = encrypted.caesar_cipher(-5)
</syntaxhighlight>
</lang>


=={{header|Cubescript}}==
=={{header|Cubescript}}==
<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,984: Line 1,984:
] ]
] ]
result $arg1
result $arg1
]</lang>
]</syntaxhighlight>


Usage:
Usage:
<lang>>>> 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.</lang>
> The Quick Brown Fox Jumps Over The Lazy Dog.</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<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,014: Line 2,014:
writeln("Encrypted: ", txt.rot(key));
writeln("Encrypted: ", txt.rot(key));
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Original: The five boxing wizards jump quickly
<pre>Original: The five boxing wizards jump quickly
Line 2,020: Line 2,020:
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):
<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,039: Line 2,039:
txt.inplaceRot(26 - key);
txt.inplaceRot(26 - key);
writeln("Decrypted: ", txt);
writeln("Decrypted: ", txt);
}</lang>
}</syntaxhighlight>


A version that uses the standard library (same output):
A version that uses the standard library (same output):
<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,058: Line 2,058:
writeln("Encrypted: ", txt.rot(key));
writeln("Encrypted: ", txt.rot(key));
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
}</lang>
}</syntaxhighlight>


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


Line 2,124: Line 2,124:
trip(".-:/\"\\!");
trip(".-:/\"\\!");
trip("The Quick Brown Fox Jumps Over The Lazy Dog.");
trip("The Quick Brown Fox Jumps Over The Lazy Dog.");
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>JK
<pre>JK
Line 2,154: Line 2,154:
{{trans|C#}}
{{trans|C#}}


<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,179: Line 2,179:
print("Encrypted: \(str)")
print("Encrypted: \(str)")
str = str.Decrypt(5)
str = str.Decrypt(5)
print("Decrypted: \(str)")</lang>
print("Decrypted: \(str)")</syntaxhighlight>


{{out}}
{{out}}
Line 2,200: Line 2,200:
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).
<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,416: Line 2,416:
P F [acc = 0 on entry]
P F [acc = 0 on entry]
DGAZA!FREQUENS!LIBYCUM!DUXIT!KARTHAGO!TRIUMPHUM.
DGAZA!FREQUENS!LIBYCUM!DUXIT!KARTHAGO!TRIUMPHUM.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,431: Line 2,431:


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<lang eiffel>
<syntaxhighlight lang=eiffel>
class
class
APPLICATION
APPLICATION
Line 2,485: Line 2,485:
end
end
end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,495: Line 2,495:
=={{header|Ela}}==
=={{header|Ela}}==


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


chars = "ABCDEFGHIJKLMOPQRSTUVWXYZ"
chars = "ABCDEFGHIJKLMOPQRSTUVWXYZ"
Line 2,522: Line 2,522:
putStrLn ""
putStrLn ""
putStr "Decoded string: "
putStr "Decoded string: "
put $ decypher key cstr</lang>
put $ decypher key cstr</syntaxhighlight>


{{out}}
{{out}}
Line 2,533: Line 2,533:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import system'routines;
<syntaxhighlight lang=elena>import system'routines;
import system'math;
import system'math;
import extensions;
import extensions;
Line 2,607: Line 2,607:


console.readChar()
console.readChar()
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,616: Line 2,616:


=={{header|Elixir}}==
=={{header|Elixir}}==
<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,633: Line 2,633:
IO.puts "Original: #{text}"
IO.puts "Original: #{text}"
IO.puts "Encrypted: #{enc = Caesar_cipher.encode(text, key)}"
IO.puts "Encrypted: #{enc = Caesar_cipher.encode(text, key)}"
IO.puts "Decrypted: #{Caesar_cipher.encode(enc, -key)}"</lang>
IO.puts "Decrypted: #{Caesar_cipher.encode(enc, -key)}"</syntaxhighlight>


{{out}}
{{out}}
Line 2,643: Line 2,643:


=={{header|Erlang}}==
=={{header|Erlang}}==
<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,678: Line 2,678:
PlainText = lists:map(fun(Char) -> rot(Char, Decode) end, CypherText).
PlainText = lists:map(fun(Char) -> rot(Char, Decode) end, CypherText).


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


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


Line 2,718: Line 2,718:


END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,728: Line 2,728:
=={{header|Euphoria}}==
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.0}}
{{works with|Euphoria|4.0.0}}
<lang Euphoria>
<syntaxhighlight lang=Euphoria>
--caesar cipher for Rosetta Code wiki
--caesar cipher for Rosetta Code wiki
--User:Lnettnay
--User:Lnettnay
Line 2,784: Line 2,784:
printf(1,"%s\n",{text})
printf(1,"%s\n",{text})


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,793: Line 2,793:


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


Line 2,805: Line 2,805:


let encrypt n = cipher n
let encrypt n = cipher n
let decrypt n = cipher (26 - n)</lang>
let decrypt n = cipher (26 - n)</syntaxhighlight>
<pre>&gt; caesar.encrypt 2 "HI";;
<pre>&gt; caesar.encrypt 2 "HI";;
val it : string = "JK"
val it : string = "JK"
Line 2,819: Line 2,819:
{{works with|Factor|0.97}}
{{works with|Factor|0.97}}
{{trans|F#}}
{{trans|F#}}
<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,836: Line 2,836:


11 "Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr." decrypt print
11 "Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr." decrypt print
11 "The quick brown fox jumped over the lazy dog." encrypt print</lang>
11 "The quick brown fox jumped over the lazy dog." encrypt print</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,847: Line 2,847:
Shifts upper/lower case letters, leaves other characters as they are.
Shifts upper/lower case letters, leaves other characters as they are.


<lang fantom>
<syntaxhighlight lang=fantom>
class Main
class Main
{
{
Line 2,900: Line 2,900:
}
}
}
}
</syntaxhighlight>
</lang>


Example:
Example:
Line 2,922: Line 2,922:
=={{header|Fhidwfe}}==
=={{header|Fhidwfe}}==
only encodes letters
only encodes letters
<lang Fhidwfe>
<syntaxhighlight lang=Fhidwfe>
lowers = ['a','z']
lowers = ['a','z']
uppers = ['A','Z']
uppers = ['A','Z']
Line 2,965: Line 2,965:


//this compiles with only 6 warnings!
//this compiles with only 6 warnings!
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
<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,986: Line 2,986:


3 ceasar-inverse test 2@ ceasar-string
3 ceasar-inverse test 2@ ceasar-string
test 2@ cr type</lang>
test 2@ cr type</syntaxhighlight>


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


Line 3,032: Line 3,032:
end subroutine
end subroutine


end program Caesar_Cipher</lang>
end program Caesar_Cipher</syntaxhighlight>
{{out}}
{{out}}
<pre>Original message = The five boxing wizards jump quickly
<pre>Original message = The five boxing wizards jump quickly
Line 3,039: Line 3,039:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<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,079: Line 3,079:
Decrypt s, 8
Decrypt s, 8
Print "Decrypted : "; s
Print "Decrypted : "; s
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 3,090: Line 3,090:
=={{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]'''
<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,109: Line 3,109:
Print sString & gb.NewLine & sCoded 'Print the result
Print sString & gb.NewLine & sCoded 'Print the result


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 3,117: Line 3,117:


=={{header|GAP}}==
=={{header|GAP}}==
<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,142: Line 3,142:


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."</lang>
# "All human beings are born free and equal in dignity and rights."</syntaxhighlight>


=={{header|GFA Basic}}==
=={{header|GFA Basic}}==
<lang basic>
<syntaxhighlight lang=basic>
'
'
' Caesar cypher
' Caesar cypher
Line 3,182: Line 3,182:
RETURN @encrypt$(text$,26-key%)
RETURN @encrypt$(text$,26-key%)
ENDFUNC
ENDFUNC
</syntaxhighlight>
</lang>


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


import (
import (
Line 3,244: Line 3,244:
fmt.Println(" Deciphered:", ck.decipher(ct))
fmt.Println(" Deciphered:", ck.decipher(ct))
}
}
}</lang>
}</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]].)
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 3,302: Line 3,302:
fmt.Println(" Deciphered:", ck.decipher(ct))
fmt.Println(" Deciphered:", ck.decipher(ct))
}
}
}</lang>
}</syntaxhighlight>
{{out}} (either version)
{{out}} (either version)
<pre>
<pre>
Line 3,321: Line 3,321:
=={{header|Groovy}}==
=={{header|Groovy}}==
Java style:
Java style:
<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,333: Line 3,333:
builder as String
builder as String
}
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</lang>
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</syntaxhighlight>


Functional style:
Functional style:
<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,342: Line 3,342:
}.join()
}.join()
}
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</lang>
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</syntaxhighlight>


Ninja style:
Ninja style:
<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()
}
}
def caesarDecode(k, text) { caesarEncode(26 - k, text) }</lang>
def caesarDecode(k, text) { caesarEncode(26 - k, text) }</syntaxhighlight>
Using built in 'tr' function and a replacement alphabet:
Using built in 'tr' function and a replacement alphabet:
<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) }</lang>
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:
<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'))
}
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</lang>
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }</syntaxhighlight>
Test code:
Test code:
<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,373: Line 3,373:
assert plainText == decodedText
assert plainText == decodedText
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,381: Line 3,381:


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


import Data.Char
import Data.Char
Line 3,397: Line 3,397:
where b' = fromIntegral $ ord b
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c
c' = fromIntegral $ ord c
</syntaxhighlight>
</lang>


And trying it out in GHCi:
And trying it out in GHCi:
Line 3,409: Line 3,409:
Similarly, but allowing for negative cipher keys, and using isAlpha, isUpper, negate:
Similarly, but allowing for negative cipher keys, and using isAlpha, isUpper, negate:


<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,432: Line 3,432:
cipher = caesar k
cipher = caesar k
plain = "Curio, Cesare venne, e vide e vinse ? "
plain = "Curio, Cesare venne, e vide e vinse ? "
mapM_ putStrLn $ [cipher, uncaesar k . cipher] <*> [plain]</lang>
mapM_ putStrLn $ [cipher, uncaesar k . cipher] <*> [plain]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Skhye, Suiqhu luddu, u lytu u lydiu ?
<pre>Skhye, Suiqhu luddu, u lytu u lydiu ?
Line 3,438: Line 3,438:


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


Line 3,469: Line 3,469:
addChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26)
addChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26)
where b' = fromIntegral $ ord b
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c</lang>
c' = fromIntegral $ ord c</syntaxhighlight>


=={{header|Hoon}}==
=={{header|Hoon}}==
<lang Hoon>|%
<syntaxhighlight lang=Hoon>|%
++ enc
++ enc
|= [msg=tape key=@ud]
|= [msg=tape key=@ud]
Line 3,480: Line 3,480:
|= [msg=tape key=@ud]
|= [msg=tape key=@ud]
(enc msg (sub 26 key))
(enc msg (sub 26 key))
--</lang>
--</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).
<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,499: Line 3,499:
"d"|"decrypt" : return map(text,(&lcase||&lcase)[k+:*&lcase],&lcase)
"d"|"decrypt" : return map(text,(&lcase||&lcase)[k+:*&lcase],&lcase)
}
}
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 3,507: Line 3,507:


=={{header|IS-BASIC}}==
=={{header|IS-BASIC}}==
<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,547: Line 3,547:
480 NEXT
480 NEXT
490 LET M$=T$
490 LET M$=T$
500 END DEF</lang>
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:
<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.]</lang>
caesar=: (cndx 0)}&a.@u:@cndx@[ {~ a.i.]</syntaxhighlight>
Example use:<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, ...</lang>
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:
<lang j>CAESAR=:1 :'(26|m&+)&.((26{.64}.a.)&i.)'</lang>
<syntaxhighlight lang=j>CAESAR=:1 :'(26|m&+)&.((26{.64}.a.)&i.)'</syntaxhighlight>
Example use:<lang j> 20 CAESAR 'HI'
Example use:<syntaxhighlight lang=j> 20 CAESAR 'HI'
BC</lang>
BC</syntaxhighlight>


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


Line 3,590: Line 3,590:
(print cipher)
(print cipher)
(print str)))
(print str)))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,602: Line 3,602:
=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<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,631: Line 3,631:
return encoded.toString();
return encoded.toString();
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,642: Line 3,642:
===ES5===
===ES5===


<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,652: Line 3,652:
for (var i = 0; i<26; i++) {
for (var i = 0; i<26; i++) {
console.log(i+': '+caesar(text,i));
console.log(i+': '+caesar(text,i));
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 3,665: Line 3,665:
===ES6===
===ES6===


<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, '')
.replace(/./g, a =>
.replace(/./g, a =>
String.fromCharCode(65 + (a.charCodeAt(0) - 65 + shift) % 26));</lang>
String.fromCharCode(65 + (a.charCodeAt(0) - 65 + shift) % 26));</syntaxhighlight>




Or, allowing encoding and decoding of both lower and upper case:
Or, allowing encoding and decoding of both lower and upper case:


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


// Int -> String -> String
// Int -> String -> String
Line 3,716: Line 3,716:
return [strCipher, ' -> ', strDecode];
return [strCipher, ' -> ', strDecode];


})(114, 'Curio, Cesare venne, e vide e vinse ? ');</lang>
})(114, 'Curio, Cesare venne, e vide e vinse ? ');</syntaxhighlight>


{{Out}}
{{Out}}
Line 3,725: Line 3,725:
{{works with|jq}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
'''Works with gojq, the Go implementation of jq'''
<lang jq>def encrypt(key):
<syntaxhighlight lang=jq>def encrypt(key):
. as $s
. as $s
| explode as $xs
| explode as $xs
Line 3,755: Line 3,755:
(encrypt(8)
(encrypt(8)
| ., decrypt(8) )
| ., decrypt(8) )
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,766: Line 3,766:
=={{header|Jsish}}==
=={{header|Jsish}}==
From Typescript entry.
From Typescript entry.
<lang javascript>/* Caesar cipher, in Jsish */
<syntaxhighlight lang=javascript>/* Caesar cipher, in Jsish */
"use strict";
"use strict";


Line 3,798: Line 3,798:
caesarCipher(caesarCipher(str, 3), -3) ==> The five boxing wizards jump quickly
caesarCipher(caesarCipher(str, 3), -3) ==> The five boxing wizards jump quickly
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 3,807: Line 3,807:
===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===


<lang julia>
<syntaxhighlight lang=julia>
# Caeser cipher
# Caeser cipher
# Julia 1.5.4
# Julia 1.5.4
Line 3,840: Line 3,840:
text = "Magic Encryption"; key = 13
text = "Magic Encryption"; key = 13
csrcipher(text, key)
csrcipher(text, key)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,850: Line 3,850:
Assumes lowercase letters, and no punctuation.
Assumes lowercase letters, and no punctuation.


<syntaxhighlight lang=k>
<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]}'
caesar[s;1]
caesar[s;1]
"uifsf jt b ujef jo uif bggbjst pg nfo"
"uifsf jt b ujef jo uif bggbjst pg nfo"
</syntaxhighlight>
</lang>


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


object Caesar {
object Caesar {
Line 3,892: Line 3,892:
val decoded = Caesar.decrypt(encoded, 8)
val decoded = Caesar.decrypt(encoded, 8)
println(decoded)
println(decoded)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,905: Line 3,905:
=={{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].
<lang scheme>
<syntaxhighlight lang=scheme>
{def caesar
{def caesar


Line 3,975: Line 3,975:
-> VENIVIDIVICI
-> VENIVIDIVICI


</syntaxhighlight>
</lang>


=={{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.


<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,989: Line 3,989:
writeln " original: ", .s
writeln " original: ", .s
writeln "encrypted: ", .rot(.s, .key)
writeln "encrypted: ", .rot(.s, .key)
writeln "decrypted: ", .rot(.rot(.s, .key), -.key)</lang>
writeln "decrypted: ", .rot(.rot(.s, .key), -.key)</syntaxhighlight>


{{out}}
{{out}}
Line 3,997: Line 3,997:


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


Print "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Print "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Line 4,020: Line 4,020:
CaesarCypher$ = (CaesarCypher$ + Chr$(rotate))
CaesarCypher$ = (CaesarCypher$ + Chr$(rotate))
Next i
Next i
End Function</lang>
End Function</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<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,038: Line 4,038:
end repeat
end repeat
return rotPhrase
return rotPhrase
end caesarCipher</lang>
end caesarCipher</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
{{trans|Common Lisp}}
{{trans|Common Lisp}}
{{works with|UCB Logo}}
{{works with|UCB Logo}}
<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,076: Line 4,076:
print sentence "|Encrypted:| :ciphertext
print sentence "|Encrypted:| :ciphertext
print sentence "|Recovered:| :recovered
print sentence "|Recovered:| :recovered
bye</lang>
bye</syntaxhighlight>


{{out}}
{{out}}
Line 4,085: Line 4,085:
=={{header|Lua}}==
=={{header|Lua}}==


<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,115: Line 4,115:
print("Decrypted text: ", decrypted)
print("Decrypted text: ", decrypted)
end
end
</syntaxhighlight>
</lang>




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


local function make_table(k)
local function make_table(k)
Line 4,150: Line 4,150:
end
end
return string.char(unpack(res_t))
return string.char(unpack(res_t))
end</lang>
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.


<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,173: Line 4,173:
Print Cipher$(B$,12)
Print Cipher$(B$,12)


</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<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,182: Line 4,182:
> StringTools:-Encode( %, encoding = alpharot[ 23 ] );
> StringTools:-Encode( %, encoding = alpharot[ 23 ] );
"The five boxing wizards jump quickly"
"The five boxing wizards jump quickly"
</syntaxhighlight>
</lang>
(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}}==
<lang Mathematica>cypher[mesg_String,n_Integer]:=StringReplace[mesg,Flatten[Thread[Rule[#,RotateLeft[#,n]]]&/@CharacterRange@@@{{"a","z"},{"A","Z"}}]]</lang>
<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]
Line 4,192: Line 4,192:


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


=={{header|Microsoft Small Basic}}==
=={{header|Microsoft Small Basic}}==
<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,227: Line 4,227:
TextWindow.WriteLine(message)
TextWindow.WriteLine(message)
TextWindow.WriteLine(caeser)
TextWindow.WriteLine(caeser)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Enter a 1-25 number key (-ve number to decode): 10
<pre>Enter a 1-25 number key (-ve number to decode): 10
Line 4,243: Line 4,243:


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<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,254: Line 4,254:


print caesar("Hello world!", 7)
print caesar("Hello world!", 7)
print caesar("Olssv dvysk!", 26-7)</lang>
print caesar("Olssv dvysk!", 26-7)</syntaxhighlight>


{{out}}
{{out}}
Line 4,263: Line 4,263:
==={{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.
<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,303: Line 4,303:
;
;
map println ` map (fn s = encipher (s,ston ` default (argv 0, "1"))) ` readfile ();
map println ` map (fn s = encipher (s,ston ` default (argv 0, "1"))) ` readfile ();
</syntaxhighlight>
</lang>
The string for encoding is supplied as an input stream, and the offset supplied on the command line (defaults to 1). For example
The string for encoding is supplied as an input stream, and the offset supplied on the command line (defaults to 1). For example
<pre>echo The cat sat on the mat | mlite -f caecip.m ~5</pre>
<pre>echo The cat sat on the mat | mlite -f caecip.m ~5</pre>
Line 4,311: Line 4,311:
=={{header|Modula-2}}==
=={{header|Modula-2}}==
{{trans|Java}}
{{trans|Java}}
<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,387: Line 4,387:


ReadChar;
ReadChar;
END CaesarCipher.</lang>
END CaesarCipher.</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
Line 4,396: Line 4,396:
It also illustrates the use of exceptions in Modula-3.
It also illustrates the use of exceptions in Modula-3.


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


IMPORT IO, IntSeq, Text;
IMPORT IO, IntSeq, Text;
Line 4,481: Line 4,481:
Decode(buffer, message);
Decode(buffer, message);
IO.Put(message); IO.PutChar('\n');
IO.Put(message); IO.PutChar('\n');
END Caesar.</lang>
END Caesar.</syntaxhighlight>


{{out}}
{{out}}
Line 4,490: Line 4,490:


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<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,524: Line 4,524:


return plaintext
return plaintext
end</lang>
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.
<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,619: Line 4,619:


method isFalse public static returns boolean
method isFalse public static returns boolean
return \isTrue</lang>
return \isTrue</syntaxhighlight>


<pre style="height: 60ex; overflow: scroll;">
<pre style="height: 60ex; overflow: scroll;">
Line 4,715: Line 4,715:
=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Python}}
{{trans|Python}}
<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,728: Line 4,728:
let enc = caesar(msg, 11)
let enc = caesar(msg, 11)
echo enc
echo enc
echo caesar(enc, 11, decode = true)</lang>
echo caesar(enc, 11, decode = true)</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Works with oo2c version2
Works with oo2c version2
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE Caesar;
MODULE Caesar;
IMPORT
IMPORT
Line 4,792: Line 4,792:


END Caesar.
END Caesar.
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 4,801: Line 4,801:


=={{header|Objeck}}==
=={{header|Objeck}}==
<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,831: Line 4,831:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,839: Line 4,839:


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


Line 4,863: Line 4,863:
else
else
c
c
) str</lang>
) str</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,872: Line 4,872:
print_endline deciphered;
print_endline deciphered;
Printf.printf "equal: %b\n" (orig = deciphered)
Printf.printf "equal: %b\n" (orig = deciphered)
;;</lang>
;;</syntaxhighlight>
{{out}}
{{out}}
<pre>$ ocaml caesar.ml
<pre>$ ocaml caesar.ml
Line 4,881: Line 4,881:
=={{header|Oforth}}==
=={{header|Oforth}}==


<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 + ;


: cipherE(s, key) s map(#[ key ceasar ]) charsAsString ;
: cipherE(s, key) s map(#[ key ceasar ]) charsAsString ;
: cipherD(s, key) cipherE(s, 26 key - ) ;</lang>
: cipherD(s, key) cipherE(s, 26 key - ) ;</syntaxhighlight>


{{out}}
{{out}}
Line 4,898: Line 4,898:


=={{header|OOC}}==
=={{header|OOC}}==
<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,916: Line 4,916:
str println()
str println()
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>$ ./caesar 8 "This should be a fairly original sentence."
<pre>$ ./caesar 8 "This should be a fairly original sentence."
Line 4,924: Line 4,924:


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


=={{header|Pascal}}==
=={{header|Pascal}}==
<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,968: Line 4,968:
writeln ('Decrypted message: ', message);
writeln ('Decrypted message: ', message);
readln;
readln;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>>: ./CaesarCipher
<pre>>: ./CaesarCipher
Line 4,978: Line 4,978:
=={{header|Perl}}==
=={{header|Perl}}==


<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,989: Line 4,989:
print "msg: $msg\nenc: $enc\ndec: $dec\n";
print "msg: $msg\nenc: $enc\ndec: $dec\n";
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 4,997: Line 4,997:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<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,018: Line 5,018:
<span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">caesar</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">caesar</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">caesar</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">26</span><span style="color: #0000FF;">-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">e</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">r</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">caesar</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">26</span><span style="color: #0000FF;">-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">e</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">r</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 5,028: Line 5,028:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang=php><?php
function caesarEncode( $message, $key ){
function caesarEncode( $message, $key ){
$plaintext = strtolower( $message );
$plaintext = strtolower( $message );
Line 5,046: Line 5,046:


echo caesarEncode( "The quick brown fox Jumped over the lazy Dog", 12 ), "\n";
echo caesarEncode( "The quick brown fox Jumped over the lazy Dog", 12 ), "\n";
?></lang>
?></syntaxhighlight>
{{out}}
{{out}}
<pre>ftq cguow ndaiz raj vgybqp ahqd ftq xmlk pas</pre>
<pre>ftq cguow ndaiz raj vgybqp ahqd ftq xmlk pas</pre>
Line 5,052: Line 5,052:
Or, using PHP's '''strtr()''' built-in function
Or, using PHP's '''strtr()''' built-in function


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


function caesarEncode($message, $key) {
function caesarEncode($message, $key) {
Line 5,060: Line 5,060:
}
}


echo caesarEncode('THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG', 12), PHP_EOL;</lang>
echo caesarEncode('THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG', 12), PHP_EOL;</syntaxhighlight>


{{out}}
{{out}}
Line 5,066: Line 5,066:


=={{header|Picat}}==
=={{header|Picat}}==
<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,089: Line 5,089:
M.put(Lower[I],Lower[II])
M.put(Lower[I],Lower[II])
end.
end.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,098: Line 5,098:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<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)
(pack
(pack
(mapcar '((C) (cadr (nth (member C *Letters) Key)))
(mapcar '((C) (cadr (nth (member C *Letters) Key)))
(chop (uppc Str)) ) ) )</lang>
(chop (uppc Str)) ) ) )</syntaxhighlight>
Test:
Test:
<pre>: (caesar "IBM" 25)
<pre>: (caesar "IBM" 25)
Line 5,117: Line 5,117:
=={{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.
<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,124: Line 5,124:
string decoded = c->decrypt(msg_s11);
string decoded = c->decrypt(msg_s11);


write("%s\n%s\n%s\n%s\n", msg, msg_s2, msg_s11, decoded);</lang>
write("%s\n%s\n%s\n%s\n", msg, msg_s2, msg_s11, decoded);</syntaxhighlight>


{{out}}
{{out}}
Line 5,135: Line 5,135:


=={{header|PL/I}}==
=={{header|PL/I}}==
<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,154: Line 5,154:
put skip list ('Decyphered text=', text);
put skip list ('Decyphered text=', text);


end caesar;</lang>
end caesar;</syntaxhighlight>
{{out}} with offset of 5:
{{out}} with offset of 5:
<pre>
<pre>
Line 5,163: Line 5,163:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang Powershell># Author: M. McNabb
<syntaxhighlight lang=Powershell># Author: M. McNabb
function Get-CaesarCipher
function Get-CaesarCipher
{
{
Line 5,237: Line 5,237:
$OutText = $null
$OutText = $null
}
}
}</lang>
}</syntaxhighlight>
Usage examples:
Usage examples:
<pre>
<pre>
Line 5,258: Line 5,258:
{{Works with|SWI-Prolog}}
{{Works with|SWI-Prolog}}
{{libheader|clpfd}}
{{libheader|clpfd}}
<lang Prolog>:- use_module(library(clpfd)).
<syntaxhighlight lang=Prolog>:- use_module(library(clpfd)).


caesar :-
caesar :-
Line 5,290: Line 5,290:


% compute values of V1 and V2
% compute values of V1 and V2
label([A, V1, V2]).</lang>
label([A, V1, V2]).</syntaxhighlight>
{{out}}
{{out}}
<pre> ?- caesar.
<pre> ?- caesar.
Line 5,301: Line 5,301:
=={{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.
<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,337: Line 5,337:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
{{out}}
{{out}}
<pre> Plain text = "The quick brown fox jumped over the lazy dogs."
<pre> Plain text = "The quick brown fox jumped over the lazy dogs."
Line 5,344: Line 5,344:
===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.
<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,364: Line 5,364:
Wend
Wend
ProcedureReturn result
ProcedureReturn result
EndProcedure</lang>
EndProcedure</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<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,377: Line 5,377:
enc = caesar(msg, 11)
enc = caesar(msg, 11)
print enc
print enc
print caesar(enc, 11, decode = True)</lang>
print caesar(enc, 11, decode = True)</syntaxhighlight>
{{out}}
{{out}}
<pre>The quick brown fox jumped over the lazy dogs
<pre>The quick brown fox jumped over the lazy dogs
Line 5,384: Line 5,384:
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>)
<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,398: Line 5,398:
enc = caesar(msg, 11)
enc = caesar(msg, 11)
print enc
print enc
print caesar(enc, 11, decode = True)</lang>
print caesar(enc, 11, decode = True)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,408: Line 5,408:
Variant with memoization of translation tables
Variant with memoization of translation tables
{{works with|Python|3.x}}
{{works with|Python|3.x}}
<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,418: Line 5,418:
string.ascii_uppercase[k:] + string.ascii_uppercase[:k] +
string.ascii_uppercase[k:] + string.ascii_uppercase[:k] +
string.ascii_lowercase[k:] + string.ascii_lowercase[:k])
string.ascii_lowercase[k:] + string.ascii_lowercase[:k])
return s.translate(table)</lang>
return s.translate(table)</syntaxhighlight>


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


Line 5,431: Line 5,431:
print(caesar(msg, 11))
print(caesar(msg, 11))
print(caesar(caesar(msg, 11), 11, True))
print(caesar(caesar(msg, 11), 11, True))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 5,444: Line 5,444:
{{works with|True BASIC}} Note that TrueBasic uses '!' for comments
{{works with|True BASIC}} Note that TrueBasic uses '!' for comments
{{trans|BASIC256}}
{{trans|BASIC256}}
<lang QBasic>LET dec$ = ""
<syntaxhighlight lang=QBasic>LET dec$ = ""
LET tipo$ = "cleartext "
LET tipo$ = "cleartext "


Line 5,475: Line 5,475:
END IF
END IF
NEXT i
NEXT i
END</lang>
END</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==
<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,510: Line 5,510:
=={{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>
<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,539: Line 5,539:




</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 5,555: Line 5,555:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang=racket>
#lang racket
#lang racket
Line 5,575: Line 5,575:
(define (encrypt s) (caesar s 1))
(define (encrypt s) (caesar s 1))
(define (decrypt s) (caesar s -1))
(define (decrypt s) (caesar s -1))
</syntaxhighlight>
</lang>
Example:
Example:
<pre>
<pre>
Line 5,588: Line 5,588:
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo|2015.12}}
{{works with|Rakudo|2015.12}}
<lang perl6>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,602: Line 5,602:
.say for $original, $en, $de;
.say for $original, $en, $de;


say 'OK' if $original eq all( map { .&decrypt(.&encrypt($original)) }, 1..25 );</lang>
say 'OK' if $original eq all( map { .&decrypt(.&encrypt($original)) }, 1..25 );</syntaxhighlight>
{{out}}
{{out}}
<pre>THE FIVE BOXING WIZARDS JUMP QUICKLY
<pre>THE FIVE BOXING WIZARDS JUMP QUICKLY
Line 5,610: Line 5,610:


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


Line 5,638: Line 5,638:
encrypt: :caesar
encrypt: :caesar
decrypt: func spec-of :caesar [caesar src negate key]
decrypt: func spec-of :caesar [caesar src negate key]
</syntaxhighlight>
</lang>
<pre>
<pre>
>> print encrypt "Ceasar Cipher" 4
>> print encrypt "Ceasar Cipher" 4
Line 5,649: Line 5,649:
=={{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.
<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,662: Line 5,662:
( Example )
( Example )
"THEYBROKEOURCIPHEREVERYONECANREADTHIS" 3 ceaser ( returns encrypted string )
"THEYBROKEOURCIPHEREVERYONECANREADTHIS" 3 ceaser ( returns encrypted string )
23 ceaser ( returns decrypted string )</lang>
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.
<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,688: Line 5,688:
return translate(s, substr(@ || @, ky, L), @) /*return the processed text.*/
return translate(s, substr(@ || @, ky, L), @) /*return the processed text.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say '***error***'; say; say arg(1); say; exit 13</lang>
err: say; say '***error***'; say; say arg(1); say; exit 13</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 22 The definition of a trivial program is one that has no bugs </tt>}}
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 22 The definition of a trivial program is one that has no bugs </tt>}}
<pre>
<pre>
Line 5,700: Line 5,700:
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.
<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,721: Line 5,721:
return translate(s, substr(@ || @, ky, L), @) /*return the processed text.*/
return translate(s, substr(@ || @, ky, L), @) /*return the processed text.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say '***error***'; say; say arg(1); say; exit 13</lang>
err: say; say '***error***'; say; say arg(1); say; exit 13</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 31 Batman's hood is called a "cowl" (old meaning). </tt>}}
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 31 Batman's hood is called a "cowl" (old meaning). </tt>}}
<pre>
<pre>
Line 5,731: Line 5,731:


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


Line 5,789: Line 5,789:
next
next
return str
return str
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 5,805: Line 5,805:


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


Line 5,817: Line 5,817:
encypted = "THEYBROKEOURCIPHEREVERYONECANREADTHIS".caesar_cipher(3)
encypted = "THEYBROKEOURCIPHEREVERYONECANREADTHIS".caesar_cipher(3)
decrypted = encypted.caesar_cipher(-3)
decrypted = encypted.caesar_cipher(-3)
</syntaxhighlight>
</lang>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<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,840: Line 5,840:
cipher$ = cipher$;code$
cipher$ = cipher$;code$
next i
next i
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>
{{out}}
{{out}}
<pre>Gimme a ofset:?9
<pre>Gimme a ofset:?9
Line 5,849: Line 5,849:
=={{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.
<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,884: Line 5,884:
let _ = writeln!(&mut io::stderr(), "ERROR: {}", msg);
let _ = writeln!(&mut io::stderr(), "ERROR: {}", msg);
process::exit(code);
process::exit(code);
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<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,898: Line 5,898:
def decode(text:String, key:Int)=encode(text,-key)
def decode(text:String, key:Int)=encode(text,-key)
private def rot(a:IndexedSeq[Char], c:Char, key:Int)=a((c-a.head+key+a.size)%a.size)
private def rot(a:IndexedSeq[Char], c:Char, key:Int)=a((c-a.head+key+a.size)%a.size)
}</lang>
}</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)
println("Ciphertext => " + encoded)
println("Ciphertext => " + encoded)
println("Decrypted => " + Caesar.decode(encoded, 3))</lang>
println("Decrypted => " + Caesar.decode(encoded, 3))</syntaxhighlight>
{{out}}
{{out}}
<pre>Plaintext => The five boxing wizards jump quickly
<pre>Plaintext => The five boxing wizards jump quickly
Line 5,912: Line 5,912:
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.
<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,923: Line 5,923:
def encode(c: Char) = if (as.contains(c)) bs(as.indexOf(c)) else c
def encode(c: Char) = if (as.contains(c)) bs(as.indexOf(c)) else c
def decode(c: Char) = if (bs.contains(c)) as(bs.indexOf(c)) else c
def decode(c: Char) = if (bs.contains(c)) as(bs.indexOf(c)) else c
}</lang>
}</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))
println("Plaintext => " + text)
println("Plaintext => " + text)
println("Ciphertext => " + encoded)
println("Ciphertext => " + encoded)
println("Decrypted => " + encoded.map(c => myCaeser.decode(c)))</lang>
println("Decrypted => " + encoded.map(c => myCaeser.decode(c)))</syntaxhighlight>


{{out}}
{{out}}
Line 5,939: Line 5,939:
=={{header|Scheme}}==
=={{header|Scheme}}==


<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,966: Line 5,966:
(display (string-map caesar msg))
(display (string-map caesar msg))
(newline)
(newline)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,975: Line 5,975:
=={{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.
<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,011: Line 6,011:
/\n\n/! s/\n([^\n])/\1\n/
/\n\n/! s/\n([^\n])/\1\n/
t loop
t loop
s/\n\n.*//</lang>
s/\n\n.*//</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,026: Line 6,026:


=={{header|Seed7}}==
=={{header|Seed7}}==
<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,054: Line 6,054:
writeln("Encrypted: " <& rot(testText, exampleKey));
writeln("Encrypted: " <& rot(testText, exampleKey));
writeln("Decrypted: " <& rot(rot(testText, exampleKey), 26 - exampleKey));
writeln("Decrypted: " <& rot(rot(testText, exampleKey), 26 - exampleKey));
end func;</lang>
end func;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,064: Line 6,064:
=={{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.
<lang sequencel>import <Utilities/Sequence.sl>;
<syntaxhighlight lang=sequencel>import <Utilities/Sequence.sl>;
import <Utilities/Conversion.sl>;
import <Utilities/Conversion.sl>;


Line 6,095: Line 6,095:
"Input: \t" ++ args[1] ++ "\n" ++
"Input: \t" ++ args[1] ++ "\n" ++
"Encrypted:\t" ++ encrypted ++ "\n" ++
"Encrypted:\t" ++ encrypted ++ "\n" ++
"Decrypted:\t" ++ decrypted;</lang>
"Decrypted:\t" ++ decrypted;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,106: Line 6,106:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<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,118: Line 6,118:
say "msg: #{msg}";
say "msg: #{msg}";
say "enc: #{enc}";
say "enc: #{enc}";
say "dec: #{dec}";</lang>
say "dec: #{dec}";</syntaxhighlight>


{{out}}
{{out}}
Line 6,129: Line 6,129:
=={{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.
<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,140: Line 6,140:
100 LET C$=C$+L$
100 LET C$=C$+L$
110 NEXT I
110 NEXT I
120 PRINT C$</lang>
120 PRINT C$</syntaxhighlight>
{{in}}
{{in}}
<pre>12
<pre>12
Line 6,156: Line 6,156:
{{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!
<lang Smalltalk>'THE QUICK BROWN FOX' rot:3 -> 'WKH TXLFN EURZQ IRA' </lang>
<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:
<lang smalltalk>
<syntaxhighlight lang=smalltalk>
!CharacterArray methodsFor:'encoding'!
!CharacterArray methodsFor:'encoding'!
rot:n
rot:n
Line 6,178: Line 6,178:
^ self
^ self


</syntaxhighlight>
</lang>


=={{header|SSEM}}==
=={{header|SSEM}}==
Line 6,186: Line 6,186:


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.
<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,204: Line 6,204:
00000000000001110000000000000000 16. Stop
00000000000001110000000000000000 16. Stop
11010000000000000000000000000000 17. 11
11010000000000000000000000000000 17. 11
01011000000000000000000000000000 18. 26</lang>
01011000000000000000000000000000 18. 26</syntaxhighlight>


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


<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,218: Line 6,218:


caesar("layout", 20)
caesar("layout", 20)
fusion</lang>
fusion</syntaxhighlight>


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


=={{header|Tcl}}==
=={{header|Tcl}}==
<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,329: Line 6,329:
string map $decryptMap $text
string map $decryptMap $text
}
}
}</lang>
}</syntaxhighlight>
Demonstrating:
Demonstrating:
<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,337: Line 6,337:
puts "Original message = $txt"
puts "Original message = $txt"
puts "Encrypted message = $enc"
puts "Encrypted message = $enc"
puts "Decrypted message = $dec"</lang>
puts "Decrypted message = $dec"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,346: Line 6,346:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<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,369: Line 6,369:


DECODED = EXCHANGE (encoded,secret2abc)
DECODED = EXCHANGE (encoded,secret2abc)
PRINT "encoded decoded ",decoded</lang>
PRINT "encoded decoded ",decoded</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,379: Line 6,379:
=={{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.
<lang txr>@(next :args)
<syntaxhighlight lang=txr>@(next :args)
@(cases)
@(cases)
@{key /[0-9]+/}
@{key /[0-9]+/}
Line 6,401: Line 6,401:
encoded: @{text :filter enc}
encoded: @{text :filter enc}
decoded: @{text :filter dec}
decoded: @{text :filter dec}
@(end)</lang>
@(end)</syntaxhighlight>
{{out}}
{{out}}
<pre>$ ./txr caesar.txr 12 'Hello, world!'
<pre>$ ./txr caesar.txr 12 'Hello, world!'
Line 6,412: Line 6,412:


=={{header|TypeScript}}==
=={{header|TypeScript}}==
<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,425: Line 6,425:


console.log('Enciphered: ' + encoded);
console.log('Enciphered: ' + encoded);
console.log('Deciphered: ' + decoded);</lang>
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.
<lang bash>caesar() {
<syntaxhighlight lang=bash>caesar() {
local OPTIND
local OPTIND
local encrypt n=0
local encrypt n=0
Line 6,485: Line 6,485:
echo "original: $txt"
echo "original: $txt"
echo "encrypted: $enc"
echo "encrypted: $enc"
echo "decrypted: $dec"</lang>
echo "decrypted: $dec"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,493: Line 6,493:


=={{header|Ursa}}==
=={{header|Ursa}}==
<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,520: Line 6,520:
end if
end if
end for
end for
out endl console</lang>
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.
<lang Ursala>#import std
<syntaxhighlight lang=Ursala>#import std
#import nat
#import nat


Line 6,534: Line 6,534:
#show+ # exhaustive test
#show+ # exhaustive test


test = ("n". <.enc"n",dec"n"+ enc"n"> plaintext)*= nrange/1 25</lang>
test = ("n". <.enc"n",dec"n"+ enc"n"> plaintext)*= nrange/1 25</syntaxhighlight>
{{out}}
{{out}}
<pre style="overflow: auto; height: 6em;">
<pre style="overflow: auto; height: 6em;">
Line 6,590: Line 6,590:
=={{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.
<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,622: Line 6,622:
println(encrypt(test_case, -1));
println(encrypt(test_case, -1));
println(decrypt(encrypt(test_case, -1), -1));
println(decrypt(encrypt(test_case, -1), -1));
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 6,633: Line 6,633:
=={{header|VBA}}==
=={{header|VBA}}==


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


Line 6,668: Line 6,668:
Caesar_Cipher = strTemp
Caesar_Cipher = strTemp
End Function
End Function
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 6,676: Line 6,676:
=={{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.
<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,712: Line 6,712:


End Function
End Function
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 6,723: Line 6,723:
=={{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.
<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,733: Line 6,733:
Char(1)
Char(1)
}
}
}</lang>
}</syntaxhighlight>


{{out}} with key 13:
{{out}} with key 13:
Line 6,744: Line 6,744:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{trans|C#}}
{{trans|C#}}
<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,774: Line 6,774:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre>Pack my box with five dozen liquor jugs.
<pre>Pack my box with five dozen liquor jugs.
Line 6,781: Line 6,781:


=={{header|Wortel}}==
=={{header|Wortel}}==
<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,798: Line 6,798:
]
]
!!ceasar "abc $%^ ABC" 10
!!ceasar "abc $%^ ABC" 10
}</lang>
}</syntaxhighlight>
Returns:
Returns:
<pre>"klm $%^ KLM"</pre>
<pre>"klm $%^ KLM"</pre>
Line 6,804: Line 6,804:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<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,829: Line 6,829:
var encoded = Caesar.encrypt("Bright vixens jump; dozy fowl quack.", 8)
var encoded = Caesar.encrypt("Bright vixens jump; dozy fowl quack.", 8)
System.print(encoded)
System.print(encoded)
System.print(Caesar.decrypt(encoded, 8))</lang>
System.print(Caesar.decrypt(encoded, 8))</syntaxhighlight>


{{out}}
{{out}}
Line 6,840: Line 6,840:
{{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}}
<lang asm> # Author: Ettore Forigo - Hexwell
<syntaxhighlight lang=asm> # Author: Ettore Forigo - Hexwell


.intel_syntax noprefix
.intel_syntax noprefix
Line 6,941: Line 6,941:
mov eax, 0 # 0
mov eax, 0 # 0
leave
leave
ret # return 0</lang>
ret # return 0</syntaxhighlight>
Usage:
Usage:
<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</lang>
abc</syntaxhighlight>


=={{header|XBasic}}==
=={{header|XBasic}}==
{{trans|Modula-2}}
{{trans|Modula-2}}
{{works with|Windows XBasic}}
{{works with|Windows XBasic}}
<lang xbasic>
<syntaxhighlight lang=xbasic>
PROGRAM "caesarcipher"
PROGRAM "caesarcipher"
VERSION "0.0001"
VERSION "0.0001"
Line 7,009: Line 7,009:
END FUNCTION e$
END FUNCTION e$
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 7,018: Line 7,018:


=={{header|XBS}}==
=={{header|XBS}}==
<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,054: Line 7,054:


log(e);
log(e);
log(d);</lang>
log(d);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 7,062: Line 7,062:


=={{header|XLISP}}==
=={{header|XLISP}}==
<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,077: Line 7,077:


(defun caesar-decode (text key)
(defun caesar-decode (text key)
(caesar-encode text (- 26 key)))</lang>
(caesar-encode text (- 26 key)))</syntaxhighlight>
Test it in a REPL:
Test it in a REPL:
<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,087: Line 7,087:
[3] (caesar-decode caesar-test 14)
[3] (caesar-decode caesar-test 14)


"CAESAR: Who is it in the press that calls on me? I hear a tongue, shriller than all the music, Cry 'Caesar!' Speak; Caesar is turn'd to hear."</lang>
"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}}==
Line 7,093: Line 7,093:
Usage: caesar key <infile.txt >outfile.xxx
Usage: caesar key <infile.txt >outfile.xxx


<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,105: Line 7,105:
ChOut(0, C);
ChOut(0, C);
until C=$1A; \EOF
until C=$1A; \EOF
]</lang>
]</syntaxhighlight>


Example outfile.xxx:
Example outfile.xxx:
Line 7,113: Line 7,113:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<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,148: Line 7,148:


return res$
return res$
end sub</lang>
end sub</syntaxhighlight>
{{out}}
{{out}}
<pre>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.
Line 7,157: Line 7,157:


=={{header|zkl}}==
=={{header|zkl}}==
<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,163: Line 7,163:
ltrs:=String(letters[n,sz],letters[0,n],letters[m,sz],letters[26,n]);
ltrs:=String(letters[n,sz],letters[0,n],letters[m,sz],letters[26,n]);
str.translate(letters,ltrs)
str.translate(letters,ltrs)
}</lang>
}</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);
println("text = ",text);
println("text = ",text);
println("encoded(%d) = %s".fmt(N,code));
println("encoded(%d) = %s".fmt(N,code));
println("decoded = ",caesarCodec(code,N,False));</lang>
println("decoded = ",caesarCodec(code,N,False));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 7,178: Line 7,178:


=={{header|zonnon}}==
=={{header|zonnon}}==
<lang zonnon>
<syntaxhighlight lang=zonnon>
module Caesar;
module Caesar;
const
const
Line 7,236: Line 7,236:
writeln(txt," -c-> ",cipher," -d-> ",decipher)
writeln(txt," -c-> ",cipher," -d-> ",decipher)
end Caesar.
end Caesar.
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 7,246: Line 7,246:
=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
{{trans|BBC BASIC}}
{{trans|BBC BASIC}}
<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,259: Line 7,259:
1050 NEXT i
1050 NEXT i
1060 RETURN
1060 RETURN
</syntaxhighlight>
</lang>
{{trans|Yabasic}}
{{trans|Yabasic}}
<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
Line 7,290: Line 7,290:
1170 LET r$=r$+p$(delta)
1170 LET r$=r$+p$(delta)
1180 NEXT i
1180 NEXT i
1190 RETURN </lang>
1190 RETURN </syntaxhighlight>
{{omit from|GUISS}}
{{omit from|GUISS}}