对称加密之凯撒密码

凯撒密码作为一种最为古老的对称加密体制,在古罗马的时候都已经很流行,他的基本思想是:通过把字母移动一定的位数来实现加密和解密。例如,如果密匙是把 明文字母的位数向后移动三位,那么明文字母B就变成了密文的E,依次类推,X将变成A,Y变成B,Z变成C,由此可见,位数就是凯撒密码加密和解密的密 钥。 

 

JAVA实现代码如下:

 

import java.io.UnsupportedEncodingException;

public class test1 {
	public String encrypt(String str, Integer key) {

		String s = "";
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (c >= 'a' && c <= 'z') // 是小写字母
			{
				c += key % 26; // 移动key%26 位
				if (c < 'a')
					c += 26; // 向左超界
				if (c > 'z')
					c -= 26; // 向右超界
			} else if (c >= 'A' && c <= 'Z') // 是大写字母
			{
				c += key % 26;
				if (c < 'A')
					c += 26;
				if (c > 'Z')
					c -= 26;
			}
			s += c;
		}
		return s;
	}
	
	public static void main(String args[]) throws UnsupportedEncodingException
	{
		String str = "HowAreYou";
		test1 t = new test1();
		String str1 = t.encrypt(str, 3);
		String str2 = t.encrypt(str1, -3);
		System.out.println("原文:"+str);
		System.out.println("加密后:"+str1);
		System.out.println("解密后:"+str2);
	}
}

 打印结果:

原文:HowAreYou
加密后:KrzDuhBrx
解密后:HowAreYou

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值