Java中的简单凯撒密码

时间:2014-01-28 17:08:21

标签: java

我正在尝试在java中创建一个简单的Caesar密码,它接受2个参数。一个是短语,另一个是字母的移位。

我是Java的新手,我仍然在努力理解基础知识。作为要求,密码应保留大写字母大写,小写字母小写。单词之间的空格也应该单独留下。

到目前为止,我已经为移位声明了变量,并为小写字母和大写字母创建了2个单独的字符串。我不太确定从哪里开始。任何帮助将不胜感激。

public class caesar2{
public static void main(String args[]){
    String phrase = args[0];
    //First Argument
    String k = args[1];
    //Second argument
    //The shift of the letters in the caesar Cipher
    char characters[] = phrase.toCharArray();
    //Sending the input characters into a character array 
    int shift = Integer.parseInt(k);
    int remainder = shift % 26;
    //The shift = value K       
    for( int i=0; i < characters.length; i++)
    {
        if ((Character.isUpperCase(characters[i]))== true)
        {
            if((int)(characters[i]) + remainder >= 90)
            {
                characters[i] = (char)(characters[i]-(26-remainder));                   
            }
            else
            {
                characters[i] = (char)(characters[i]+remainder);
            }
        }
        else if (Character.isLowerCase(characters[i])==true)
        {
            if ((int)(characters[i] + remainder) >= 122)
            {
                characters[i] = (char)(characters[i] - (26-remainder));
            }
            else
            {
                characters[i] = (char)(characters[i]+remainder);
            }
        }   
    }
    for(int i =0; i< characters.length;i++)
        System.out.println (characters[i]);
    {
        }
}

}

5 个答案:

答案 0 :(得分:3)

加密部分

import java.util.Scanner;

public class CaesarCipher {

   public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String plainText = in.nextLine();
   // key value should be from 0 to 25
    int key = in.nextInt();
    plainText = plainText.toUpperCase();
    char[] plainTextChar = plainText.toCharArray();
    for(int i=0;i<plainTextChar.length;i++) {
        plainTextChar[i] = (char)(((int)plainTextChar[i]+key-65)%26 + 65);
    }
    System.out.println(String.valueOf(plainTextChar));
 }  
}

答案 1 :(得分:2)

首先,您不需要2个数组,只需要其中一个数组,并保持大小写状态(例如,在boolean isCapital中)。

其次,如果你使用一组字母,这对你的问题来说会更容易使用。

char[] letters = {'A', 'B', 'C'...};

然后你只需将移位应用于数组大小的字母模数索引。

答案 2 :(得分:2)

此代码可能会帮助您在eclipse,netbeans等java编辑器中运行此代码,因为Scanner用于获取用户输入。

import java.util.Scanner;
public class CaeserCipher
{
public static void main(String[] args) 
{
    Scanner sc=new Scanner(System.in);
    String str;
    String key;
    int keyLength;

    System.out.println("Enter message:");
    str=sc.nextLine();
    System.out.println("Enter encryption key:");
    key=sc.next();
    keyLength=key.length();
    //This for loop is repeated use of 'Enrypt' and 'Decrypt' options
    for(;;)
    {
        System.out.println("1.Encrypt\n2.Decrypt\n3.Exit...");
        int choice=sc.nextInt();
        switch(choice)
        {
            case 1:
            /*send input string keyLength to encrypt() method to encrypt it returns 'Encrypted' string*/
                System.out.println("Encrypted message..."+encrypt(str,keyLength));
                break;
            case 2:
                //send retrived string from encrypt() method and keyLength to decrypt() method it returns 'Decrypted' string
                System.out.println("Decryptedmessage..."+decrypt(encrypt(str,keyLength),keyLength));
                break;
            case 3:
                //exit from the program
                System.exit(0);
                break;
            default:
            System.out.println("Invalid option..");
        }
    }
}
public static String encrypt(String str,int keyLength)
{
    String encrypted="";
    for(int i=0;i<str.length();i++)
    {
        //stores ascii value of character in the string at index 'i'
        int c=str.charAt(i);
        //encryption logic for uppercase letters
        if(Character.isUpperCase(c))
        {
            c=c+(keyLength%26);
            //if c value exceeds the ascii value of 'Z' reduce it by subtracting 26(no.of alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
            if(c>'Z')
                c=c-26;
        }
        //encryption logic for lowercase letters
        else if(Character.isLowerCase(c))
        {
            c=c+(keyLength%26);
            //if c value exceeds the ascii value of 'z' reduce it by subtracting 26(no.of alphabets) to keep in boundaries of ascii values of 'a' and 'z'
            if(c>'z')
                c=c-26;
        }
        //concatinate the encrypted characters/strings
        encrypted=encrypted+(char) c;
    }
    return encrypted;
}
public static String decrypt(String str,int keyLength)
{
    String decrypted="";
    for(int i=0;i<str.length();i++)
    {
        //stores ascii value of character in the string at index 'i'
        int c=str.charAt(i);
        //decryption logic for uppercase letters
        if(Character.isUpperCase(c))
        {
            c=c-(keyLength%26);
            //if c value deceed the ascii value of 'A' increase it by adding 26(no.of alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
            if(c<'A')
                c=c+26;
        }
        //decryption logic for uppercase letters
        else if(Character.isLowerCase(c))
        {
            c=c-(keyLength%26);
            //if c value deceed the ascii value of 'A' increase it by adding 26(no.of alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
            if(c<'a')
                c=c+26;
        }
        //concatinate the decrypted characters/strings
        decrypted=decrypted+(char) c;
    }
    return decrypted;
}
}

答案 3 :(得分:1)

通过使用字母数(26),键/班次编号以及要移动的字母,我找到了找到正确字母的关系

您可以放置​​一个字符串,然后只移动字母(UPPER和更低),其余字符将保持不变。

键可以是任何int,也可以是负数。

我希望它可以帮助你,对不好的英语抱歉。

/**
 * byte constant wich means the number of letter in the alphabet
 */
private static final byte ALPHABET_LENGTH = 26;

/**
 * To encrypt the text
 * @param key int: the encryption key
 * @param text String: the text to encrypt 
 * @return String: the encrypted text
 */
public static final String encryptText(int key, String text) {
    StringBuilder cipherText = new StringBuilder();
    for(int i = 0; i < text.length(); i++) 
    {
        if(key >= 0) {
            if(Character.isLowerCase(text.charAt(i))) {
                cipherText.append((char) ('a' + ((text.charAt(i) - 'a' + key) %  AnticoCifrarioDiCesare.ALPHABET_LENGTH)));
            }
            else if(Character.isUpperCase(text.charAt(i))) {
                cipherText.append((char) ('A' + ((text.charAt(i) - 'A' + key) %  AnticoCifrarioDiCesare.ALPHABET_LENGTH)));
            }
            else {
                cipherText.append(text.charAt(i));
            }
        }
        else {
            if(Character.isLowerCase(text.charAt(i))) {
                cipherText.append((char) ('a' + (AnticoCifrarioDiCesare.ALPHABET_LENGTH + text.charAt(i) - 'a' + key % AnticoCifrarioDiCesare.ALPHABET_LENGTH) % AnticoCifrarioDiCesare.ALPHABET_LENGTH));
            }
            else if(Character.isUpperCase(text.charAt(i))) {
                cipherText.append((char) ('A' + (AnticoCifrarioDiCesare.ALPHABET_LENGTH + text.charAt(i) - 'A' + key % AnticoCifrarioDiCesare.ALPHABET_LENGTH) % AnticoCifrarioDiCesare.ALPHABET_LENGTH));
            }
            else {
                cipherText.append(text.charAt(i));
            }
        }
    }
    return cipherText.toString();
}
/**
 * To decrypt the text
 * @param key int: the key to decrypt
 * @param cipher String: the text to decrypt
 * @return String: the text decrypted
 */
public static final String decryptText(int key, String cipher) {
    StringBuilder rawText = new StringBuilder();
    for(int i = 0; i < cipher.length(); i++) 
    {
        if(key >= 0) {
            if(Character.isLowerCase(cipher.charAt(i))) {
                rawText.append((char) ('a' + (AnticoCifrarioDiCesare.ALPHABET_LENGTH + cipher.charAt(i) - 'a' - key % AnticoCifrarioDiCesare.ALPHABET_LENGTH) % AnticoCifrarioDiCesare.ALPHABET_LENGTH));
            }
            else if(Character.isUpperCase(cipher.charAt(i))) {
                rawText.append((char) ('A' + (AnticoCifrarioDiCesare.ALPHABET_LENGTH + cipher.charAt(i) - 'A' - key % AnticoCifrarioDiCesare.ALPHABET_LENGTH) % AnticoCifrarioDiCesare.ALPHABET_LENGTH));
            }
            else {
                rawText.append(cipher.charAt(i));
            }
        }
        else {
            if(Character.isLowerCase(cipher.charAt(i))) {
                rawText.append((char) ('a' + ((cipher.charAt(i) - 'a' - key) %  AnticoCifrarioDiCesare.ALPHABET_LENGTH)));
            }
            else if(Character.isUpperCase(cipher.charAt(i))) {
                rawText.append((char) ('A' + ((cipher.charAt(i) - 'A' - key) %  AnticoCifrarioDiCesare.ALPHABET_LENGTH)));
            }
            else {
                rawText.append(cipher.charAt(i));
            }
        }
    }
    return rawText.toString();
}

答案 4 :(得分:1)

import java.io.DataInputStream;
//Done by Sridhar P
 public class Main {
  public static void main(String[] args)throws Exception {
   int key,choice,ascii=0,i,j,n,addascii;
   char c;
   String message="",encrypted="";
   System.out.println("choose a option:");
   System.out.println("1.Encrypt");
   System.out.println("2.Decrypt");
   System.out.println("3.Hack");
   DataInputStream din = new DataInputStream(System.in);
   choice = Integer.parseInt(din.readLine());
   switch(choice){
     case 1:
     {
      System.out.println("Enter the message to encrypt:");
      message = din.readLine();
      n=message.length();
      System.out.println("Enter the key [1-26]:");
      key = Integer.parseInt(din.readLine());
      char[] msg = message.toCharArray();
      for(i=0;i<n;i++)
      {
      ascii = (int) msg[i];
      addascii = key + ascii;
      c = (char) addascii;
      encrypted = encrypted + c; 
      }
      System.out.println("Encrypted text is :"+encrypted);
      break;
     }
    case 2:
    {
      System.out.println("Enter the message to decrypt:");
      encrypted = din.readLine();
      n=encrypted.length();
      System.out.println("Enter the key [1-26]:");
      key = Integer.parseInt(din.readLine());
      char[] msg = encrypted.toCharArray();
      for(i=0;i<n;i++)
      {
      ascii = (int) msg[i];
      addascii = ascii - key;
      c = (char) addascii;
      message = message + c; 
      }
      System.out.println("Decrypted text is :"+message);
      break;
    } 
    case 3:
    {
      System.out.println("Enter the message to decrypt:");
      encrypted = din.readLine();
      n=encrypted.length();
      char[] msg = encrypted.toCharArray();
      for(j=1;j<27;j++)
      {
      key=j;
      for(i=0;i<n;i++)
      {
      ascii = (int) msg[i];
      addascii = ascii - key;
      c = (char) addascii;
      message = message + c; 
      }
      System.out.println(j+" "+message);
      message="";
      }
    } 
   }
  }
}