欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一个Java配置文件加密解密工具类分享

程序员文章站 2024-02-26 10:44:46
常见的如: 数据库用户密码,短信平台用户密码,系统间校验的固定密码等。本工具类参考了 《spring.3.x企业应用开发实战》一书 5.3节的实现。完整代码与注释信息如下:...

常见的如: 数据库用户密码,短信平台用户密码,系统间校验的固定密码等。
本工具类参考了 《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));
 }
}