此加密的方式在日後的工作中也可能會經常用到!!!現在學習、正好。
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 用密鑰和明文加密得到密文
*
*
* 2013-12-28
*/
public class Ciphertext {
public static void main(String[] args) {
// 從鍵盤輸入
Scanner sc = new Scanner(System.in);
System.out.println("請輸入密鑰(純數字):");
String key = sc.next();
System.out.println("請輸入要加密的字符串:");
sc.nextLine(); // 跳過"\n"
String text = sc.nextLine();
// 用正則判斷一下密鑰是否純數字
Matcher matcher = Pattern.compile("\\d*").matcher(key);
System.out.println(matcher.matches());
if(matcher.matches()){
Ciphertext.getCiphertext(key.trim(), text.trim());
}else{
System.out.println("輸入的密鑰不是純數字!");
}
}
/**
* 根據轉入的cipherkey和text生成密文
* @param cipherkey 密鑰
* @param text 明文
*/
public static void getCiphertext(String cipherkey, String text){
// 密鑰(數字組成的)
char[] keyArray = cipherkey.toCharArray();
// 明文的字符數組
char[] textArray = text.toCharArray();
for(int i = 0, len = 0; i < textArray.length; i++){
// 當密鑰到末尾後,又重新開始
if(len == keyArray.length){
len = 0;
}
// char轉成String
String temp = Character.toString(keyArray[len]);
// String轉成int
int key = Integer.parseInt(temp);
/*
* 因爲char和int相加默認就會把int轉成char(即unicode碼)來運算
* 所以藉助了String
*/
System.out.print((char)(key + (int)textArray[i])); // 輸出密文
len++;
}
}
}