首页 > 编程 > Java > 正文

java实现可逆加密算法

2019-11-26 09:10:29
字体:
来源:转载
供稿:网友

很多加密包都提供复杂的加密算法,比如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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表