很多加密包都提供复杂的加密算法,比如md5,这些算法有的是不可逆的。
有时候我们需要可逆算法,将敏感数据加密后放在数据库或配置文件中,在需要时再再还原。
这里介绍一种非常简单的java实现可逆加密算法。
算法使用一个预定义的种子(seed)来对加密内容进行异或运行,解密只用再进行一次异或运算就还原了。
代码如下:
seed任意写都可以。
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/rpg_marker/article/details/8213196