凯撒密码

原理:它将字母表中的字母移动一定位置而实现加密。例如如果向右移动 2 位,则
字母 A 将变为 C,字母 B 将变为 D, …,字母 X 变成 Z,字母 Y 则变为 A,字母 Z 变为 B。因此,假如有个明文字符串“ Hello”用这种方法加密的话,将变为密文:“ Jgnnq”。而如果要解密,则只要将字母向相反方向移动同样位数即可。如密文“ Jgnnq”每个字母左移两位
变为“ Hello”。这里,移动的位数“ 2”是加密和解密所用的密钥。

	/**
	 * @param s 要加密的字符串
	 * @param key 移动的位数
	 * @return
	 */
    public static String KaiSa(String s,int key){
    	String res = "";
    	if(null != s && !s.equals("")){
    		for(int i = 0; i < s.length(); i++){
    			char _c = s.charAt(i);
    			if(_c>='a' && _c<='z'){//是小写字母
    			    _c+=key%26;        //移动 key%26 位
    			   if(_c<'a') _c+=26;  //向左超界
    			   if(_c>'z') _c-=26;  //向右超界
    			}
    			if(_c>='A' && _c<='Z'){// 是大写字母
    			   _c+=key%26;         //移动 key%26 位
    			   if(_c<'A') _c+=26;  //向左超界
    			   if(_c>'Z') _c-=26;  //向右超界
    			}
    			res+=_c;
    		}
    	}
    	return res;
    }
    
    public static void main(String[] args) {
    	//加密
    	String s1 = KaiSaEncryptionAndDecryption.KaiSa("love you",4);
    	System.out.println(s1);	
    	//解密
    	String s2 = KaiSaEncryptionAndDecryption.KaiSa(s1,-4);
    	System.out.println(s2);
	} 



运行结果:
        pszi csy
        love you

猜你喜欢

转载自zhaoxiaoboblogs.iteye.com/blog/2325854