很多加密包都提供復(fù)雜的加密算法,比如md5,這些算法有的是不可逆的。
有時(shí)候我們需要可逆算法,將敏感數(shù)據(jù)加密后放在數(shù)據(jù)庫或配置文件中,在需要時(shí)再再還原。
這里介紹一種非常簡單的java實(shí)現(xiàn)可逆加密算法。
算法使用一個(gè)預(yù)定義的種子(seed)來對加密內(nèi)容進(jìn)行異或運(yùn)行,解密只用再進(jìn)行一次異或運(yùn)算就還原了。
代碼如下:
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" ); } } } |
運(yùn)行以上代碼:
[-e, 1234567890]
1234567890 encrypt password is 313233376455276898a5[-d, 313233376455276898a5]
313233376455276898a5 decrypt password is 1234567890
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/rpg_marker/article/details/8213196