java - Java 中的简单凯撒密码

标签 java

我正在尝试用java制作一个简单的凯撒密码,它接受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]);
    {
        }
}

}

最佳答案

此代码可能会帮助您在 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;
}
}

关于java - Java 中的简单凯撒密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21412148/

相关文章:

java - 链表上的冒泡排序实现

java - 仅在通用类型上未经检查的强制转换警告

java - C++ shared_ptr 和 Java native 对象所有权

java.lang.IllegalArgumentException : Log tag "okhttp3.mockwebserver.MockWebServer" exceeds limit of 23 characters

java - 对象数组测试但没有得到任何输出

java - Java平台模块系统中的 'java.se'和 'java.base'模块有什么区别

java - 如何从 HibernateTransactionManager 获取事务状态

java - 使用 Monetary API java 进行格式化的超过 2 精度舍入

Java:java.lang.UnsatisfiedLinkError 无法使用 JNI 调用 .cpp 文件中的 native 方法

java - 从 Jasper 报告中抛出异常