利用AES加密存储数据库信息到配置文件(格式:XML),获取并解密初始化数据库信息为静态参数——含AES加密解密,代码中最后三个方法即是

maven

<dependency>
  	<groupId>com.alibaba</groupId>
  	<artifactId>fastjson</artifactId>
  	<version>1.2.32</version>
</dependency>
  	
<dependency> 
	<groupId>commons-codec</groupId>
	<artifactId>commons-codec</artifactId>
	<version>1.9</version> 
</dependency> 
     <!-- dom4j -->
<dependency>
	<groupId>dom4j</groupId>
	<artifactId>dom4j</artifactId>
	<version>1.6.1</version>
</dependency>

完整demo代码


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.alibaba.fastjson.JSONObject;

import javax.crypto.*;

import java.io.File;
import java.util.Base64;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.DocumentException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.security.SecureRandom;

public class AesUtil {
	
	private static String storeid;
	private static String ip;
	private static String num;
	private static String pwd;

	public static String getStoreid() {
		return storeid;
	}

	public static void setStoreid(String storeid) {
		AesUtil.storeid = storeid;
	}

	public static String getIp() {
		return ip;
	}

	public static void setIp(String ip) {
		AesUtil.ip = ip;
	}

	public static String getNum() {
		return num;
	}

	public static void setNum(String num) {
		AesUtil.num = num;
	}

	public static String getPwd() {
		return pwd;
	}

	public static void setPwd(String pwd) {
		AesUtil.pwd = pwd;
	}

	public static void main(String[] args) throws Exception {
//		存储加密数据
		setXml(Encrypt("ip123456"), Encrypt("num789"), Encrypt("pwe123456"), Encrypt("33"));
//		初始化赋值给静态参数
		init();
	}

	/**
	 * 获取信息转化为json格式然后进行检查信息的完整度,赋值给静态参数
	 * @return
	 * @throws Exception
	 */
	public static void init() throws Exception {
		JSONObject obj = getXml();
		if (obj.containsKey("ip")&&obj.getString("ip").length()>0) {
			setIp(obj.getString("ip"));
		} else {
			throw new NullPointerException("ip");
		}
		if (obj.containsKey("num")&&obj.getString("num").length()>0) {
			setNum(obj.getString("num"));
		} else {
			throw new NullPointerException("num");
		}
		if (obj.containsKey("pwd")&&obj.getString("pwd").length()>0) {
			setPwd(obj.getString("pwd"));
		} else {
			throw new NullPointerException("pwd");
		}
		if (obj.containsKey("storeid")&&obj.getString("storeid").length()>0) {
			setStoreid(obj.getString("storeid"));
		} else {
			throw new NullPointerException("storeid");
		}
	}

	/**
	 * 获取信息转化为json格式
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getXml() throws Exception {
		JSONObject obj = new JSONObject();
		try {
			SAXReader sax = new SAXReader();
			Document doc = sax.read(new File("config.xml"));
			Element root = doc.getRootElement();
			List<Element> firstChild = root.elements();
			for (Element firstEle : firstChild) {
				List<Attribute> afirstEle = firstEle.attributes();
				for (Attribute attr : afirstEle) {
					obj.put(attr.getName(), Decrpyt(attr.getText()));
				}
			}
		} catch (DocumentException ex) {
			ex.printStackTrace();
		}
		System.out.println(obj);
		return obj;
	}
	/**
	 * 存储信息到相对路径下
	 * @return
	 * @throws Exception
	 */
	public static void setXml(String ip, String num, String pwd, String storeid) throws Exception {
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("Datebase");
		Element user = root.addElement("user");
		user.addAttribute("ip", ip);
		user.addAttribute("num", num);
		user.addAttribute("pwd", pwd);
		user.addAttribute("storeid", storeid);
		OutputStream os = new FileOutputStream("config.xml");
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		XMLWriter xw = new XMLWriter(os, format);
		xw.write(doc);
		xw.flush();
		xw.close();
	}

	private static final String ALGORITHM = "AES";

	/**
	 * 生成秘钥
	 * @return
	 * @throws Exception
	 */
	private static SecretKey geneKey() throws Exception {
		KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
		SecureRandom random = new SecureRandom();
//		自定义秘钥关键
		random.setSeed("lxd123456".getBytes());
		keyGenerator.init(random);
		SecretKey secretKey = keyGenerator.generateKey();
		return secretKey;
	}
	/**
	 * 加密
	 * @return
	 * @throws Exception
	 */
	public static String Encrypt(String content) throws Exception {
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		SecretKey secretKey = AesUtil.geneKey();
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		cipher.update(content.getBytes());
		byte[] result = cipher.doFinal();
		String base64Result = Base64.getEncoder().encodeToString(result);
		return base64Result;
	}
	/**
	 * 解密
	 * @return
	 * @throws Exception
	 */
	public static String Decrpyt(String content) throws Exception {
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		SecretKey secretKey = AesUtil.geneKey();
		cipher.init(Cipher.DECRYPT_MODE, secretKey);
		byte[] encodedBytes = Base64.getDecoder().decode(content.getBytes());
		byte[] result = cipher.doFinal(encodedBytes); 
		return new String(result);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值