【发布时间】:2013-10-02 18:16:02
【问题描述】:
我必须实现Vigenère cipher 的变体。我得到了加密部分没有问题,但我在解密代码中有一个错误,我不明白我做错了什么。
要求是:
密钥只能包含
A-Z(大写)关键字符的代码值为 A 为 0,B 为 1,...,Z 为 25
如果代码为
加密字符码=原始字符码+关键字符码
最终加密字符必须介于 32 和 126 之间,因此如果最终加密字符 > 126,则必须通过将值加上 32 然后减去 126 将其带回到 32 - 126 范围内
加密代码:
// it works ok
// I have tested it with some provided strings and the results are as expected
public String encrypt(String plainText)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < plainText.length(); i++) {
char c = plainText.charAt(i);
if (c >= 32) {
int keyCharValue = theKey.charAt(i % theKey.length()) - 'A';
c += keyCharValue;
if (c > 126) {
c = (char) (c + 32 - 126);
}
}
sb.append(c);
}
return sb.toString();
}
解密代码:
// there probably is an off-by-one error somewhere
// everything is decrypted ok, except '~' which gets decrypted to ' ' (space)
public String decrypt(String cipherText)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cipherText.length(); i++) {
char c = cipherText.charAt(i);
if (c >= 32) {
int keyCharValue = theKey.charAt(i % theKey.length()) - 'A';
c -= keyCharValue;
if (c < 32) {
c = (char) (c + 126 - 32);
}
}
sb.append(c);
}
return sb.toString();
}
示例(带有密钥ABCDEFGHIJKLMNOPQRSTUVWXYZ):
原
~~~~~~~~~~~~~~~~~~~~~~~~~~加密
~!"#$%&'()*+,-./0123456789已解密
~('~' 后跟空格)
编辑:
这是我用于测试的代码(它测试从 0 到 126 的每个字符作为字符串重复):
public static void main(String[] args) {
int passed = 0;
int failed = 0;
String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int c = 0; c <= 126; c++) {
StringBuilder sbString = new StringBuilder();
for (int i = 0; i <= 25; i++) {
sbString.append((char) c);
}
String original = sbString.toString();
Cipher cipher = Cipher(key);
String encrypted = cipher.encrypt(original);
String decrypted = cipher.decrypt(encrypted);
if (!original.equals(decrypted)) {
failed++;
System.out.println("--FAILED--");
System.out.println(original);
System.out.println(encrypted);
System.out.println(decrypted);
} else {
passed++;
}
}
int tests = passed + failed;
System.out.println(tests + " tests");
System.out.println("passed: " + passed);
System.out.println("failed: " + failed);
}
【问题讨论】:
-
@Pratik 好像是大写字母。
-
您好,我运行了上述方法并且它工作正常......我正在从解密方法中获取原始消息。
-
32-126 独占范围意味着 ~ 不是允许的结果。您的意思是包容性吗?
标签: java algorithm encryption vigenere