标签:style blog color java os io for ar
* 所有的加密技术的基本操作都是用encrypt()和decrypt()方法对消息
* 进行分解和组合,其中消息是用空格分隔的字符串,除了encrypt()和decrypt()
* 外每个加密类还需要encode()和decode()方法对每一个单词按照特定的算法
* 规则进行编码,。例如Caesar Cipher 和 Transpose Clipher
* 按照设想由于加密都有相同的方法,因此首先定义一个通用的类Cipher类
* 封装公用的方法。
package Case.Encryption; import java.util.*; public abstract class Cipher { /** * 所有的加密技术的基本操作都是用encrypt()和decrypt()方法对消息 * 进行分解和组合,其中消息是用空格分隔的字符串,除了encrypt()和decrypt() * 外每个加密类还需要encode()和decode()方法对每一个单词按照特定的算法 * 规则进行编码,。例如Caesar Cipher 和 Transpose Clipher * 按照设想由于加密都有相同的方法,因此首先定义一个通用的类Cipher类 * 封装公用的方法。 * * */ public String encrypt(String s){ StringBuffer result=new StringBuffer(); StringTokenizer words=new StringTokenizer(s); while(words.hasMoreTokens()){ result.append(encode(words.nextToken())+""); } return result.toString(); } public String decrypt(String s) { StringBuffer result=new StringBuffer(); StringTokenizer words=new StringTokenizer(s); while(words.hasMoreTokens()) { result.append(decode(words.nextToken())+""); } return result.toString(); } public abstract String encode(String word); public abstract String decode(String woid); }
package Case.Encryption; public class Caesar extends Cipher{ @Override public String encode(String word) { // TODO Auto-generated method stub StringBuffer result =new StringBuffer(); for(int k=0;k<word.length();k++) { char ch=word.charAt(k); ch=(char)(‘a‘+(ch-‘a‘+3)%26);//?正则表达式 result.append(ch); } return result.toString(); } @Override public String decode(String word) { // TODO Auto-generated method stub StringBuffer result =new StringBuffer(); for(int k=0;k<word.length();k++) { char ch=word.charAt(k); ch=(char)(‘a‘+(ch-‘a‘+23)%26);//?正则表达式 result.append(ch); } return result.toString(); } }
package Case.Encryption; /**本例采用的是最简单的翻转易位方法,也可以采用其他的易位方法*/ public class Transpose extends Cipher{ @Override public String encode(String word) { // TODO Auto-generated method stub StringBuffer result =new StringBuffer(); return result.reverse().toString(); } @Override public String decode(String word) { // TODO Auto-generated method stub return encode(word); } }
1 package Case.Encryption; 2 3 public class TestEncrypt { 4 public static void main(String[] args) { 5 Caesar caesar =new Caesar(); 6 String plain ="this is the secret message."; 7 String secret=caesar.encrypt(plain); 8 String decrypt=caesar.decrypt(secret); 9 System.out.println("*********Caesar Cipher Encryption**********"); 10 System.out.println("PlainText: "+plain); 11 System.out.println("Encrypted: "+secret); 12 System.out.println("Decrypted: "+decrypt); 13 14 Transpose ts=new Transpose(); 15 String tsecret=ts.encrypt(plain); 16 String tdecrypt=ts.decrypt(secret); 17 System.out.println("**********Transpose Cipher Encryption**********"); 18 System.out.println("PlainText: "+plain); 19 System.out.println("Encrypted: "+tsecret); 20 System.out.println("Decrypted: "+tdecrypt); 21 } 22 23 }
标签:style blog color java os io for ar
原文地址:http://www.cnblogs.com/zhanggongchang/p/3913264.html