Vigenère cipher: Difference between revisions

Content added Content deleted
(Modified D version)
(→‎{{header|D}}: less compact but faster)
Line 318: Line 318:
<lang d>import std.stdio, std.string;
<lang d>import std.stdio, std.string;


string encrypt(string text, in string key) {
string encrypt(string txt, in string key) {
string encoded;
string res;
foreach (i, c; text.toupper().removechars("^A-Z"))
foreach (c; txt.toupper) {
encoded ~= (c + key[i % $] - 2 * 'A') % 26 + 'A';
if (c < 'A' || c > 'Z') continue;
res ~= (c + key[res.length % $] - 2 * 'A') % 26 + 'A';
return encoded;
}
return res;
}
}

string decrypt(string encoded, in string key) {
string decrypt(string txt, in string key) {
string decoded;
string res;
foreach (i, c; encoded.toupper().removechars("^A-Z"))
foreach (c; txt.toupper) {
decoded ~= (c - key[i % $] + 26) % 26 + 'A';
if (c < 'A' || c > 'Z') continue;
res ~= (c - key[res.length % $] + 26) % 26 + 'A';
return decoded;
}
return res;
}
}