读书人

对称加密之Caesar密码

发布时间: 2012-10-27 10:42:26 作者: rapoo

对称加密之凯撒密码

凯撒密码作为一种最为古老的对称加密体制,在古罗马的时候都已经很流行,他的基本思想是:通过把字母移动一定的位数来实现加密和解密。例如,如果密匙是把明文字母的位数向后移动三位,那么明文字母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

1 楼 qq123zhz 2011-07-22 对中文没有效果吧。。。。

读书人网 >编程

热点推荐