java實(shí)現(xiàn)可逆加密算法
很多加密包都提供復(fù)雜的加密算法,比如MD5,這些算法有的是不可逆的。
有時(shí)候我們需要可逆算法,將敏感數(shù)據(jù)加密后放在數(shù)據(jù)庫或配置文件中,在需要時(shí)再再還原。
這里介紹一種非常簡(jiǎn)單的java實(shí)現(xiàn)可逆加密算法。
算法使用一個(gè)預(yù)定義的種子(seed)來對(duì)加密內(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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
巧用FutureTask 線程池輕松解決接口超時(shí)問題
這篇文章主要為大家介紹了使用FutureTask結(jié)合線程池輕松解決接口超時(shí)問題的巧妙用法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
MyBatis查詢數(shù)據(jù)庫語句總結(jié)
MyBatis是一種持久化框架,可以與許多不同類型的關(guān)系型數(shù)據(jù)庫連接,下面這篇文章主要給大家介紹了關(guān)于MyBatis查詢數(shù)據(jù)庫語句的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06
基于SpringBoot和Vue實(shí)現(xiàn)頭像上傳與回顯功能
在現(xiàn)代Web應(yīng)用中,用戶個(gè)性化體驗(yàn)尤為重要,其中頭像上傳與回顯是一個(gè)常見的功能需求,本文將詳細(xì)介紹如何使用Spring Boot和Vue.js構(gòu)建一個(gè)前后端協(xié)同工作的頭像上傳系統(tǒng),并實(shí)現(xiàn)圖片的即時(shí)回顯,需要的朋友可以參考下2024-08-08
mybatis連接MySQL8出現(xiàn)的問題解決方法
這篇文章主要介紹了mybatis連接MySQL8出現(xiàn)的問題解決方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-10-10

