Caesar cipher: Difference between revisions

(Added Easylang)
 
(8 intermediate revisions by 6 users not shown)
Line 383:
</pre>
=={{header|Ada}}==
<syntaxhighlight lang="ada">with-- Caesar Cipher Implementation in Ada.Text_IO;
 
with Ada.Text_IO; use Ada.Text_IO;
procedure Caesar is
 
procedure Caesar is
type modulo26 is modulo 26;
 
-- Base function to encrypt a character
function modulo26 (Character: Character; Output: Character) return modulo26 is
function Cipher(Char_To_Encrypt: Character; Shift: Integer; Base: Character) return Character is
Base_Pos : constant Natural := Character'Pos(Base);
begin
return modulo26 (Character'PosVal((Character)+Character'Pos(OutputChar_To_Encrypt) + Shift - Base_Pos) mod 26 + Base_Pos);
end modulo26Cipher;
 
-- Function to encrypt a character
function Character(Val: in modulo26; Output: Character)
function Encrypt_Char(Char_To_Encrypt: Character; Shift: Integer) return Character is
begin
case Char_To_Encrypt is
return Character'Val(Integer(Val)+Character'Pos(Output));
when 'A'..'Z' =>
end Character;
-- Encrypt uppercase letters
 
return Cipher (Char_To_Encrypt, Shift, 'A');
function crypt (Playn: String; Key: modulo26) return String is
Ciph: String(Playn when 'Range);a'..'z' =>
-- Encrypt lowercase letters
return Cipher (Char_To_Encrypt, Shift, 'a');
when others =>
-- Leave other characters unchanged
return Char_To_Encrypt;
end case;
end Encrypt_Char;
 
-- Function to decrypt a character
function Decrypt_Char(Char_To_Decrypt: Character; Shift: Integer) return Character is
begin
return Encrypt_Char(Char_To_Decrypt, -Shift);
for I in Playn'Range loop
end Decrypt_Char;
case Playn(I) is
when 'A' .. 'Z' =>
Ciph(I) := Character(modulo26(Playn(I)+Key), 'A');
when 'a' .. 'z' =>
Ciph(I) := Character(modulo26(Playn(I)+Key), 'a');
when others =>
Ciph(I) := Playn(I);
end case;
end loop;
return Ciph;
end crypt;
 
TextMessage: constant String := Ada.Text_IO.Get_Line;
KeyShift: modulo26Positive := 3; -- Default key from "Commentarii de Bello Gallico" shift cipher
-- Shift value (can be any positive integer)
 
Encrypted_Message: String(Message'Range);
begin -- encryption main program
Decrypted_Message: String(Message'Range);
begin
-- Encrypt the message
for I in Message'Range loop
Encrypted_Message(I) := Encrypt_Char(Message(I), Shift);
end loop;
 
-- Decrypt the encrypted message
Ada.Text_IO.Put_Line("Playn ------------>" & Text);
for I in Message'Range loop
Text := crypt(Text, Key);
Decrypted_Message(I) := Decrypt_Char(Encrypted_Message(I), Shift);
Ada.Text_IO.Put_Line("Ciphertext ----------->" & Text);
end loop;
Ada.Text_IO.Put_Line("Decrypted Ciphertext ->" & crypt(Text, -Key));
 
-- Display results
end Caesar;</syntaxhighlight>
Put_Line("Plaintext: " & Message);
Put_Line("Ciphertext: " & Encrypted_Message);
Put_Line("Decrypted Ciphertext: " & Decrypted_Message);
 
end Caesar;
</syntaxhighlight>
{{out}}
<pre>> ./caesar
The five boxing wizards jump quickly
Plaintext: ------------>The five boxing wizards jump quickly
Ciphertext: ----------->Wkh ilyh eralqj zlcdugv mxps txlfnob
Decrypted Ciphertext: ->The five boxing wizards jump quickly</pre>
</pre>
 
=={{header|ALGOL 68}}==
{{trans|Ada|Note: This specimen retains the original [[#Ada|Ada]] coding style.}}
Line 1,863 ⟶ 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
Line 2,825 ⟶ 2,855:
if (-1 < index)
{
^ Letters[(_key+index).mod:(26)]
}
else
Line 2,832 ⟶ 2,862:
if (-1 < index)
{
^ BigLetters[(_key+index).mod:(26)]
}
else
Line 2,855 ⟶ 2,885:
console.printLine("Original text :",TestText);
var encryptedText := TestText.encrypt:(Key);
 
console.printLine("Encrypted text:",encryptedText);
 
var decryptedText := encryptedText.decrypt:(Key);
 
console.printLine("Decrypted text:",decryptedText);
Line 2,898 ⟶ 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 4,266 ⟶ 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 = ffn(.s, .key) {
cp2s map(ffn(.c) { rotate(rotate(.c, .key, 'a'..'z'), .key, 'A'..'Z') }, s2cp .s)
}
 
 
val .s = "A quick brown fox jumped over something."
Line 4,281 ⟶ 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,560 ⟶ 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="purebasicbasic">Procedure.s CC_encrypt(plainText.s, key, reverse = 0)
Procedure.s CC_encrypt(plainText.s, key, reverse = 0)
;if reverse <> 0 then reverse the encryption (decrypt)
If reverse: reverse = 26: key = 26 - key: EndIf
Line 5,623 ⟶ 5,760:
Wend
ProcedureReturn result
EndProcedure</syntaxhighlight>
</syntaxhighlight>
 
=={{header|Python}}==
<syntaxhighlight lang="python">def caesar(s, k, decode = False):
Line 7,593 ⟶ 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,613 ⟶ 7,785:
decoded = The five boxing wizards jump quickly
</pre>
 
=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
885

edits