java中的ASCII Vigenere密码实现

Posted

技术标签:

【中文标题】java中的ASCII Vigenere密码实现【英文标题】:ASCII Vigenere cipher implementation in java 【发布时间】:2015-01-27 23:40:38 【问题描述】:

这是关于我从我的编程老师那里得到的一项作业。 我们将为所有可打印的 ASCII 代码实现 vigenere 密码并使用它运行测试。

vigenere 密码是一种多字母密码,使用多个凯撒密码,移位为 1。另见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;

【问题讨论】:

能否请您解释一下vigenere cipher是什么? 如果你能善待并把它添加到你的帖子中,那就太棒了 已将其添加到帖子中:) 【参考方案1】:

您的代码和 cmets 之间的唯一区别是,当 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);

【讨论】:

以上是关于java中的ASCII Vigenere密码实现的主要内容,如果未能解决你的问题,请参考以下文章

Java 中的 Vigenere 密码算法 - 将消息解密为明文

C语言的Vigenere Cypher程序

Java Vigenere 密码

Java 中的 Vigenere/Polyalphabetic Cipher Decoder/Decrypter/Breaker

使用从文件中读取明文的 Vigenere 密码进行加密 (JAVA)

Java vigenere 密码性能问题