java實(shí)現(xiàn)可逆加密算法
很多加密包都提供復(fù)雜的加密算法,比如MD5,這些算法有的是不可逆的。
有時(shí)候我們需要可逆算法,將敏感數(shù)據(jù)加密后放在數(shù)據(jù)庫或配置文件中,在需要時(shí)再再還原。
這里介紹一種非常簡單的java實(shí)現(xiàn)可逆加密算法。
算法使用一個預(yù)定義的種子(seed)來對加密內(nèi)容進(jìn)行異或運(yùn)行,解密只用再進(jìn)行一次異或運(yùn)算就還原了。
代碼如下:
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"); } } }
運(yùn)行以上代碼:
[-e, 1234567890]
1234567890 encrypt password is 313233376455276898a5[-d, 313233376455276898a5]
313233376455276898a5 decrypt password is 1234567890
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳細(xì)講解springboot如何實(shí)現(xiàn)異步任務(wù)
異步:異步與同步相對,當(dāng)一個異步過程調(diào)用發(fā)出后,調(diào)用者在沒有得到結(jié)果之前,就可以繼續(xù)執(zhí)行后續(xù)操作。也就是說無論異步方法執(zhí)行代碼需要多長時(shí)間,跟主線程沒有任何影響,主線程可以繼續(xù)向下執(zhí)行2022-04-04淺析Spring IOC bean為什么默認(rèn)是單例
單例的意思就是說在 Spring IoC 容器中只會存在一個 bean 的實(shí)例,無論一次調(diào)用還是多次調(diào)用,始終指向的都是同一個 bean 對象,本文小編將和大家一起分析Spring IOC bean為什么默認(rèn)是單例,需要的朋友可以參考下2023-12-12Java判斷范圍型的數(shù)據(jù)是否存在重疊的方法
遇到了個問題,同一天可以輸入多個時(shí)間段,但是每個時(shí)間段的時(shí)間不能出現(xiàn)重疊,這不就是判斷數(shù)據(jù)返回是否有重疊的變種嗎,所以本文給大家介紹了Java判斷范圍型的數(shù)據(jù)是否存在重疊的方法,需要的朋友可以參考下2024-07-07