Java密码转移字母

时间:2015-02-08 15:38:00

标签: java encryption unicode

我目前正在尝试编写基本加密程序。在大多数情况下,我有它的工作。它根本不是我想要的。 基本上,用户输入短语,移位量(例如5,向前5个字母),并且程序加密短语。 例如,如果用户输入“red”,班次为5,则程序应打印出:WJI 但是,我得到了使用Unicode的程序,所以它打印出相应的Unicode字符,所以我得到符号,例如加密中的“{,:”。请注意,它仍然有效,但不是我想要的方式。

这是我的代码:

import javax.swing.*;
public class SimpleEncryption {

/**
 * @param args the command line arguments
 */
static int shift;
public static void main(String[] args) {
   String cipher = JOptionPane.showInputDialog(null, "Please enter a sentence or word that you wish to encode or decode. This program uses"
           + " a basic cipher shift.");
  String upperCase = cipher.toUpperCase();
   char[] cipherArray = cipher.toCharArray(); 
   String rotationAmount = JOptionPane.showInputDialog(null, "Please enter a shift amount.");
   int rotation = Integer.parseInt(rotationAmount);
   String encryptOrDecrypt = JOptionPane.showInputDialog(null, "Please choose whether to encrypt or decrypt this message. \n"
           + "Encrypt - press 1\nDecrypt - press 2");
   int choice = Integer.parseInt(encryptOrDecrypt);
   int cipherLength = cipherArray.length;

   if (choice == 1) { //if the user chooses to encrypt their cipher
       System.out.println("The original phrase is: "+upperCase);
       System.out.println("ENCRYPTED PHRASE:");
       for (int i = 0; i < cipherLength; i++) {
       shift = (upperCase.charAt(i) + rotation);
       System.out.print((char)(shift));
       }
       System.out.println(" ");
   }
       else if (choice == 2) {
          System.out.println("DECRYPTED PHRASE:");
               for (int i = 0; i < cipherLength; i++) {
                  shift = (cipher.charAt(i) - rotation);
                   System.out.print((char)(shift));
               }


               }


   }

}

赞赏任何和所有建议。另外,假设用户输入的移位值为25.如何让字母表“循环”。例如,字母是Z,移位2会使它成为“B”?

1 个答案:

答案 0 :(得分:0)

而不是

shift = cipher.charAt(i) - rotation

int tmp = cipher.charAt(i) - 'A';    // Offset from 'A'
int rotated = (tmp - rotation) % 25; // Compute rotation, wrap at 25
shift = rotated + 'A';               // Add back offset from 'A'