Vigenere Cipher输出

问题描述 投票:3回答:2

我正在查看http://rosettacode.org/wiki/Vigen%C3%A8re_cipher#Java上提供的Vigene Ciphere源代码。我尝试自己测试程序,并没有输出我期望的基于vigene的值。例如,'dog'是单词,'bob'是关键,我希望将其加密为'ech',而不是'qot'。

public static void main(String[] args) {
    String key = "bob";
    String ori = "dog";
    String enc = encrypt(ori, key);
    System.out.println(enc);

}

static String encrypt(String text, final String key) {
    String res = "";
    text = text.toLowerCase();
    for (int i = 0, j = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (c < 'a' || c > 'z') continue;
        res += (char)((c + key.charAt(j) - 2 * 'A') % 26 + 'A');
        j = ++j % key.length();
    }
    return res;
}

但是输出是不同的。这是因为我对密码的理解不正确,或者采用了与众所周知的vigenere密码不同的方法。

java vigenere
2个回答
0
投票

正如用户已经指出的那样,您应该将行更改为:

res += (char)((c + key.charAt(j) - 2 * 'a') % 26 + 'a');

或者,你可以改变这个:

if (c < 'a' || c > 'z') continue;

对此:

if (c < 'A' || c > 'Z') continue;

只需确保将ASCII转换回字母时,您使用的是正确的ASCII值(即大写为65 (A),小写为97 (a))。


0
投票

因为您要将文本设置为加密为小写,所以尝试将这些字符文字也更改为小写:

res += (char)((c + key.charAt(j) - 2 * 'a') % 26 + 'a');

将int转换为char时,必须考虑到'a'的整数值不等于'A'。因为您要检查当前字符是否在'a'和'z'之间(因为您已将其设置为小写),所以您还应该以小写形式输出。

© www.soinside.com 2019 - 2024. All rights reserved.