我是靠谱客的博主 认真哈密瓜,这篇文章主要介绍装饰模式实例与解析 实例二:多重加密系统,现在分享给大家,希望可以做个参考。

实例二:多重加密系统 某系统提供了一个数据加密功能,可以对字符串进行加密。最简单的加密算法通过对字母进行移位来实现,同时还提供了稍复杂的逆向输出加密,还提供了更为高级的求模加密。用户先使用最简单的加密算法对字符串进行加密,如果觉得还不够可以对加密之后的结果使用其他加密算法进行二次加密,当然也可以进行第三次加密。现使用装饰模式设计该多重加密系统。

 

 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class AdvancedCipher extends CipherDecorator { public AdvancedCipher(Cipher cipher) { super(cipher); } public String encrypt(String plainText) { String result=super.encrypt(plainText); result=mod(result); return result; } public String mod(String text) { String str=""; for(int i=0;i<text.length();i++) { String c=String.valueOf(text.charAt(i)%6); str+=c; } return str; } }
复制代码
1
2
3
4
5
public interface Cipher { public String encrypt(String plainText); }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class CipherDecorator implements Cipher { private Cipher cipher; public CipherDecorator(Cipher cipher) { this.cipher=cipher; } public String encrypt(String plainText) { return cipher.encrypt(plainText); } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Client { public static void main(String args[]) { String password="sunnyLiu"; //明文 String cpassword; //密文 Cipher sc,cc; sc=new SimpleCipher(); cpassword=sc.encrypt(password); System.out.println(cpassword); System.out.println("---------------------"); cc=new ComplexCipher(sc); cpassword=cc.encrypt(password); System.out.println(cpassword); System.out.println("---------------------"); /* ac=new AdvancedCipher(cc); cpassword=ac.encrypt(password); System.out.println(cpassword); System.out.println("---------------------"); */ } }

 

 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class ComplexCipher extends CipherDecorator { public ComplexCipher(Cipher cipher) { super(cipher); } public String encrypt(String plainText) { String result=super.encrypt(plainText); result=reverse(result); return result; } public String reverse(String text) { String str=""; for(int i=text.length();i>0;i--) { str+=text.substring(i-1,i); } return str; } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class SimpleCipher implements Cipher { public String encrypt(String plainText) { String str=""; for(int i=0;i<plainText.length();i++) { char c=plainText.charAt(i); if(c>='a'&&c<='z') { c+=6; if(c>'z') c-=26; if(c<'a') c+=26; } if(c>='A'&&c<='Z') { c+=6; if(c>'Z') c-=26; if(c<'A') c+=26; } str+=c; } return str; } }

 

最后

以上就是认真哈密瓜最近收集整理的关于装饰模式实例与解析 实例二:多重加密系统的全部内容,更多相关装饰模式实例与解析内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(116)

评论列表共有 0 条评论

立即
投稿
返回
顶部