国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

一個Java配置文件加密解密工具類分享

2019-11-26 15:32:19
字體:
來源:轉載
供稿:網友

常見的如: 數據庫用戶密碼,短信平臺用戶密碼,系統間校驗的固定密碼等。
本工具類參考了 《Spring.3.x企業應用開發實戰》一書 5.3節的實現。
完整代碼與注釋信息如下:

復制代碼 代碼如下:

package com.cncounter.util.comm;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESUtils {

 // 密鑰
 private static Key key;
 // KEY種子
 private static String KEY_STR = "encrypt@cncounter.com";
 // 常量
 public static final String UTF_8 = "UTF-8";
 public static final String DES = "DES";

 // 靜態初始化
 static{
  try {
   // KEY 生成器
   KeyGenerator generator = KeyGenerator.getInstance(DES);
   // 初始化,安全隨機算子
   generator.init(new SecureRandom( KEY_STR.getBytes(UTF_8) ));
   // 生成密鑰
   key = generator.generateKey();
   generator = null;
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }

 /**
  * 對源字符串加密,返回 BASE64編碼后的加密字符串
  * @param source 源字符串,明文
  * @return 密文字符串
  */
 public static String encode(String source){
  try {
   // 根據編碼格式獲取字節數組
   byte[] sourceBytes = source.getBytes(UTF_8);
   // DES 加密模式
   Cipher cipher = Cipher.getInstance(DES);
   cipher.init(Cipher.ENCRYPT_MODE, key);
   // 加密后的字節數組
   byte[] encryptSourceBytes = cipher.doFinal(sourceBytes);
   // Base64編碼器
   BASE64Encoder base64Encoder = new BASE64Encoder();
   return base64Encoder.encode(encryptSourceBytes);
  } catch (Exception e) {
   // throw 也算是一種 return 路徑
   throw new RuntimeException(e);
  }
 }

 /**
  * 對本工具類 encode() 方法加密后的字符串進行解碼/解密
  * @param encrypted 被加密過的字符串,即密文
  * @return 明文字符串
  */
 public static String decode(String encrypted){
  // Base64解碼器
  BASE64Decoder base64Decoder = new BASE64Decoder();
  try {
   // 先進行base64解碼
   byte[] cryptedBytes = base64Decoder.decodeBuffer(encrypted);
   // DES 解密模式
   Cipher cipher = Cipher.getInstance(DES);
   cipher.init(Cipher.DECRYPT_MODE, key);
   // 解碼后的字節數組
   byte[] decryptStrBytes = cipher.doFinal(cryptedBytes);
   // 采用給定編碼格式將字節數組變成字符串
   return new String(decryptStrBytes, UTF_8);
  } catch (Exception e) {
   // 這種形式確實適合處理工具類
   throw new RuntimeException(e);
  }
 }
 // 單元測試
 public static void main(String[] args) {
  // 需要加密的字符串
  String email = "renfufei@qq.com";
  // 加密
  String encrypted = DESUtils.encode(email);
  // 解密
  String decrypted = DESUtils.decode(encrypted);
  // 輸出結果;
  System.out.println("email: " + email);
  System.out.println("encrypted: " + encrypted);
  System.out.println("decrypted: " + decrypted);
  System.out.println("email.equals(decrypted): " + email.equals(decrypted));
 }
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 柘城县| 阿尔山市| 嘉义市| 冕宁县| 天柱县| 尉氏县| 苏尼特右旗| 界首市| 文成县| 青岛市| 罗山县| 松江区| 龙井市| 昌邑市| 日照市| 安福县| 荆门市| 阿巴嘎旗| 富顺县| 万州区| 荆州市| 松滋市| 岳普湖县| 湘潭市| 宜丰县| 寿宁县| 蕉岭县| 柯坪县| 平度市| 河曲县| 西城区| 巢湖市| 连江县| 湘潭市| 调兵山市| 客服| 上蔡县| 顺义区| 龙井市| 宁远县| 开阳县|