JAVA 可逆加密算法的简单实现 - XOR异或运算

来源:互联网 发布:移动网络能玩lol吗 编辑:程序博客网 时间:2024/06/05 16:57

很多加密包都提供复杂的加密算法,比如MD5,这些算法有的是不可逆的。

有时候我们需要可逆算法,将敏感数据加密后放在数据库或配置文件中,在需要时再再还原。

这里介绍一种非常简单的java实现可逆加密算法。

算法使用一个预定义的种子(seed)来对加密内容进行异或运行,解密只用再进行一次异或运算就还原了。

代码如下:

seed任意写都可以。

 

package cn.exam.signup.service.pay.util;import java.math.BigInteger;import java.util.Arrays;public class EncrUtil {private static final int RADIX = 16;private static final String SEED = "0933910847463829232312312";public static final String encrypt(String password) {if (password == null)return "";if (password.length() == 0)return "";BigInteger bi_passwd = new BigInteger(password.getBytes());BigInteger bi_r0 = new BigInteger(SEED);BigInteger bi_r1 = bi_r0.xor(bi_passwd);return bi_r1.toString(RADIX);}public static final String decrypt(String encrypted) {if (encrypted == null)return "";if (encrypted.length() == 0)return "";BigInteger bi_confuse = new BigInteger(SEED);try {BigInteger bi_r1 = new BigInteger(encrypted, RADIX);BigInteger bi_r0 = bi_r1.xor(bi_confuse);return new String(bi_r0.toByteArray());} catch (Exception e) {return "";}}public static void main(String args[]){System.out.println(Arrays.toString(args));if(args==null || args.length!=2) return;if("-e".equals(args[0])){System.out.println(args[1]+" encrypt password is "+encrypt(args[1]));}else if("-d".equals(args[0])){System.out.println(args[1]+" decrypt password is "+decrypt(args[1]));}else{System.out.println("args -e:encrypt");System.out.println("args -d:decrypt");}}}


运行以上代码:

[-e, 1234567890]
1234567890 encrypt password is 313233376455276898a5

[-d, 313233376455276898a5]
313233376455276898a5 decrypt password is 1234567890

 

原创粉丝点击