new tasks

This commit is contained in:
Ingy döt Net 2013-04-09 00:46:50 -07:00
parent 2a4d27cea0
commit 80737d5a6a
1194 changed files with 15353 additions and 1 deletions

View file

@ -0,0 +1,3 @@
Implement a [[wp:Caesar cipher|Caesar cipher]], both encryption and decryption. The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z). The encryption 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". This simple "monoalphabetic substitution cipher" provides almost no security, because an attacker who has the encrypted 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 key of length 1. Also, [[Rot-13]] is identical to Caesar cipher with key 13.

View file

@ -0,0 +1,2 @@
---
note: Encryption

View file

@ -0,0 +1,42 @@
#!/usr/bin/awk -f
BEGIN {
message = "My hovercraft is full of eels."
key = 1
cypher = caesarEncode(key, message)
clear = caesarDecode(key, cypher)
print "message: " message
print " cypher: " cypher
print " clear: " clear
exit
}
function caesarEncode(key, message) {
return caesarXlat(key, message, "encode")
}
function caesarDecode(key, message) {
return caesarXlat(key, message, "decode")
}
function caesarXlat(key, message, dir, plain, cypher, i, num, s) {
plain = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
cypher = substr(plain, key+1) substr(plain, 1, key)
if (toupper(substr(dir, 1, 1)) == "D") {
s = plain
plain = cypher
cypher = s
}
s = ""
message = toupper(message)
for (i = 1; i <= length(message); i++) {
num = index(plain, substr(message, i, 1))
if (num) s = s substr(cypher, num, 1)
else s = s substr(message, i, 1)
}
return s
}

View file

@ -0,0 +1,36 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define caesar(x) rot(13, x)
#define decaesar(x) rot(13, x)
#define decrypt_rot(x, y) rot((26-x), y)
void rot(int c, char *str)
{
int l = strlen(str);
const char *alpha[2] = { "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
int i;
for (i = 0; i < l; i++)
{
if (!isalpha(str[i]))
continue;
str[i] = alpha[isupper(str[i])][((int)(tolower(str[i])-'a')+c)%26];
}
}
int main()
{
char str[] = "This is a top secret text message!";
printf("Original: %s\n", str);
caesar(str);
printf("Encrypted: %s\n", str);
decaesar(str);
printf("Decrypted: %s\n", str);
return 0;
}

View file

@ -0,0 +1,23 @@
(defn encrypt-character [offset c]
(if (Character/isLetter c)
(let [v (int c)
base (if (>= v (int \a))
(int \a)
(int \A))
offset (mod offset 26)] ;works with negative offsets too!
(char (+ (mod (+ (- v base) offset) 26)
base)))
c))
(defn encrypt [offset text]
(apply str (map #(encrypt-character offset %) text)))
(defn decrypt [offset text]
(encrypt (- 26 offset) text))
(let [text "The Quick Brown Fox Jumps Over The Lazy Dog."
enc (encrypt -1 text)]
(print "Original text:" text "\n")
(print "Encryption:" enc "\n")
(print "Decryption:" (decrypt -1 enc) "\n"))

View file

@ -0,0 +1,10 @@
cipher = (msg, rot) ->
msg.replace /([a-z|A-Z])/g, ($1) ->
c = $1.charCodeAt(0)
String.fromCharCode \
if c >= 97
then (c + rot + 26 - 97) % 26 + 97
else (c + rot + 26 - 65) % 26 + 65
console.log cipher "Hello World", 2
console.log cipher "azAz %^&*()", 3

View file

@ -0,0 +1 @@
ceasar:main("The five boxing wizards jump quickly", 3).

View file

@ -0,0 +1,33 @@
%% Ceasar cypher in Erlang for the rosetta code wiki.
%% Implemented by J.W. Luiten
-module(ceasar).
-export([main/2]).
%% rot: rotate Char by Key places
rot(Char,Key) when (Char >= $A) and (Char =< $Z) or
(Char >= $a) and (Char =< $z) ->
Offset = $A + Char band 32,
N = Char - Offset,
Offset + (N + Key) rem 26;
rot(Char, _Key) ->
Char.
%% key: normalize key.
key(Key) when Key < 0 ->
26 + Key rem 26;
key(Key) when Key > 25 ->
Key rem 26;
key(Key) ->
Key.
main(PlainText, Key) ->
Encode = key(Key),
Decode = key(-Key),
io:format("Plaintext ----> ~s~n", [PlainText]),
CypherText = lists:map(fun(Char) -> rot(Char, Encode) end, PlainText),
io:format("Cyphertext ---> ~s~n", [CypherText]),
PlainText = lists:map(fun(Char) -> rot(Char, Decode) end, CypherText).

View file

@ -0,0 +1,19 @@
: ceasar ( c n -- c )
over 32 or [char] a -
dup 0 26 within if
over + 25 > if 26 - then +
else 2drop then ;
: ceasar-string ( n str len -- )
over + swap do i c@ over ceasar i c! loop drop ;
: ceasar-inverse ( n -- 'n ) 26 swap - 26 mod ;
2variable test
s" The five boxing wizards jump quickly!" test 2!
3 test 2@ ceasar-string
test 2@ cr type
3 ceasar-inverse test 2@ ceasar-string
test 2@ cr type

View file

@ -0,0 +1,43 @@
program Caesar_Cipher
implicit none
integer, parameter :: key = 3
character(43) :: message = "The five boxing wizards jump quickly"
write(*, "(2a)") "Original message = ", message
call encrypt(message)
write(*, "(2a)") "Encrypted message = ", message
call decrypt(message)
write(*, "(2a)") "Decrypted message = ", message
contains
subroutine encrypt(text)
character(*), intent(inout) :: text
integer :: i
do i = 1, len(text)
select case(text(i:i))
case ('A':'Z')
text(i:i) = achar(modulo(iachar(text(i:i)) - 65 + key, 26) + 65)
case ('a':'z')
text(i:i) = achar(modulo(iachar(text(i:i)) - 97 + key, 26) + 97)
end select
end do
end subroutine
subroutine decrypt(text)
character(*), intent(inout) :: text
integer :: i
do i = 1, len(text)
select case(text(i:i))
case ('A':'Z')
text(i:i) = achar(modulo(iachar(text(i:i)) - 65 - key, 26) + 65)
case ('a':'z')
text(i:i) = achar(modulo(iachar(text(i:i)) - 97 - key, 26) + 97)
end select
end do
end subroutine
end program Caesar_Cipher

View file

@ -0,0 +1,57 @@
package main
import (
"fmt"
"strings"
"unicode"
)
type ckey struct {
enc, dec unicode.SpecialCase
}
func newCaesar(k int) (*ckey, bool) {
if k < 1 || k > 25 {
return nil, false
}
i := uint32(k)
r := rune(k)
return &ckey{
unicode.SpecialCase{
{'A', 'Z' - i, [3]rune{r}},
{'Z' - i + 1, 'Z', [3]rune{r - 26}},
{'a', 'z' - i, [3]rune{r}},
{'z' - i + 1, 'z', [3]rune{r - 26}},
},
unicode.SpecialCase{
{'A', 'A' + i - 1, [3]rune{26 - r}},
{'A' + i, 'Z', [3]rune{-r}},
{'a', 'a' + i - 1, [3]rune{26 - r}},
{'a' + i, 'z', [3]rune{-r}},
},
}, true
}
func (ck ckey) encipher(pt string) string {
return strings.ToUpperSpecial(ck.enc, pt)
}
func (ck ckey) decipher(ct string) string {
return strings.ToUpperSpecial(ck.dec, ct)
}
func main() {
pt := "The five boxing wizards jump quickly"
fmt.Println("Plaintext:", pt)
for _, key := range []int{0, 1, 7, 25, 26} {
ck, ok := newCaesar(key)
if !ok {
fmt.Println("Key", key, "invalid")
continue
}
ct := ck.encipher(pt)
fmt.Println("Key", key)
fmt.Println(" Enciphered:", ct)
fmt.Println(" Deciphered:", ck.decipher(ct))
}
}

View file

@ -0,0 +1,59 @@
package main
import (
"fmt"
"strings"
)
type ckey struct {
enc, dec func(rune) rune
}
func newCaesar(k int) (*ckey, bool) {
if k < 1 || k > 25 {
return nil, false
}
rk := rune(k)
return &ckey{
enc: func(c rune) rune {
if c >= 'a' && c <= 'z'-rk || c >= 'A' && c <= 'Z'-rk {
return c + rk
} else if c > 'z'-rk && c <= 'z' || c > 'Z'-rk && c <= 'Z' {
return c + rk - 26
}
return c
},
dec: func(c rune) rune {
if c >= 'a'+rk && c <= 'z' || c >= 'A'+rk && c <= 'Z' {
return c - rk
} else if c >= 'a' && c < 'a'+rk || c >= 'A' && c < 'A'+rk {
return c - rk + 26
}
return c
},
}, true
}
func (ck ckey) encipher(pt string) string {
return strings.Map(ck.enc, pt)
}
func (ck ckey) decipher(ct string) string {
return strings.Map(ck.dec, ct)
}
func main() {
pt := "The five boxing wizards jump quickly"
fmt.Println("Plaintext:", pt)
for _, key := range []int{0, 1, 7, 25, 26} {
ck, ok := newCaesar(key)
if !ok {
fmt.Println("Key", key, "invalid")
continue
}
ct := ck.encipher(pt)
fmt.Println("Key", key)
fmt.Println(" Enciphered:", ct)
fmt.Println(" Deciphered:", ck.decipher(ct))
}
}

View file

@ -0,0 +1,17 @@
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,26 @@
public class Cipher {
public static void main(String[] args) {
String enc = Cipher.encode(
"The quick brown fox Jumped over the lazy Dog", 12);
System.out.println(enc);
System.out.println(Cipher.decode(enc, 12));
}
public static String decode(String enc, int offset) {
return encode(enc, -offset);
}
public static String encode(String enc, int offset) {
offset = offset % 26 + 26;
StringBuilder encoded = new StringBuilder();
for (char i : enc.toLowerCase().toCharArray()) {
if (Character.isLetter(i)) {
int j = (i - 'a' + offset) % 26;
encoded.append((char) (j + 'a'));
} else {
encoded.append(i);
}
}
return encoded.toString();
}
}

View file

@ -0,0 +1,24 @@
<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,30 @@
local function encrypt(text, key)
return text:gsub("%a", function(t)
local base = (t:lower() == t and string.byte('a') or string.byte('A'))
local r = t:byte() - base
r = r + key
r = r%26 -- works correctly even if r is negative
r = r + base
return string.char(r)
end)
end
local function decrypt(text, key)
return encrypt(text, -key)
end
caesar = {
encrypt = encrypt,
decrypt = decrypt,
}
-- test
do
local text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
local encrypted = caesar.encrypt(text, 7)
local decrypted = caesar.decrypt(encrypted, 7)
print("Original text: ", text)
print("Encrypted text: ", encrypted)
print("Decrypted text: ", decrypted)
end

View file

@ -0,0 +1,19 @@
<?php
function caesarEncode( $message, $key ){
$plaintext = strtolower( $message );
$ciphertext = "";
$ascii_a = ord( 'a' );
$ascii_z = ord( 'z' );
while( strlen( $plaintext ) ){
$char = ord( $plaintext );
if( $char >= $ascii_a && $char <= $ascii_z ){
$char = ( ( $key + $char - $ascii_a ) % 26 ) + $ascii_a;
}
$plaintext = substr( $plaintext, 1 );
$ciphertext .= chr( $char );
}
return $ciphertext;
}
echo caesarEncode( "The quick brown fox Jumped over the lazy Dog", 12 ), "\n";
?>

View file

@ -0,0 +1,11 @@
sub encipher {
my ($_, $k, $decode) = @_;
$k = 26 - $k if $decode;
join('', map(chr(((ord(uc $_) - 65 + $k) % 26) + 65), /([a-z])/gi));
}
my $msg = 'THE FIVE BOXING WIZARDS JUMP QUICKLY';
my $enc = encipher($msg, 10);
my $dec = encipher($enc, 10, 'decode');
print "msg: $msg\nenc: $enc\ndec: $dec\n";

View file

@ -0,0 +1,6 @@
(setq *Letters (apply circ (mapcar char (range 65 90))))
(de caesar (Str Key)
(pack
(mapcar '((C) (cadr (nth (member C *Letters) Key)))
(chop (uppc Str)) ) ) )

View file

@ -0,0 +1,33 @@
:- use_module(library(clpfd)).
caesar :-
L1 = "The five boxing wizards jump quickly",
writef("Original : %s\n", [L1]),
% encryption of the sentence
encoding(3, L1, L2) ,
writef("Encoding : %s\n", [L2]),
% deciphering on the encoded sentence
encoding(3, L3, L2),
writef("Decoding : %s\n", [L3]).
% encoding/decoding of a sentence
encoding(Key, L1, L2) :-
maplist(caesar_cipher(Key), L1, L2).
caesar_cipher(_, 32, 32) :- !.
caesar_cipher(Key, V1, V2) :-
V #= Key + V1,
% we verify that we are in the limits of A-Z and a-z.
((V1 #=< 0'Z #/\ V #> 0'Z) #\/ (V1 #=< 0'z #/\ V #> 0'z)
#\/
(V1 #< 0'A #/\ V2 #>= 0'A)#\/ (V1 #< 0'a #/\ V2 #>= 0'a)) #==> A,
% if we are not in these limits A is 1, otherwise 0.
V2 #= V - A * 26,
% compute values of V1 and V2
label([A, V1, V2]).

View file

@ -0,0 +1,15 @@
import string
def caesar(s, k, decode = False):
if decode: k = 26 - k
return s.translate(
string.maketrans(
string.ascii_uppercase + string.ascii_lowercase,
string.ascii_uppercase[k:] + string.ascii_uppercase[:k] +
string.ascii_lowercase[k:] + string.ascii_lowercase[:k]
)
)
msg = "The quick brown fox jumped over the lazy dogs"
print msg
enc = caesar(msg, 11)
print enc
print caesar(enc, 11, decode = True)

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

@ -0,0 +1,11 @@
def caesar(s, k, decode = False):
if decode: k = 26 - k
return "".join([chr((ord(i) - 65 + k) % 26 + 65)
for i in s.upper()
if ord(i) >= 65 and ord(i) <= 90 ])
msg = "The quick brown fox jumped over the lazy dogs"
print msg
enc = caesar(msg, 11)
print enc
print caesar(enc, 11, decode = True)

View file

@ -0,0 +1,23 @@
/*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──────────────────────*/
err: say; say '***error!***'; say; say arg(1); say; exit 13

View file

@ -0,0 +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

View file

@ -0,0 +1,5 @@
> (define s (encrypt "The five boxing wizards jump quickly."))
> s
"Uif gjwf cpyjoh xjabset kvnq rvjdlmz."
> (decrypt s)
"The five boxing wizards jump quickly."

View file

@ -0,0 +1,19 @@
#lang racket
(define A (char->integer #\A))
(define Z (char->integer #\Z))
(define a (char->integer #\a))
(define z (char->integer #\z))
(define (rotate c n)
(define cnum (char->integer c))
(define (shift base) (integer->char (+ base (modulo (+ n (- cnum base)) 26))))
(cond [(<= A cnum Z) (shift A)]
[(<= a cnum z) (shift a)]
[else c]))
(define (caesar s n)
(list->string (for/list ([c (in-string s)]) (rotate c n))))
(define (encrypt s) (caesar s 1))
(define (decrypt s) (caesar s -1))

View file

@ -0,0 +1,23 @@
@atoz = Hash.new do |hash, key|
str = ('A'..'Z').to_a.rotate(key).join("")
hash[key] = (str << str.downcase)
end
def encrypt(key, plaintext)
(1..25) === key or raise ArgumentError, "key not in 1..25"
plaintext.tr(@atoz[0], @atoz[key])
end
def decrypt(key, ciphertext)
(1..25) === key or raise ArgumentError, "key not in 1..25"
ciphertext.tr(@atoz[key], @atoz[0])
end
original = "THEYBROKEOURCIPHEREVERYONECANREADTHIS"
en = encrypt(3, original)
de = decrypt(3, en)
[original, en, de].each {|e| puts e}
puts 'OK' if
(1..25).all? {|k| original == decrypt(k, encrypt(k, original))}

View file

@ -0,0 +1,5 @@
val text="The five boxing wizards jump quickly"
println("Plaintext => " + text)
val encoded=Caesar.encode(text, 3)
println("Ciphertext => " + encoded)
println("Decrypted => " + Caesar.decode(encoded, 3))

View file

@ -0,0 +1,12 @@
object Caesar {
private val alphaU='A' to 'Z'
private val alphaL='a' to 'z'
def encode(text:String, key:Int)=text.map{
case c if alphaU.contains(c) => rot(alphaU, c, key)
case c if alphaL.contains(c) => rot(alphaL, c, key)
case c => c
}
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)
}

View file

@ -0,0 +1,18 @@
!CharacterArray methodsFor:'encoding'!
rot:n
^ self class
streamContents:[:aStream |
self do:[:char |
aStream nextPut:(char rot:n) ]]
!Character methodsFor:'encoding'!
rot:n
(self isLetter) ifTrue:[
self isLowercase ifTrue:[
^ 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz' at:(self-$a+1+n)
] ifFalse:[
^ 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ' at:(self-$A+1+n)
]
].
^ self

View file

@ -0,0 +1 @@
'THE QUICK BROWN FOX' rot:3 -> 'WKH TXLFN EURZQ IRA'

View file

@ -0,0 +1,7 @@
set caesar [Caesar new 3]
set txt "The five boxing wizards jump quickly."
set enc [$caesar encrypt $txt]
set dec [$caesar decrypt $enc]
puts "Original message = $txt"
puts "Encrypted message = $enc"
puts "Decrypted message = $dec"

View file

@ -0,0 +1,23 @@
package require Tcl 8.6; # Or TclOO package for 8.5
oo::class create Caesar {
variable encryptMap decryptMap
constructor shift {
for {set i 0} {$i < 26} {incr i} {
# Play fast and loose with string/list duality for shorter code
append encryptMap [format "%c %c %c %c " \
[expr {$i+65}] [expr {($i+$shift)%26+65}] \
[expr {$i+97}] [expr {($i+$shift)%26+97}]]
append decryptMap [format "%c %c %c %c " \
[expr {$i+65}] [expr {($i-$shift)%26+65}] \
[expr {$i+97}] [expr {($i-$shift)%26+97}]]
}
}
method encrypt text {
string map $encryptMap $text
}
method decrypt text {
string map $decryptMap $text
}
}