Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -1,3 +1,11 @@
Implement a [[wp:Caesar cipher|Caesar cipher]], both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates 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". 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.
Implement a [[wp:Caesar cipher|Caesar cipher]], both encoding and decoding. <br>
The key is an integer from 1 to 25.
Caesar cipher is identical to [[Vigenère cipher]] with key of length 1. Also, [[Rot-13]] is identical to Caesar cipher with key 13.
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".
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.
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.

View file

@ -1,2 +1,4 @@
---
category:
- String manipulation
note: Encryption

View file

@ -0,0 +1,52 @@
((main
{"The quick brown fox jumps over the lazy dog.\n"
dup <<
17 caesar_enc !
dup <<
17 caesar_dec !
<<})
(caesar_enc
{ 2 take
{ caesar_enc_loop ! }
nest })
(caesar_enc_loop {
give
<- str2ar
{({ dup is_upper ! }
{ 0x40 -
-> dup <-
encrypt !
0x40 + }
{ dup is_lower ! }
{ 0x60 -
-> dup <-
encrypt !
0x60 + }
{ 1 }
{fnord})
cond}
eachar
collect !
ls2lf ar2str})
(collect { -1 take })
(encrypt { + 1 - 26 % 1 + })
(caesar_dec { <- 26 -> - caesar_enc ! })
(is_upper
{ dup
<- 0x40 cugt ->
0x5b cult
cand })
(is_lower
{ dup
<- 0x60 cugt ->
0x7b cult
cand }))

View file

@ -1,8 +1,8 @@
import std.stdio, std.traits;
pure S rot(S)(in S s, in int key) pure /*nothrow*/
S rot(S)(in S s, in int key) pure nothrow @safe
if (isSomeString!S) {
auto res = s.dup; // Not nothrow.
auto res = s.dup;
foreach (immutable i, ref c; res) {
if ('a' <= c && c <= 'z')
@ -13,7 +13,7 @@ if (isSomeString!S) {
return res;
}
void main() {
void main() @safe {
enum key = 3;
immutable txt = "The five boxing wizards jump quickly";
writeln("Original: ", txt);

View file

@ -1,11 +1,11 @@
import std.stdio, std.ascii, std.string, std.algorithm;
string rot(in string s, in int key) pure /*nothrow*/ {
string rot(in string s, in int key) pure nothrow @safe {
auto uppr = uppercase.dup.representation;
bringToFront(uppr[0 .. key], uppr[key .. $]);
auto lowr = lowercase.dup.representation;
bringToFront(lowr[0 .. key], lowr[key .. $]);
return s.translate(makeTrans(letters, cast(char[])(uppr ~ lowr)));
return s.translate(makeTrans(letters, assumeUTF(uppr ~ lowr)));
}
void main() {

View file

@ -0,0 +1,53 @@
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Run application.
local
s: STRING_32
do
s := "The tiny tiger totally taunted the tall Till."
print ("%NString to encode: " + s)
print ("%NEncoded string: " + encode (s, 12))
print ("%NDecoded string (after encoding and decoding): " + decode (encode (s, 12), 12))
end
feature -- Basic operations
decode (to_be_decoded: STRING_32; offset: INTEGER): STRING_32
-- Decode `to be decoded' according to `offset'.
do
Result := encode (to_be_decoded, 26 - offset)
end
encode (to_be_encoded: STRING_32; offset: INTEGER): STRING_32
-- Encode `to be encoded' according to `offset'.
local
l_offset: INTEGER
l_char_code: INTEGER
do
create Result.make_empty
l_offset := (offset \\ 26) + 26
across to_be_encoded as tbe loop
if tbe.item.is_alpha then
if tbe.item.is_upper then
l_char_code := ('A').code + (tbe.item.code - ('A').code + l_offset) \\ 26
Result.append_character (l_char_code.to_character_32)
else
l_char_code := ('a').code + (tbe.item.code - ('a').code + l_offset) \\ 26
Result.append_character (l_char_code.to_character_32)
end
else
Result.append_character (tbe.item)
end
end
end
end

View file

@ -1,7 +1,7 @@
#define system.
#define system'routines.
#define extensions.
#define extensions'math.
#define system'math.
// --- Constants ---
@ -29,13 +29,13 @@
(-1 < anIndex)
? [
theExtendee eval:(Letters @ (modulus:(theKey+anIndex):26))
theExtendee eval:(Letters @ ((theKey+anIndex) int mod:26))
]
! [
anIndex := BigLetters indexOf &index:0 &char:aChar.
(-1 < anIndex)
? [
theExtendee eval:(BigLetters @ (modulus:(theKey+anIndex):26))
theExtendee eval:(BigLetters @ ((theKey+anIndex) int mod:26))
]
! [
theExtendee eval:aChar.

View file

@ -0,0 +1,13 @@
def caesarEncode(cipherKey, text) {
def builder = new StringBuilder()
text.each { character ->
int ch = character[0] as char
switch(ch) {
case 'a'..'z': ch = ((ch - 97 + cipherKey) % 26 + 97); break
case 'A'..'Z': ch = ((ch - 65 + cipherKey) % 26 + 65); break
}
builder << (ch as char)
}
builder as String
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }

View file

@ -0,0 +1,7 @@
def caesarEncode(cipherKey, text) {
text.chars.collect { c ->
int off = c.isUpperCase() ? 'A' : 'a'
c.isLetter() ? (((c as int) - off + cipherKey) % 26 + off) as char : c
}.join()
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }

View file

@ -0,0 +1,4 @@
def caesarEncode(k, text) {
(text as int[]).collect { it==' ' ? ' ' : (((it & 0x1f) + k - 1) % 26 + 1 | it & 0xe0) as char }.join()
}
def caesarDecode(k, text) { caesarEncode(26 - k, text) }

View file

@ -0,0 +1,4 @@
def caesarEncode(k, text) {
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) }

View file

@ -0,0 +1,5 @@
def caesarEncode(k, text) {
def c = { (it*2)[k..(k+25)].join() }
text.tr('a-zA-Z', c('a'..'z') + c('A'..'Z'))
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }

View file

@ -0,0 +1,10 @@
def plainText = "The Quick Brown Fox jumped over the lazy dog"
def cipherKey = 12
def cipherText = caesarEncode(cipherKey, plainText)
def decodedText = caesarDecode(cipherKey, cipherText)
println "plainText: $plainText"
println "cypherText($cipherKey): $cipherText"
println "decodedText($cipherKey): $decodedText"
assert plainText == decodedText

View file

@ -1,24 +0,0 @@
def caeserEncode(int cipherKey, String text) {
def builder = new StringBuilder()
text.each { character ->
int ch = character[0] as char
switch(ch) {
case 'a'..'z': ch = ((ch - 97 + cipherKey) % 26 + 97); break
case 'A'..'Z': ch = ((ch - 65 + cipherKey) % 26 + 65); break
}
builder.append(ch as char)
}
builder.toString()
}
def caeserDecode(int cipherKey, String text) { caeserEncode(26 - cipherKey, text) }
def plainText = "The Quick Brown Fox jumped over the lazy dog"
def cipherKey = 12
def cipherText = caeserEncode(cipherKey, plainText)
def decodedText = caeserDecode(cipherKey, cipherText)
println "plainText: $plainText"
println "cypherText($cipherKey): $cipherText"
println "decodedText($cipherKey): $decodedText"
assert plainText == decodedText

View file

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

View file

@ -1 +1 @@
cypher[mesg_String,n_Integer]:=StringReplace[mesg,Flatten[Thread[Rule[#,RotateLeft[#,3]]]&/@CharacterRange@@@{{"a","z"},{"A","Z"}}]]
cypher[mesg_String,n_Integer]:=StringReplace[mesg,Flatten[Thread[Rule[#,RotateLeft[#,n]]]&/@CharacterRange@@@{{"a","z"},{"A","Z"}}]]

View file

@ -0,0 +1,19 @@
main: func (args: String[]) {
shift := args[1] toInt()
if (args length != 3) {
"Usage: #{args[0]} [number] [sentence]" println()
"Incorrect number of arguments." println()
} else if (!shift && args[1] != "0"){
"Usage: #{args[0]} [number] [sentence]" println()
"Number is not a valid number." println()
} else {
str := ""
for (c in args[2]) {
if (c alpha?()) {
c = (c lower?() ? 'a' : 'A') + (26 + c toLower() - 'a' + shift) % 26
}
str += c
}
str println()
}
}

View file

@ -0,0 +1,59 @@
MODULE Caesar;
IMPORT
Out;
CONST
encode* = 1;
decode* = -1;
VAR
text,cipher: POINTER TO ARRAY OF CHAR;
PROCEDURE Cipher*(txt: ARRAY OF CHAR; key: INTEGER; op: INTEGER; VAR cipher: ARRAY OF CHAR);
VAR
i: LONGINT;
BEGIN
i := 0;
WHILE i < LEN(txt) - 1 DO
IF (txt[i] >= 'A') & (txt[i] <= 'Z') THEN
cipher[i] := CHR(ORD('A') + ((ORD(txt[i]) - ORD('A') + (key * op))) MOD 26)
ELSIF (txt[i] >= 'a') & (txt[i] <= 'z') THEN
cipher[i] := CHR(ORD('a') + ((ORD(txt[i]) - ORD('a') + (key * op))) MOD 26)
ELSE
cipher[i] := txt[i]
END;
INC(i)
END;
cipher[i] := 0X
END Cipher;
BEGIN
NEW(text,3);NEW(cipher,3);
COPY("HI",text^);
Out.String(text^);Out.String(" =e=> ");
Cipher(text^,2,encode,cipher^);
Out.String(cipher^);
COPY(cipher^,text^);
Cipher(text^,2,decode,cipher^);
Out.String(" =d=> ");Out.String(cipher^);Out.Ln;
COPY("ZA",text^);
Out.String(text^);Out.String(" =e=> ");
Cipher(text^,2,encode,cipher^);
Out.String(cipher^);
COPY(cipher^,text^);
Cipher(text^,2,decode,cipher^);
Out.String(" =d=> ");Out.String(cipher^);Out.Ln;
NEW(text,37);NEW(cipher,37);
COPY("The five boxing wizards jump quickly",text^);
Out.String(text^);Out.String(" =e=> ");
Cipher(text^,3,encode,cipher^);
Out.String(cipher^);
COPY(cipher^,text^);
Cipher(text^,3,decode,cipher^);
Out.String(" =d=> ");Out.String(cipher^);Out.Ln;
END Caesar.

View file

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

View file

@ -0,0 +1,75 @@
# Author: M. McNabb
function Get-CaesarCipher
{
Param
(
[Parameter(
Mandatory=$true,ValueFromPipeline=$true)]
[string]
$Text,
[ValidateRange(1,25)]
[int]
$Key = 1,
[switch]
$Decode
)
begin
{
$LowerAlpha = [char]'a'..[char]'z'
$UpperAlpha = [char]'A'..[char]'Z'
}
process
{
$Chars = $Text.ToCharArray()
function encode
{
param
(
$Char,
$Alpha = [char]'a'..[char]'z'
)
$Index = $Alpha.IndexOf([int]$Char)
$NewIndex = ($Index + $Key) - $Alpha.Length
$Alpha[$NewIndex]
}
function decode
{
param
(
$Char,
$Alpha = [char]'a'..[char]'z'
)
$Index = $Alpha.IndexOf([int]$Char)
$int = $Index - $Key
if ($int -lt 0) {$NewIndex = $int + $Alpha.Length}
else {$NewIndex = $int}
$Alpha[$NewIndex]
}
foreach ($Char in $Chars)
{
if ([int]$Char -in $LowerAlpha)
{
if ($Decode) {$Char = decode $Char}
else {$Char = encode $Char}
}
elseif ([int]$Char -in $UpperAlpha)
{
if ($Decode) {$Char = decode $Char $UpperAlpha}
else {$Char = encode $Char $UpperAlpha}
}
$Char = [char]$Char
[string]$OutText += $Char
}
$OutText
$OutText = $null
}
}

View file

@ -4,19 +4,19 @@ 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."
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'
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)
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. */
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

@ -2,9 +2,9 @@
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."
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'
@ -13,11 +13,10 @@ caesar: procedure; parse arg s,k; @='abcdefghijklmnopqrstuvwxyz'
/*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'
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
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,56 @@
caesar() {
local OPTIND
local encrypt n=0
while getopts :edn: option; do
case $option in
e) encrypt=true ;;
d) encrypt=false ;;
n) n=$OPTARG ;;
:) echo "error: missing argument for -$OPTARG" >&2
return 1 ;;
?) echo "error: unknown option -$OPTARG" >&2
return 1 ;;
esac
done
shift $((OPTIND-1))
if [[ -z $encrypt ]]; then
echo "error: specify one of -e or -d" >&2
return 1
fi
local upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ
local lower=abcdefghijklmnopqrstuvwxyz
if $encrypt; then
tr "$upper$lower" "${upper:n}${upper:0:n}${lower:n}${lower:0:n}" <<< "$1"
else
tr "${upper:n}${upper:0:n}${lower:n}${lower:0:n}" "$upper$lower" <<< "$1"
fi
}
tr() {
local -A charmap
local i trans line char
for ((i=0; i<${#1}; i++)); do
charmap[${1:i:1}]=${2:i:1}
done
while IFS= read -r line; do
trans=""
for ((i=0; i<${#line}; i++)); do
char=${line:i:1}
if [[ -n ${charmap[$char]} ]]; then
trans+=${charmap[$char]}
else
trans+=$char
fi
done
echo "$trans"
done
}
txt="The five boxing wizards jump quickly."
enc=$(caesar -e -n 5 "$txt")
dec=$(caesar -d -n 5 "$enc")
echo "original: $txt"
echo "encrypted: $enc"
echo "decrypted: $dec"