This commit is contained in:
Ingy döt Net 2013-10-27 22:24:23 +00:00
parent 6f050a029e
commit 776bba907c
3887 changed files with 59894 additions and 7280 deletions

View file

@ -0,0 +1,29 @@
import std.stdio, std.string;
string encrypt(in string txt, in string key) pure
in {
assert(key.removechars("^A-Z") == key);
} body {
string res;
foreach (immutable i, immutable c; toUpper(txt).removechars("^A-Z"))
res ~= (c + key[i % $] - 2 * 'A') % 26 + 'A';
return res;
}
string decrypt(in string txt, in string key) pure
in {
assert(key.removechars("^A-Z") == key);
} body {
string res;
foreach (immutable i, immutable c; toUpper(txt).removechars("^A-Z"))
res ~= (c - key[i % $] + 26) % 26 + 'A';
return res;
}
void main() {
immutable key = "VIGENERECIPHER";
immutable original = "Beware the Jabberwock, my son!" ~
" The jaws that bite, the claws that catch!";
immutable encoded = original.encrypt(key);
writeln(encoded, "\n", encoded.decrypt(key));
}

View file

@ -0,0 +1,25 @@
import std.stdio, std.range, std.ascii, std.string, std.algorithm,
std.conv;
enum mod = (in int m, in int n) pure nothrow => ((m % n) + n) % n;
enum _s2v = (in string s) pure /*nothrow*/ =>
s.toUpper.removechars("^A-Z").map!q{ a - 'A' };
string _v2s(R)(R v) pure /*nothrow*/ {
return v.map!(x => uppercase[x.mod(26)]).text;
}
enum encrypt = (in string txt, in string key) pure /*nothrow*/ =>
txt._s2v.zip(key._s2v.cycle).map!q{ a[0] + a[1] }._v2s;
enum decrypt = (in string txt, in string key) pure /*nothrow*/ =>
txt._s2v.zip(key._s2v.cycle).map!q{ a[0] - a[1] }._v2s;
void main() {
immutable key = "Vigenere Cipher!!!";
immutable original = "Beware the Jabberwock, my son!" ~
" The jaws that bite, the claws that catch!";
immutable encoded = original.encrypt(key);
writeln(encoded, "\n", encoded.decrypt(key));
}