java 中的 ASCII Vigenere 密码实现
ASCII Vigenere cipher implementation in java
这是关于我从编程老师那里得到的作业。
我们将为所有可打印的 ASCII 代码实施 vigenere 密码,并使用它 运行 进行测试。
vigenere 密码是一种多表密码,使用多个凯撒密码,移位一个。另见 Wikipedia
我按如下方式实现了我的 vigenere,但是我的作业中的测试没有为我的实现产生所需的输出。
我进行了搜索,但它的 ASCII 实现似乎很少见。
我的代码中是否存在我没有看到的明显错误?
public String encrypt(String plaintext) {
String cipherText = "";
for (int i = 0; i < plaintext.length(); i++) {
char c = plaintext.charAt(i);
// vigenere for the letters A-Z is defined as vigenere(m) = m[i] + k[i] % 26
// where m[i] is the message and k[i] is the key.
//
// For ASCII support, as printable space starts at 32,
// subtract 2*32 from the sum of keyChar and messageChar to get zero based.
// Then calculate the modulo of this sum to be sure to stay in bounds.
// Finally add 32 to the result of the modulo operation to place it in the 32 - 126 range.
//
// The key wrapping is implemented as i % _key.length() to restart
// from the beginning if the end of the key is reached.
cipherText += (char) ((c + _key.charAt(i % _key.length()) - 64) % 94 + 32);
}
return cipherText;
}
您的代码和注释之间的唯一区别是当 32 到 126 的范围包含 95 个字符时,您使用的是 % 94 .
将相应的语句更改为使用模 95,并稍微分解一下:
int caesar = _key.charAt(i % _key.length()) - 32;
int sum = c - 32 + caesar;
cipherText += (char) (sum % 95 + 32);
那么你的解密算法可以使用所有相同的代码,只是将上面的第二个语句替换为:
int sum = c - 32 + (95 - caesar);
这是关于我从编程老师那里得到的作业。 我们将为所有可打印的 ASCII 代码实施 vigenere 密码,并使用它 运行 进行测试。
vigenere 密码是一种多表密码,使用多个凯撒密码,移位一个。另见 Wikipedia
我按如下方式实现了我的 vigenere,但是我的作业中的测试没有为我的实现产生所需的输出。
我进行了搜索,但它的 ASCII 实现似乎很少见。 我的代码中是否存在我没有看到的明显错误?
public String encrypt(String plaintext) {
String cipherText = "";
for (int i = 0; i < plaintext.length(); i++) {
char c = plaintext.charAt(i);
// vigenere for the letters A-Z is defined as vigenere(m) = m[i] + k[i] % 26
// where m[i] is the message and k[i] is the key.
//
// For ASCII support, as printable space starts at 32,
// subtract 2*32 from the sum of keyChar and messageChar to get zero based.
// Then calculate the modulo of this sum to be sure to stay in bounds.
// Finally add 32 to the result of the modulo operation to place it in the 32 - 126 range.
//
// The key wrapping is implemented as i % _key.length() to restart
// from the beginning if the end of the key is reached.
cipherText += (char) ((c + _key.charAt(i % _key.length()) - 64) % 94 + 32);
}
return cipherText;
}
您的代码和注释之间的唯一区别是当 32 到 126 的范围包含 95 个字符时,您使用的是 % 94 .
将相应的语句更改为使用模 95,并稍微分解一下:
int caesar = _key.charAt(i % _key.length()) - 32;
int sum = c - 32 + caesar;
cipherText += (char) (sum % 95 + 32);
那么你的解密算法可以使用所有相同的代码,只是将上面的第二个语句替换为:
int sum = c - 32 + (95 - caesar);