Java vigenere密码性能问题

时间:2013-10-26 12:41:31

标签: java performance encryption vigenere

我制作了一个vigenere加密/解密程序,似乎按照我的意图工作,但是在一个非常大的文本文件(500,000个字符aprox)上运行加密/解密需要2-4分钟。我查看了我的代码,无法看到哪些操作可能会减慢它的速度。任何人都有任何想法,我怎么能加快这一点?

代码:

public static String encrypt(String text, String key)
{
    String cipherText = "";
    text = text.toLowerCase();
    for(int i = 0; i < text.length(); i++)
    {
        System.out.println("Count: "+ i); //I just put this in to check the 
                                          //loop wasn't doing anything unexpected
        int keyIndex = key.charAt(i%key.length()) - 'a';
        int textIndex = text.charAt(i) - 'a';
        if(text.charAt(i) >= 'a' && text.charAt(i) <= 'z') { //check letter is in alphabet
            int vigenere = ((textIndex + keyIndex) % 26) + 'a';
            cipherText = cipherText + (char)vigenere;
        } else 
            cipherText = cipherText + text.charAt(i);
        }

    }
    return cipherText;
}

在运行加密之前,我有一个方法,使用Scanner将文本文件读取到String。此字符串加上预定义的密钥用于创建加密文本。

感谢。

ANSWER

感谢RC - 这是我的字符串连接花时间。如果有其他人感兴趣,这是我的更新代码,现在可以快速运行:

public static String encrypt(String text, String key)
{
    StringBuilder cipher = new StringBuilder();
    for(int i = 0; i < text.length(); i++)
    {
        int keyIndex = key.charAt(i%key.length()) - 'a';
        int textIndex = text.charAt(i) - 'a';
        if(text.charAt(i) >= 'a' && text.charAt(i) <= 'z') {
            int vigenere = ((textIndex + keyIndex) % 26) + 'a';
            cipher.append((char)vigenere);
        } else {
            cipher.append(text.charAt(i));
        }

    }
    return cipher.toString();
}

2 个答案:

答案 0 :(得分:0)

附加到StringBuilder而不是创建新的String实例。 你想做一个

buffer.append((char)vigenere);

而不是cipherText = cipherText + (char)vigenere;

答案 1 :(得分:0)

目前你正在做

for(int i = 0; i < text.length(); i++){
    ...
    int keyIndex = key.charAt(i%key.length()) - 'a';
    ...
}

您可以尝试从for循环中删除keyIndex的calucation,并在预处理步骤中实现它。例如,您可以将keyIndex值/字符存储在单独的数组中,并访问原始循环中的数组内容。这应该可以节省一些计算步骤。