我正在寻找一种凯撒密码,其中应包含常见的ASCII可打印字符(字符代码32-126)。
我当前的代码:
private static char Cipher(char ch, int key)
{
if (!char.IsLetter(ch))
return ch;
char offset = char.IsUpper(ch) ? 'A' : 'a';
return (char)((((ch + key) - offset) % 26) + offset);
}
public static string Encipher(string input, int key)
{
string output = string.Empty;
foreach (char ch in input)
output += Cipher(ch, key);
return output;
}
public static string Decipher(string input, int key) {return Encipher(input, 26 - key);}
(来源:https://www.programmingalgorithms.com/algorithm/caesar-cipher/)
我认为我至少需要更改
if (!char.IsLetter(ch)) *and* return Encipher(input, 26 - key);
到
if (char.IsControl(ch)) *and* return Encipher(input, 94 - key);
并将26的模数更改为94(?),但还需要做什么?我假设随机数生成器(这是针对一个时间片的实现)也需要更改为0-93(或95 ??)。但是,对此进行测试会给我带来错误,并且不会使输出与输入相同。也许我也需要进行isLetter检查,因此isUpper检查不会因为非字母而失败。我还想念什么?
private static char Cipher(char ch, int key)
{
if (char.IsControl(ch))
return ch;
char offset = ' ';
return (char)((((ch + key) - offset) % 95) + offset);
}
public static string Encipher(string input, int key)
{
string output = string.Empty;
foreach (char ch in input)
output += Cipher(ch, key);
return output;
}
public static string Decipher(string input, int key)
{
return Encipher(input, 95 - key);
}