2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -1,17 +1,20 @@
;Task:
Implement a [[wp:Caesar cipher|Caesar cipher]], both encoding and decoding. <br>
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
<br>So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "monoalphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to [[Vigenère cipher]] with a key of length 1. <br>
Also, [[Rot-13]] is identical to Caesar cipher with key 13.
;See also:
;Related tasks:
* [[Rot-13]]
* [[Substitution Cipher]]
* [[Vigenère Cipher/Cryptanalysis]]
<br>
<br><br>

View file

@ -0,0 +1,7 @@
CAESAR[]
[0] AK CAESAR V
[1] A'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
[2] ((,VA)/,V)A[⎕IO+52|(2×K)+((A,V)-⎕IO)~52]
[3] AV

View file

@ -1,13 +1,9 @@
(defun encipher-char (ch key)
(let*
((c (char-code ch))
(la (char-code #\a)) (lz (char-code #\z))
(ua (char-code #\A)) (uz (char-code #\Z))
(base (cond
((and (>= c la) (<= c lz)) la)
((and (>= c ua) (<= c uz)) ua)
(t nil))))
(if base (code-char (+ (mod (+ (- c base) key) 26) base)) ch)))
(let* ((c (char-code ch)) (la (char-code #\a)) (ua (char-code #\A))
(base (cond ((<= la c (char-code #\z)) la)
((<= ua c (char-code #\Z)) ua)
(nil))))
(if base (code-char (+ (mod (+ (- c base) key) 26) base)) ch)))
(defun caesar-cipher (str key)
(map 'string #'(lambda (c) (encipher-char c key)) str))

View file

@ -0,0 +1,28 @@
open number char monad io string
chars = "ABCDEFGHIJKLMOPQRSTUVWXYZ"
caesar _ _ [] = ""
caesar op key (x::xs) = check shifted ++ caesar op key xs
where orig = indexOf (string.upper $ toString x) chars
shifted = orig `op` key
check val | orig == -1 = x
| val > 24 = trans $ val - 25
| val < 0 = trans $ 25 + val
| else = trans shifted
trans idx = chars:idx
cypher = caesar (+)
decypher = caesar (-)
key = 2
do
putStrLn "A string to encode:"
str <- readStr
putStr "Encoded string: "
cstr <- return <| cypher key str
put cstr
putStrLn ""
putStr "Decoded string: "
put $ decypher key cstr

View file

@ -7,7 +7,7 @@ defmodule Caesar_cipher do
def encode(text, key) do
map = Map.new |> set_map(?a..?z, key) |> set_map(?A..?Z, key)
String.codepoints(text) |> Enum.map_join(fn c -> Dict.get(map, c, c) end)
String.graphemes(text) |> Enum.map_join(fn c -> Map.get(map, c, c) end)
end
end

View file

@ -0,0 +1,16 @@
module Caesar (caesar, uncaesar) where
import Data.Char
caesar, uncaesar :: (Integral a) => a -> String -> String
caesar k = map f
where f c = case generalCategory c of
LowercaseLetter -> addChar 'a' k c
UppercaseLetter -> addChar 'A' k c
_ -> c
uncaesar k = caesar (-k)
addChar :: (Integral a) => Char -> a -> Char -> Char
addChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26)
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c

View file

@ -0,0 +1,32 @@
{-# LANGUAGE LambdaCase #-}
module Main where
import Control.Error (tryRead, tryAt)
import Control.Monad.Trans (liftIO)
import Control.Monad.Trans.Except (ExceptT, runExceptT)
import Data.Char
import System.Exit (die)
import System.Environment (getArgs)
main :: IO ()
main = runExceptT parseKey >>= \case
Left err -> die err
Right k -> interact $ caesar k
parseKey :: (Read a, Integral a) => ExceptT String IO a
parseKey = liftIO getArgs >>=
flip (tryAt "Not enough arguments") 0 >>=
tryRead "Key is not a valid integer"
caesar :: (Integral a) => a -> String -> String
caesar k = map f
where f c = case generalCategory c of
LowercaseLetter -> addChar 'a' k c
UppercaseLetter -> addChar 'A' k c
_ -> c
addChar :: (Integral a) => Char -> a -> Char -> Char
addChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26)
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c

View file

@ -1,17 +0,0 @@
import Data.Char (ord, chr)
import Data.Ix (inRange)
caesar :: Int -> String -> String
caesar k = map f
where
f c
| inRange ('a','z') c = tr 'a' k c
| inRange ('A','Z') c = tr 'A' k c
| otherwise = c
unCaesar :: Int -> String -> String
unCaesar k = caesar (-k)
-- char addition
tr :: Char -> Int -> Char -> Char
tr base offset char = chr $ ord base + (ord char - ord base + offset) `mod` 26

View file

@ -0,0 +1,11 @@
function caesar (text, shift) {
return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/[A-Z]/g, function(a) {
return String.fromCharCode(65+(a.charCodeAt(0)-65+shift)%26);
});
}
// Tests
var text = 'veni, vidi, vici';
for (var i = 0; i<26; i++) {
console.log(i+': '+caesar(text,i));
}

View file

@ -0,0 +1,5 @@
var caesar = (text, shift) => text
.toUpperCase()
.replace(/[^A-Z]/g, '')
.replace(/[A-Z]/g, a =>
String.fromCharCode(65 + (a.charCodeAt(0) - 65 + shift) % 26));

View file

@ -0,0 +1,43 @@
((key, strPlain) => {
// Int -> String -> String
let caesar = (k, s) => s.split('')
.map(c => tr(
inRange(['a', 'z'], c) ? 'a' :
inRange(['A', 'Z'], c) ? 'A' : 0,
k, c
))
.join('');
// Int -> String -> String
let unCaesar = (k, s) => caesar(26 - (k % 26), s);
// Char -> Int -> Char -> Char
let tr = (base, offset, char) =>
base ? (
String.fromCharCode(
ord(base) + (
ord(char) - ord(base) + offset
) % 26
)
) : char;
// [a, a] -> a -> b
let inRange = ([min, max], v) => !(v < min || v > max);
// Char -> Int
let ord = c => c.charCodeAt(0);
// range :: Int -> Int -> [Int]
let range = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// TEST
let strCipher = caesar(key, strPlain),
strDecode = unCaesar(key, strCipher);
return [strCipher, ' -> ', strDecode];
})(114, 'Curio, Cesare venne, e vide e vinse ? ');

View file

@ -1,24 +0,0 @@
<html><head><title>Caesar</title></head>
<body><pre id='x'></pre>
<script type="application/javascript">
function disp(x) {
var e = document.createTextNode(x + '\n');
document.getElementById('x').appendChild(e);
}
function trans(msg, rot) {
return msg.replace(/([a-z])/ig,
function($1) {
var c = $1.charCodeAt(0);
return String.fromCharCode(
c >= 97 ? (c + rot + 26 - 97) % 26 + 97
: (c + rot + 26 - 65) % 26 + 65);
});
}
var msg = "The quick brown f0x Jumped over the lazy Dog 123";
var enc = trans(msg, 3);
var dec = trans(enc, -3);
disp("Original:" + msg + "\nEncoded: " + enc + "\nDecoded: " + dec);
</script></body></html>

View file

@ -0,0 +1,4 @@
s:"there is a tide in the affairs of men"
caesar:{ :[" "=x; x; {x!_ci 97+!26}[y]@_ic[x]-97]}'
caesar[s;1]
"uifsf jt b ujef jo uif bggbjst pg nfo"

View file

@ -0,0 +1,32 @@
local memo = {}
local function make_table(k)
local t = {}
local a, A = ('a'):byte(), ('A'):byte()
for i = 0,25 do
local c = a + i
local C = A + i
local rc = a + (i+k) % 26
local RC = A + (i+k) % 26
t[c], t[C] = rc, RC
end
return t
end
local function caesar(str, k, decode)
k = (decode and -k or k) % 26
local t = memo[k]
if not t then
t = make_table(k)
memo[k] = t
end
local res_t = { str:byte(1,-1) }
for i,c in ipairs(res_t) do
res_t[i] = t[c] or c
end
return string.char(unpack(res_t))
end

View file

@ -1,9 +1,11 @@
from string import ascii_uppercase as abc
def caesar(s, k, decode = False):
trans = dict(zip(abc, abc[(k,26-k)[decode]:] + abc[:(k,26-k)[decode]]))
return ''.join(trans[L] for L in s.upper() if L in abc)
msg = "The quick brown fox jumped over the lazy dogs"
print(caesar(msg, 11))
print(caesar(caesar(msg, 11), 11, True))
import string
def caesar(s, k = 13, decode = False, *, memo={}):
if decode: k = 26 - k
k = k % 26
table = memo.get(k)
if table is None:
table = memo[k] = str.maketrans(
string.ascii_uppercase + string.ascii_lowercase,
string.ascii_uppercase[k:] + string.ascii_uppercase[:k] +
string.ascii_lowercase[k:] + string.ascii_lowercase[:k])
return s.translate(table)

View file

@ -0,0 +1,9 @@
from string import ascii_uppercase as abc
def caesar(s, k, decode = False):
trans = dict(zip(abc, abc[(k,26-k)[decode]:] + abc[:(k,26-k)[decode]]))
return ''.join(trans[L] for L in s.upper() if L in abc)
msg = "The quick brown fox jumped over the lazy dogs"
print(caesar(msg, 11))
print(caesar(caesar(msg, 11), 11, True))

View file

@ -1,22 +1,22 @@
/*REXX pgm: Caesar cypher: Latin alphabet only, no punctuation or blanks*/
/* allowed, all lowercase Latin letters are treated as uppercase. */
arg key p /*get key and text to be cyphered*/
p=space(p,0) /*remove all blanks from text. */
say 'Caesar cypher key:' key
say ' plain text:' p
y=caesar(p, key) ; say ' cyphered:' y
z=caesar(y,-key) ; say ' uncyphered:' z
if z\==p then say "plain text doesn't match uncyphered cyphered text."
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────CAESAR subroutine───────────────────*/
caesar: procedure; arg s,k; @='ABCDEFGHIJKLMNOPQRSTUVWXYZ'; L=length(@)
ak=abs(k)
if ak>length(@)-1 | k==0 | k=='' then call err k 'key is invalid'
_=verify(s,@) /*any illegal char specified ? */
if _\==0 then call err 'unsupported character:' substr(s,_,1)
/*now that error checks are done:*/
if k>0 then ky=k+1 /*either cypher it, or ··· */
else ky=27-ak /* decypher it. */
return translate(s,substr(@||@,ky,L),@)
/*──────────────────────────────────ERR subroutine──────────────────────*/
err: say; say '***error!***'; say; say arg(1); say; exit 13
/*REXX program supports the Caesar cypher for the Latin alphabet only, no punctuation */
/*──────────── or blanks allowed, all lowercase Latin letters are treated as uppercase.*/
parse arg key .; arg . p /*get key & uppercased text to be used.*/
p=space(p,0) /*elide any and all spaces (blanks). */
say 'Caesar cypher key:' key /*echo the Caesar cypher key to console*/
say ' plain text:' p /* " " plain text " " */
y=Caesar(p, key); say ' cyphered:' y /* " " cyphered text " " */
z=Caesar(y,-key); say ' uncyphered:' z /* " " uncyphered text " " */
if z\==p then say "plain text doesn't match uncyphered cyphered text."
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Caesar: procedure; arg s,k; @='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ak=abs(k) /*obtain the absolute value of the key.*/
L=length(@) /*obtain the length of the @ string. */
if ak>length(@)-1 | k==0 then call err k 'key is invalid.'
_=verify(s,@) /*any illegal characters specified ? */
if _\==0 then call err 'unsupported character:' substr(s, _, 1)
if k>0 then ky=k+1 /*either cypher it, or ··· */
else ky=L+1-ak /* decypher it. */
return translate(s, substr(@||@,ky,L),@) /*return the processed text. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say '***error***'; say; say arg(1); say; exit 13

View file

@ -1,22 +1,22 @@
/*REXX pgm: Caesar cypher for almost all keyboard chars including blanks*/
parse arg key p /*get key and text to be cyphered*/
say 'Caesar cypher key:' key
say ' plain text:' p
y=caesar(p, key) ; say ' cyphered:' y
z=caesar(y,-key) ; say ' uncyphered:' z
if z\==p then say "plain text doesn't match uncyphered cyphered text."
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────CAESAR subroutine───────────────────*/
caesar: procedure; parse arg s,k; @='abcdefghijklmnopqrstuvwxyz'
@=translate(@)@'0123456789(){}[]<>' /*add uppercase, digs, group symb*/
@=@'~!@#$%^&*_+:";?,./`-= ''' /*add other characters here. */
/*last char is doubled, REXX quoted syntax rules.*/
L=length(@)
ak=abs(k)
if ak>length(@)-1 | k==0 then call err k 'key is invalid'
_=verify(s,@) /*any illegal char specified ? */
if _\==0 then call err 'unsupported character:' substr(s,_,1)
if k>0 then ky=k+1
else ky=L+1-ak
return translate(s,substr(@||@,ky,L),@)
/*──────────────────────────────────ERR subroutine──────────────────────*/
/*REXX program supports the Caesar cypher for most keyboard characters including blanks.*/
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 ' plain text:' p /* " " plain text " " */
y=Caesar(p, key); say ' cyphered:' y /* " " cyphered text " " */
z=Caesar(y,-key); say ' uncyphered:' z /* " " uncyphered text " " */
if z\==p then say "plain text doesn't match uncyphered cyphered text."
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Caesar: procedure; parse arg s,k; @= 'abcdefghijklmnopqrstuvwxyz'
@=translate(@)@"0123456789(){}[]<>'" /*add uppercase, digitss, group symbols*/
@=@'~!@#$%^&*_+:";?,./`-= ' /*also add other characters to the list*/
L=length(@) /*obtain the length of the @ string. */
ak=abs(k) /*obtain the absolute value of the key.*/
if ak>length(@)-1 | k==0 then call err k 'key is invalid.'
_=verify(s,@) /*any illegal characters specified ? */
if _\==0 then call err 'unsupported character:' substr(s, _, 1)
if k>0 then ky=k+1 /*either cypher it, or ··· */
else ky=L+1-ak /* decypher it. */
return translate(s, substr(@ || @, ky, L), @)
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say '***error***'; say; say arg(1); say; exit 13

View file

@ -0,0 +1,36 @@
use std::io::{self, Write};
use std::fmt::Display;
use std::{env, process};
fn main() {
let shift: u8 = env::args().nth(1)
.unwrap_or_else(|| exit_err("No shift provided", 2))
.parse()
.unwrap_or_else(|e| exit_err(e, 3));
let plain = get_input()
.unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)));
let cipher = plain.chars()
.map(|c| {
let case = if c.is_uppercase() {'A'} else {'a'} as u8;
if c.is_alphabetic() { (((c as u8 - case + shift) % 26) + case) as char } else { c }
}).collect::<String>();
println!("Cipher text: {}", cipher.trim());
}
fn get_input() -> io::Result<String> {
print!("Plain text: ");
try!(io::stdout().flush());
let mut buf = String::new();
try!(io::stdin().read_line(&mut buf));
Ok(buf)
}
fn exit_err<T: Display>(msg: T, code: i32) -> ! {
let _ = writeln!(&mut io::stderr(), "ERROR: {}", msg);
process::exit(code);
}

View file

@ -0,0 +1,13 @@
10 LET t$="PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS"
20 PRINT t$''
30 LET key=RND*25+1
40 LET k=key: GO SUB 1000: PRINT t$''
50 LET k=26-key: GO SUB 1000: PRINT t$
60 STOP
1000 FOR i=1 TO LEN t$
1010 LET c= CODE t$(i)
1020 IF c<65 OR c>90 THEN GO TO 1050
1030 LET c=c+k: IF c>90 THEN LET c=c-90+64
1040 LET t$(i)=CHR$ c
1050 NEXT i
1060 RETURN