java中的简单凯撒密码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1821545/
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 Max Canlas
Hey I'm making a simple caesar cipher in Java using the formula [x-> (x+shift-1) mod 127 + 1] I want to have my encrypted text to have the ASCII characters except the control characters(i.e from 32-127). How can I avoid the control characters from 0-31 applying in the encrypted text. Thank you.
嘿,我正在使用公式 [x-> (x+shift-1) mod 127 + 1] 在 Java 中制作一个简单的凯撒密码我想让我的加密文本包含除控制字符之外的 ASCII 字符(即从 32 -127)。如何避免在加密文本中应用 0-31 的控制字符。谢谢你。
回答by Jon Skeet
How about something like this:
这样的事情怎么样:
public String applyCaesar(String text, int shift)
{
char[] chars = text.toCharArray();
for (int i=0; i < text.length(); i++)
{
char c = chars[i];
if (c >= 32 && c <= 127)
{
// Change base to make life easier, and use an
// int explicitly to avoid worrying... cast later
int x = c - 32;
x = (x + shift) % 96;
if (x < 0)
x += 96; //java modulo can lead to negative values!
chars[i] = (char) (x + 32);
}
}
return new String(chars);
}
Admittedly this treats 127 as a non-control character, which it isn't... you may wish to tweak it to keep the range as [32, 126].
诚然,这将 127 视为非控制字符,它不是……您可能希望调整它以将范围保持为 [32, 126]。
回答by Andreas Dolk
Map your characters from [32..127] to [0..95], do a mod 95+1
and map the result back to [32..127].
将您的字符从 [32..127]mod 95+1
映射到 [0..95],执行 a并将结果映射回 [32..127]。
回答by rook
Usually cipher text is base64 encoded, base16 (hex) also works well. Base64 is used most often for cipher text because it takes up less space than hex, hex is most commonly used for message digests. In the java.util.prefs.Base64 library you will find byteArrayToBase64() and base64ToByteArray().
通常密文是 base64 编码的,base16(十六进制)也很好用。Base64 最常用于密文,因为它比十六进制占用更少的空间,十六进制最常用于消息摘要。在 java.util.prefs.Base64 库中,您将找到 byteArrayToBase64() 和 base64ToByteArray()。
On a side note you should NEVER write your own encryption algorithm for security reasons, you should be using a block cipher or stream cipher. I hope this is for fun!
附带说明一下,出于安全原因,您永远不应该编写自己的加密算法,您应该使用分组密码或流密码。我希望这是为了好玩!
回答by Rodolfo
there! Is there any way to consider the whole range of characters? For example, "á", "é", "?", "?", and not consider " " (the [Space])? (For example, my String is "Hello World", and the standard result is "Khoor#Zruog"; I want to erase that "#", so the result would be "KhoorZruog")
那里!有没有办法考虑整个字符范围?例如,“á”、“é”、“?”、“?”,而不考虑“”([空格])?(例如,我的字符串是“Hello World”,标准结果是“Khoor#Zruog”;我想删除那个“#”,所以结果是“KhoorZruog”)
I'm sure my answer is in this piece of code:
我确定我的答案在这段代码中:
if (c >= 32 && c <= 127)
{
// Change base to make life easier, and use an
// int explicitly to avoid worrying... cast later
int x = c - 32;
x = (x + shift) % 96;
chars[i] = (char) (x + 32);
}
... But I've tried some things, and the didn't work :S So, I'll wait for your answers :D See you!
...但我已经尝试了一些东西,但没有奏效 :S 所以,我会等你的答案 :D 再见!
回答by Obscure
Why not try
为什么不试试
for(int i = 0; i < length; i++)
{
char c = chars[i]
if(Character.isLetter(c))
{
int x = c - 32;
x = (x + shift) % 96;
chars[i] = (char) (x+32);
}
}
for(int i = 0; i < length; i++)
{
char c = chars[i]
if(Character.isLetter(c))
{
int x = c - 32;
x = (x + shift) % 96;
chars[i] = (char) (x+32);
}
}
回答by xameeramir
Copy paste this in NetBeans with name "caesar":
将其复制粘贴到名为“caesar”的 NetBeans 中:
//package caesar;
import java.io.*;
public class caesar {
int offset=3;
public String encrypt(String s) throws IOException
{
StringBuilder sb=new StringBuilder();
for(int i=0;i<s.length();i++)
{
char t=s.charAt(i);
if(t>='A' && t<='Z')
{
int t1=t-'A'+offset;
t1=t1%26;
sb.append((char)(t1+'A'));
}
else if(t>='a' && t<='z')
{
int t1=t-'a'+offset;
t1=t1%26;
sb.append((char)(t1+'a'));
}
}
return sb.toString();
}
public String decrypt(String s) throws IOException
{
StringBuilder sb=new StringBuilder();
for(int i=0;i<s.length();i++)
{
char t=s.charAt(i);
if(t>='A' && t<='Z')
{
int t1=t-'A'-offset;
if(t1<0)t1=26+t1;
sb.append((char)(t1+'A'));
}
else if(t>='a' && t<='z')
{
int t1=t-'a'-offset;
if(t1<0)t1=26+t1;
sb.append((char)(t1+'a'));
}
}
return sb.toString();
}
public static void main(String[] args) {
try
{
System.out.println("Caesar encrypion technique");
BufferedReader b;
String oriTxt,encTxt,decTxt;
System.out.println("Enter string to encrypt:");
b=new BufferedReader(new InputStreamReader(System.in));
oriTxt=b.readLine();
caesar c=new caesar();
encTxt=c.encrypt(oriTxt);
System.out.println("Encrypted text :"+encTxt);
decTxt=c.decrypt(encTxt);
System.out.println("Derypted text :"+decTxt);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
}
回答by Tanujit Roy
import java.util.Scanner;
//caeser
public class Major_Assingment {
public static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZhh";
public static String encrypt(String plainText,int shiftKey)
{
plainText = plainText.toUpperCase();
String cipherText= " ";
for(int i=0; i<plainText.length(); i++)
{
int charPosition = ALPHABET.indexOf(plainText.charAt(i));
int keyVal = (shiftKey + charPosition)% 26 ;
char replaceVal = ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}
return cipherText;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string for Encryption:");
String message = new String();
message = sc.next();
System.out.println(encrypt(message,3));
sc.close();
}
}