Caesar cipher: Difference between revisions
→{{header|langur}}
imported>Arakov |
Langurmonkey (talk | contribs) |
||
(20 intermediate revisions by 15 users not shown) | |||
Line 383:
</pre>
=={{header|Ada}}==
<syntaxhighlight lang="ada">
with Ada.Text_IO; use Ada.Text_IO;
procedure Caesar is
-- Base function to encrypt a character
function Cipher(Char_To_Encrypt: Character; Shift: Integer; Base: Character) return Character is
Base_Pos : constant Natural := Character'Pos(Base);
begin
return
end
-- Function to encrypt a character
function Encrypt_Char(Char_To_Encrypt: Character; Shift:
begin
case Char_To_Encrypt is
when 'A'..'Z' =>
-- Encrypt uppercase letters
return Cipher (Char_To_Encrypt, Shift, 'A');
-- Encrypt lowercase letters
return Cipher (Char_To_Encrypt, Shift, 'a');
when others =>
-- Leave other characters unchanged
return Char_To_Encrypt;
end case;
end Encrypt_Char;
-- Function to decrypt a character
function Decrypt_Char(Char_To_Decrypt: Character; Shift: Integer) return Character is
begin
return Encrypt_Char(Char_To_Decrypt, -Shift);
end Decrypt_Char;
-- Shift value (can be any positive integer)
Encrypted_Message: String(Message'Range);
Decrypted_Message: String(Message'Range);
begin
-- Encrypt the message
for I in Message'Range loop
Encrypted_Message(I) := Encrypt_Char(Message(I), Shift);
end loop;
-- Decrypt the encrypted message
for I in Message'Range loop
Decrypted_Message(I) := Decrypt_Char(Encrypted_Message(I), Shift);
end loop;
-- Display results
Put_Line("Plaintext: " & Message);
Put_Line("Ciphertext: " & Encrypted_Message);
Put_Line("Decrypted Ciphertext: " & Decrypted_Message);
end Caesar;
</syntaxhighlight>
{{out}}
<pre>> ./caesar
The five boxing wizards jump quickly
Plaintext:
Ciphertext:
Decrypted Ciphertext:
</pre>
=={{header|ALGOL 68}}==
{{trans|Ada|Note: This specimen retains the original [[#Ada|Ada]] coding style.}}
Line 1,220 ⟶ 1,236:
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|QBasic}}
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">
Line 1,248 ⟶ 1,265:
250 end
</syntaxhighlight>
{{
<pre> >run
If decrypting enter <d> -- else press enter ?
Line 1,259 ⟶ 1,276:
Enter ciphertext > ? HT CJQZMXMVAO DN APGG JA ZZGN.
MY HOVERCRAFT IS FULL OF EELS.</pre>
==={{header|GW-BASIC}}===
{{works with|Chipmunk Basic}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
{{works with|MSX BASIC}}
{{trans|Chipmunk Basic}}
<syntaxhighlight lang="qbasic">10 REM Caesar cipher
20 CLS
30 DEC$ = ""
40 TYPE$ = "cleartext "
50 PRINT "If decrypting enter "+"<d> "+" -- else press enter "; : INPUT DEC$
60 INPUT "Enter offset > "; IOFFSET
70 IF DEC$ = "d" THEN IOFFSET = 26-IOFFSET: TYPE$ = "ciphertext "
110 PRINT "Enter "+TYPE$+"> ";
120 INPUT CAD$
140 LONGITUD = LEN(CAD$)
150 FOR I = 1 TO LONGITUD
160 ITEMP = ASC(MID$(CAD$,I,1))
170 IF ITEMP > 64 AND ITEMP < 91 THEN ITEMP = ((ITEMP-65)+IOFFSET) MOD 26 : PRINT CHR$(ITEMP+65); : ELSE PRINT CHR$(ITEMP);
230 NEXT I
240 PRINT
250 END</syntaxhighlight>
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
=={{header|Beads}}==
Line 1,835 ⟶ 1,879:
=> "The Quick Brown Fox jumped over the lazy dog"
</pre>
Fast version, using str/escape:
<syntaxhighlight lang="clojure">(defn fast-caesar [n s]
(let [m (mod n 26)
upper (map char (range 65 91))
upper->new (zipmap upper (drop m (cycle upper)))
lower (map char (range 97 123))
lower->new (zipmap lower (drop m (cycle lower)))]
(clojure.string/escape s (merge upper->new lower->new))))</syntaxhighlight>
output:<pre>
(fast-caesar 12 "The Quick Brown Fox jumped over the lazy dog")
=> "Ftq Cguow Ndaiz Raj vgybqp ahqd ftq xmlk pas"
</pre>
=={{header|COBOL}}==
[[COBOL-85]] ASCII or EBCIDIC
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
WORKING-STORAGE SECTION.
01 MSG
VALUE "The quick brown fox jumped over the lazy dog.".
01 OFFSET PIC
01 FROM-CHARS PIC X(52).
01 TO-CHARS PIC X(52).
01 TABL.
02 PIC X(26) VALUE "abcdefghijklmnopqrstuvwxyz".
02 PIC X(26) VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
02 PIC X(26) VALUE "abcdefghijklmnopqrstuvwxyz".
02 PIC X(26) VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
BEGIN.
DISPLAY
STOP RUN.
ENCRYPT.
MOVE TABL (1:52) TO FROM-CHARS
MOVE TABL (1 + OFFSET:52) TO TO-CHARS
INSPECT MSG CONVERTING FROM-CHARS TO TO-CHARS.
DECRYPT.
MOVE TABL (1 + OFFSET:52) TO FROM-CHARS
MOVE TABL (1:52) TO TO-CHARS
INSPECT MSG CONVERTING FROM-CHARS TO TO-CHARS.
END PROGRAM CAESAR.</syntaxhighlight>
{{out}}
<pre>
Line 1,883 ⟶ 1,938:
</pre>
{{works with|
<syntaxhighlight lang="
IDENTIFICATION DIVISION.
PROGRAM-ID. caesar-cipher.
Line 1,891 ⟶ 1,947:
REPOSITORY.
FUNCTION encrypt
FUNCTION decrypt.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 plaintext PIC X(50).
01 offset
01 encrypted-str PIC X(50).
PROCEDURE DIVISION.
DISPLAY "Enter a message to encrypt: " WITH NO ADVANCING
ACCEPT plaintext
DISPLAY "Enter the amount to shift by: " WITH NO ADVANCING
ACCEPT offset
MOVE encrypt(offset, plaintext) TO encrypted-str
DISPLAY "Encrypted: " encrypted-str
DISPLAY "Decrypted: " decrypt(offset, encrypted-str).
END PROGRAM caesar-cipher.
IDENTIFICATION DIVISION.
FUNCTION-ID. encrypt.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 i
01 a USAGE BINARY-CHAR.
LINKAGE SECTION.
01 offset
01 str PIC X(50).
01 encrypted-str PIC X(50).
PROCEDURE DIVISION USING offset, str RETURNING encrypted-str.
PERFORM VARYING i FROM 1 BY 1 UNTIL i > LENGTH(str)
EXIT PERFORM CYCLE
END-IF
IF str(i:1) IS ALPHABETIC-UPPER
ELSE
MOVE
END-IF
MOVE CHAR(MOD(ORD(str(i:1)) - a + offset, 26) + a)
END-PERFORM
EXIT FUNCTION.
END FUNCTION encrypt.
IDENTIFICATION DIVISION.
FUNCTION-ID. decrypt.
Line 1,953 ⟶ 2,007:
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION encrypt.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 decrypt-offset
LINKAGE SECTION.
01 offset
01 str PIC X(50).
01 decrypted-str PIC X(50).
PROCEDURE DIVISION USING offset, str RETURNING decrypted-str.
SUBTRACT
MOVE
EXIT FUNCTION.
END FUNCTION decrypt.</syntaxhighlight>
Line 1,978 ⟶ 2,031:
Decrypted: The quick brown fox jumps over the lazy dog.
</pre>
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">cipher = (msg, rot) ->
Line 2,403 ⟶ 2,457:
Encrypted: Ufhp rd gtc bnym knaj itejs qnvztw ozlx.
Decrypted: Pack my box with five dozen liquor jugs.</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
func$ crypt str$ key .
for c$ in strchars str$
c = strcode c$
if c >= 65 and c <= 90
c = (c + key - 65) mod 26 + 65
elif c >= 97 and c <= 122
c = (c + key - 97) mod 26 + 97
.
enc$ &= strchar c
.
return enc$
.
enc$ = crypt "Rosetta Code" 4
print enc$
print crypt enc$ -4
</syntaxhighlight>
=={{header|EDSAC order code}}==
The EDSAC had only upper-case letters, which were represented by 5-bit codes.
Line 2,645 ⟶ 2,718:
ENTER MESSAGE
</pre>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
Line 2,781 ⟶ 2,855:
if (-1 < index)
{
^ Letters[(_key+index).mod
}
else
Line 2,788 ⟶ 2,862:
if (-1 < index)
{
^ BigLetters[(_key+index).mod
}
else
Line 2,811 ⟶ 2,885:
console.printLine("Original text :",TestText);
var encryptedText := TestText.encrypt
console.printLine("Encrypted text:",encryptedText);
var decryptedText := encryptedText.decrypt
console.printLine("Decrypted text:",decryptedText);
Line 2,854 ⟶ 2,928:
Decrypted: The five boxing wizards jump quickly
</pre>
=={{header|Elm}}==
<syntaxhighlight lang="elm">
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
module Main exposing (main)
import Browser
import Html exposing (Html, h2, div, p, input, button, text, textarea)
import Html.Attributes exposing (style, class, placeholder, value)
import Html.Events exposing (onInput, onClick)
-- MAIN
main =
Browser.sandbox { init = init, update = update, view = view }
-- MODEL
type alias Model =
{ codeKey : Int
, normtext : String
}
init : Model
init =
{ codeKey = 3
, normtext = "" }
-- UPDATE
type Msg
= Change String
| DecKey
| IncKey
update : Msg -> Model -> Model
update msg model =
case msg of
DecKey ->
{ model | codeKey = model.codeKey - 1}
IncKey ->
{ model | codeKey = model.codeKey + 1}
Change newContent ->
{ model | normtext = String.toUpper newContent }
encodeChar : Int -> Char -> Char
encodeChar codeKey character =
if Char.isUpper character then
Char.fromCode (modBy 26 (Char.toCode character - 65 + codeKey) + 65)
else if Char.isLower character then
Char.fromCode (modBy 26 (Char.toCode (Char.toUpper character) - 65 + codeKey) + 65)
else
character
encodeText : Int -> String -> String
encodeText codeKey normtext =
String.map (encodeChar codeKey) normtext
subheads aKey =
if aKey > 0 then "Original"
else if aKey < 0 then "Encrypted text"
else "?"
-- VIEW
view : Model -> Html Msg
view model =
div []
[ div []
[h2 [class "h2style"] [text (subheads model.codeKey)]
, textarea [ class "textframe", placeholder "Write here your text!"
, value model.normtext, onInput Change ] []
]
, div []
[h2 [class "h2style"] [text (subheads (negate model.codeKey))]
, textarea [ class "textframe", value (encodeText model.codeKey model.normtext) ] []]
, div [class "keystyle"] [ button [ class "butstyle", onClick DecKey ] [ text "-1" ]
, text (" Key " ++ String.fromInt model.codeKey)
, button [ class "butstyle", onClick IncKey ] [ text "+1" ]
]
]
</syntaxhighlight>
{{out}}
<pre>
Original: THE QUICK ORANGE FOX JUMPED OVER THE SLOW DOG
Encrypted: WKH TXLFN RUDQJH IRA MXPSHG RYHU WKH VORZ GRJ (used key value 3)
Encrypted: XLI UYMGO SVERKI JSB NYQTIH SZIV XLI WPSA HSK (used key value 4)
Decrypted: THE QUICK ORANGE FOX JUMPED OVER THE SLOW DOG (used key value -3)
Decrypted: THE QUICK ORANGE FOX JUMPED OVER THE SLOW DOG (used key value -4)
Live version with html file calling the elm module as compiled to JavaScript
at https://ellie-app.com/qVvVDKdK6PQa1
</pre>
%% Ceasar cypher in Erlang for the rosetta code wiki.
%% Implemented by J.W. Luiten
Line 3,173 ⟶ 3,351:
</syntaxhighlight>
=={{header|Forth}}==
<syntaxhighlight lang="forth">:
over 32 or [char] a -
dup 0 26 within if
Line 3,179 ⟶ 3,357:
else 2drop then ;
:
over + swap do i c@ over
:
2variable test
s" The five boxing wizards jump quickly!" test 2!
3 test 2@
test 2@ cr type
3
test 2@ cr type</syntaxhighlight>
=={{header|Fortran}}==
{{works with|Fortan 90 and later}}
Line 3,700 ⟶ 3,879:
Encphered text = "wkh txlfn eurzq ira mxpshg ryhu wkh odcb grj"
Decphered text = "the quick brown fox jumped over the lazy dog"</pre>
=={{Header|Insitux}}==
<syntaxhighlight lang="insitux">
(function caeser by of
(let alphabets (proj (map char-code) (range 65 91) (range 97 123))
shifted (.. vec (map (rotate by) alphabets))
table (kv-dict (flatten alphabets) (flatten shifted)))
(... str (map #(or (table %) %) of)))
(let original "The Quick Brown Fox Jumps Over The Lazy Dog."
encrypted (caeser -1 original)
decrypted (caeser 1 encrypted))
(str "Original: " original "
Encrypted: " encrypted "
Decrypted: " decrypted)
</syntaxhighlight>
{{out}}
<pre>
Original: The Quick Brown Fox Jumps Over The Lazy Dog.
Encrypted: Sgd Pthbj Aqnvm Enw Itlor Nudq Sgd Kzyx Cnf.
Decrypted: The Quick Brown Fox Jumps Over The Lazy Dog.
</pre>
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 PROGRAM "CaesarCi.bas"
Line 3,834 ⟶ 4,039:
<syntaxhighlight lang="javascript">function caesar (text, shift) {
return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/./g, function(a) {
return String.fromCharCode(
});
}
Line 3,859 ⟶ 4,064:
.replace(/[^A-Z]/g, '')
.replace(/./g, a =>
String.fromCharCode(
Line 4,041 ⟶ 4,246:
"uifsf jt b ujef jo uif bggbjst pg nfo"
</syntaxhighlight>
=={{header|Koka}}==
<syntaxhighlight lang="koka">
fun encode(s : string, shift : int)
fun encode-char(c)
if c < 'A' || (c > 'Z' && c < 'a') || c > 'z' return c
val base = if c < 'Z' then (c - 'A').int else (c - 'a').int
val rot = (base + shift) % 26
(rot.char + (if c < 'Z' then 'A' else 'a'))
s.map(encode-char)
fun decode(s: string, shift: int)
s.encode(0 - shift)
fun trip(s: string, shift: int)
s.encode(shift).decode(shift)
fun main()
"HI".encode(2).println
"HI".encode(20).println
"HI".trip(10).println
val enc = "The quick brown fox jumped over the lazy dog".encode(11)
enc.println
enc.decode(11).println
</syntaxhighlight>
{{out}}
<pre>
JK
BC
HI
Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr
The quick brown fox jumped over the lazy dog
</pre>
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.5-2
Line 4,083 ⟶ 4,321:
Bright vixens jump; dozy fowl quack.
</pre>
=={{header|LabVIEW}}==
For readability, input is in all caps.<br/>{{VI snippet}}<br/>[[File:LabVIEW_Caesar_cipher.png]]
Line 4,161 ⟶ 4,400:
Using the built-in rotate() function on a number over a range, a number outside of the range will pass through unaltered.
<syntaxhighlight lang="langur">val .rot =
cp2s map(
}
val .s = "A quick brown fox jumped over something."
Line 4,176 ⟶ 4,416:
encrypted: X nrfzh yoltk clu grjmba lsbo pljbqefkd.
decrypted: A quick brown fox jumped over something.</pre>
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">key = 7
Line 5,455 ⟶ 5,696:
=={{header|PureBasic}}==
The case is maintained for alphabetic characters (uppercase/lowercase input = uppercase/lowercase output) while non-alphabetic characters, if present are included and left unchanged in the result.
<syntaxhighlight lang="
Procedure.s CC_encrypt(plainText.s, key, reverse = 0)
;if reverse <> 0 then reverse the encryption (decrypt)
If reverse: reverse = 26: key = 26 - key: EndIf
Line 5,518 ⟶ 5,760:
Wend
ProcedureReturn result
EndProcedure
</syntaxhighlight>
=={{header|Python}}==
<syntaxhighlight lang="python">def caesar(s, k, decode = False):
Line 6,610 ⟶ 6,854:
Decrypted message = The five boxing wizards jump quickly.
</pre>
=={{header|True BASIC}}==
{{works with|QBasic}}
{{trans|BASIC256}}
<syntaxhighlight lang="qbasic">LET dec$ = ""
LET tipo$ = "cleartext "
PRINT "If decrypting enter 'd' -- else press enter ";
INPUT dec$
PRINT "Enter offset ";
INPUT llave
IF dec$ = "d" THEN
LET llave = 26 - llave
LET tipo$ = "ciphertext "
END IF
PRINT "Enter "; tipo$;
INPUT cadena$
LET cadena$ = UCASE$(cadena$)
LET longitud = LEN(cadena$)
FOR i = 1 TO longitud
!LET iTemp = ASC(MID$(cadena$,i,1)) 'QBasic
LET itemp = ORD((cadena$)[i:i+1-1][1:1]) !'True BASIC
IF iTemp > 64 AND iTemp < 91 THEN
!LET iTemp = ((iTemp - 65) + llave) MOD 26 'QBasic
LET iTemp = MOD(((iTemp - 65) + llave), 26) !'True BASIC
PRINT CHR$(iTemp + 65);
ELSE
PRINT CHR$(iTemp);
END IF
NEXT i
END</syntaxhighlight>
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
Line 7,039 ⟶ 7,320:
import rand
const (
lo_abc = 'abcdefghijklmnopqrstuvwxyz'
up_abc = 'ABCDEFGHIJKLMNIPQRSTUVWXYZ'
Line 7,066 ⟶ 7,346:
if nchr > u8(122) {nchr -= 26}
}
else {nchr = chr}
chr_arr << nchr
}
Line 7,108 ⟶ 7,386:
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="
static encrypt(s, key) {
var offset = key % 26
Line 7,140 ⟶ 7,418:
Bright vixens jump; dozy fowl quack.
</pre>
=={{header|X86 Assembly}}==
{{trans|C custom implementation}}
Line 7,453 ⟶ 7,732:
You are encouraged to solve this task according to the task description, using any language you may know.</pre>
=={{header|Zig}}==
<syntaxhighlight lang="zig">
const std = @import("std");
const stdout = @import("std").io.getStdOut().writer();
pub fn rot(txt: []u8, key: u8) void {
for (txt, 0..txt.len) |c, i| {
if (std.ascii.isLower(c)) {
txt[i] = (c - 'a' + key) % 26 + 'a';
} else if (std.ascii.isUpper(c)) {
txt[i] = (c - 'A' + key) % 26 + 'A';
}
}
}
pub fn main() !void {
const key = 3;
var txt = "The five boxing wizards jump quickly".*;
try stdout.print("Original: {s}\n", .{txt});
rot(&txt, key);
try stdout.print("Encrypted: {s}\n", .{txt});
rot(&txt, 26 - key);
try stdout.print("Decrypted: {s}\n", .{txt});
}
</syntaxhighlight>
{{out}}
<pre>
Original: The five boxing wizards jump quickly
Encrypted: Wkh ilyh eralqj zlcdugv mxps txlfnob
Decrypted: The five boxing wizards jump quickly
</pre>
=={{header|zkl}}==
<syntaxhighlight lang="zkl">fcn caesarCodec(str,n,encode=True){
Line 7,473 ⟶ 7,785:
decoded = The five boxing wizards jump quickly
</pre>
=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
|