Java中的简单凯撒密码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21412148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple Caesar Cipher in Java
提问by user3245510
I'm trying to make a simple Caesar cipher in java that accepts 2 arguments. One being the phrase, and the next being the shift of the letters.
我正在尝试在接受 2 个参数的 java 中制作一个简单的凯撒密码。一个是短语,另一个是字母的移位。
I'm very new to Java, and I'm still trying to understand the basics. As a requirement, the cipher should keep capital letters capital, and lower case letters lower case. The space between words should also be left alone.
我对 Java 很陌生,我仍在努力了解基础知识。作为要求,密码应保持大写字母大写,小写字母小写。单词之间的空格也应该单独留下。
So far I have declared the the variable for the shift and have made 2 separate strings for lower case letters and uppercase letters. I'm not too sure where to proceed from here. Any help would be greatly appreciated.
到目前为止,我已经为班次声明了变量,并为小写字母和大写字母制作了 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]);
{
}
}
}
}
回答by m0skit0
First you don't need 2 arrays, you just need one of them, and keep state of capitalization (in a boolean isCapital
for example).
首先,您不需要 2 个数组,您只需要其中一个,并保持大写状态(boolean isCapital
例如在 a中)。
Second, if you use an array of letters, that would be far easier to use for your problem.
其次,如果您使用字母数组,那么您的问题会更容易使用。
char[] letters = {'A', 'B', 'C'...};
Then you just have to apply the shift to the index of the letter modulus the size of the array.
然后,您只需要将移位应用于字母模数的索引,即数组的大小。
回答by Jagadishwar Reddy c
This code might help you run this in java editors like eclipse,netbeans since Scanner is used to take user input.
此代码可能会帮助您在 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;
}
}
回答by Madhu Amarnath
Encryption Part
加密部分
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));
}
}
回答by Eugenio Berretta
I've found the relation to find the right letter by using the number of letters(26), the key/shift number and the letter you want to shift
我找到了通过使用字母数 (26)、键/移位号和要移位的字母来找到正确字母的关系
You can put a String and then only letters (UPPER and lower) are shifted, all the rest of the characters will remain the same.
您可以放置一个字符串,然后只移动字母(大写和小写),其余所有字符将保持不变。
The key can be any int, also negative.
键可以是任何整数,也可以是负数。
I hope it can help you, sorry for the bad English.
我希望它可以帮助你,抱歉英语不好。
/**
* 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();
}
回答by Sridhar
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="";
}
}
}
}
}