【问题标题】:Decrypting Vigenère cipher in Java在 Java 中解密 Vigenère 密码
【发布时间】:2012-11-04 10:44:08
【问题描述】:

我正在尝试使用 java 方法解密密码加密,但是我的代码似乎没有正确返回。我试图扭转加密过程,但我看不出我做错了什么。抱歉,我希望这不是一个愚蠢的问题。

public void decrypt()
{
    String cipherText = this.message;
    String key = this.KEY;
    String alphabet = "abcdefghijklmnopqrstuvwxyz"; 
    int alphabetSize = alphabet.length();
    int textSize = cipherText.length();
    int keySize = key.length();
    StringBuilder decryptedText = new StringBuilder(textSize);

    for (int i = 0; i < textSize; i++)
    {
        char encyrptChar = cipherText.charAt(i); // get the current character to be shifted
        char keyChar = key.charAt(i % keySize); // use key again if the end is reached
        int plainPos = alphabet.indexOf(encyrptChar); // plain character's position in alphabet string
         // decrypt the input text
        int keyPos = alphabet.indexOf(keyChar); // key character's position in alphabet
        int shiftedPos = plainPos-keyPos;
        shiftedPos += alphabetSize;
        decryptedText.append(alphabet.charAt(shiftedPos));
    }

    this.message =  decryptedText.toString();
}

【问题讨论】:

  • 代码的逻辑是什么,你想做什么?
  • 我昨天已经看到了同样的问题……看来作业的截止日期快到了;)
  • 如果来自 Coursera,此类问题应关闭并删除:coursera.org/about/honorcode
  • @das_weezul 我见过一个在网络上运行的,并且忽略了不可打印的字符。不用说,它们都是 vigenere,但仍然互不相容。
  • 我没有参加 coursera 课程。请不要这样指责我。

标签: java encryption vigenere


【解决方案1】:
shiftedPos += alphabetSize;

你为什么这样做?我认为只有在 shiftPos 时才需要这样做

if(shiftedPos<0)
   shiftedPos += alphabetSize;

这是因为如果 a=0 且 b=1,则 (a-b)=-1 表示 z。 要使用整个 ASCII 集,您只需以正确的顺序将 alpabeth 字符串和大小替换为所有 ASCII 字符。

【讨论】:

    【解决方案2】:

    采取这些措施:

        char encyrptChar = cipherText.charAt(i); // get the current character to be shifted
        char keyChar = key.charAt(i % keySize); // use key again if the end is reached
        int plainPos = alphabet.indexOf(encyrptChar); // plain character's position in alphabet string
    
        int keyPos = alphabet.indexOf(keyChar); // key character's position in alphabet
                int shiftedPos = plainPos-keyPos;
                shiftedPos += alphabetSize;
    

    有一些问题。

    1. plainPos实际上是一个加密值,不要混淆。
    2. plainPos-keyPos 应该等于解密后的值。然后,您应该通过 alphabetSize 对其进行修改,以获得正确的值。

    在处理命名约定时要小心。这确实会导致一些问题......

    除此之外,我认为您的代码实际上工作正常。我当然看不出任何问题。通过online encryptor/decryptor 试用。

    【讨论】:

      猜你喜欢
      • 2019-07-18
      • 2017-04-26
      • 1970-01-01
      • 2016-08-11
      • 2015-04-28
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 2011-09-29
      相关资源
      最近更新 更多