Playfair cipher: Difference between revisions
Content deleted Content added
m Category:Encryption |
Updated D entry |
||
Line 143: | Line 143: | ||
{{trans|Python}} |
{{trans|Python}} |
||
<lang d>import std.stdio, std.array, std.algorithm, std.range, std.ascii, |
<lang d>import std.stdio, std.array, std.algorithm, std.range, std.ascii, |
||
std.conv, std.string, std.regex; |
std.conv, std.string, std.regex, std.typecons; |
||
string unique(in string s) pure nothrow @safe { |
string unique(in string s) pure nothrow @safe { |
||
Line 186: | Line 186: | ||
enc[[m[i1][j1], m[i2][j2]]] = [m[i1][j2], m[i2][j1]]; |
enc[[m[i1][j1], m[i2][j2]]] = [m[i1][j2], m[i2][j1]]; |
||
dec = enc. |
dec = enc.byKeyValue.map!(t => tuple(t.value, t.key)).assocArray; |
||
} |
} |
||
private string _canonicalize(in string s) const pure |
private string _canonicalize(in string s) const pure @safe { |
||
return s.toUpper.removechars("^A-Z").replace(from, to); |
return s.toUpper.removechars("^A-Z").replace(from, to); |
||
} |
} |
||
Line 197: | Line 197: | ||
.matchAll(r"(.)(?:(?!\1)(.))?") |
.matchAll(r"(.)(?:(?!\1)(.))?") |
||
.map!(m => enc[m[0].leftJustify(2, 'X')]) |
.map!(m => enc[m[0].leftJustify(2, 'X')]) |
||
.join( |
.join(' '); |
||
} |
} |
||
string decode(in string s) const |
string decode(in string s) const pure @safe { |
||
return _canonicalize(s).chunks(2).map!(p => dec[p.text]).join( |
return _canonicalize(s).chunks(2).map!(p => dec[p.text]).join(' '); |
||
} |
} |
||
} |
} |
||
void main() { |
void main() /*@safe*/ { |
||
/*immutable*/ const pf = Playfair("Playfair example"); |
/*immutable*/ const pf = Playfair("Playfair example"); |
||
immutable orig = "Hide the gold in...the TREESTUMP!!!"; |
immutable orig = "Hide the gold in...the TREESTUMP!!!"; |