本帖最后由 chung 于 2013-8-26 17:38 编辑
- package test;
- import java.util.Scanner;
- public class CaeserTest {
- public static char ascii2Char(int ASCII) {
- return (char) ASCII;
- }
- public static String ascii2String(int[] ASCIIs) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < ASCIIs.length; i++) {
- sb.append((char) ascii2Char(ASCIIs[i]));
- }
- return sb.toString();
- }
- public String encrypt(String str, int key){
-
- char[] chars = str.toCharArray();
- int[] asciiArray = new int[chars.length];
- key = key%127;
-
- for(int i = 0; i < chars.length; i++){
- //System.out.println((int)chars[i]);
- asciiArray[i] = (int) (chars[i]) + key;
- //System.out.println(asciiArray[i]);
- }
- return ascii2String(asciiArray);
- }
-
- public String decrypt(String str, int key){
- char[] chars = str.toCharArray();
- int[] asciiArray = new int[chars.length];
- key = key%127;
- for(int i = 0; i < chars.length; i++){
- //System.out.println((int)chars[i]);
- asciiArray[i] = (int) (chars[i]) - key;
- //System.out.println(asciiArray[i]);
- }
- return ascii2String(asciiArray);
- }
-
- public static void main(String[] args) {
- CaeserTest ct = new CaeserTest();
- System.out.println("输入明文字符串:");
- Scanner input = new Scanner(System.in);
- String str = input.nextLine();
-
- System.out.print("输入密钥:");
- int key = input.nextInt();
-
- System.out.println("输出密文字符串:" + new String(ct.encrypt(str, key)));
- System.out.println("输出明文字符串:" + new String(ct.decrypt(ct.encrypt(str, key), key)));
- }
- }
复制代码 凯撒密码简单的加解密实现 |