装饰模式实例与解析 实例二:多重加密系统

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

 

 

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;
	}
}
public interface Cipher
{
	public String encrypt(String plainText);
}
public class CipherDecorator implements Cipher
{
	private Cipher cipher;
	
	public CipherDecorator(Cipher cipher)
	{
		this.cipher=cipher;
	}
	
	public String encrypt(String plainText)
	{
		return cipher.encrypt(plainText);
	}
}
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("---------------------");
		*/
	}
}

 

 

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;
	}
}
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;
	}
}

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值