---
title: "java 加密解密 示例"
author: "彭自荣"
date: "2008-05-23T13:09:02Z"
tags: []
slug: "java"
draft: false
lastmod: "2008-05-23T13:09:02Z"
id: 196031
url: "https://rian.iteye.com/blog/196031"
---

```java

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

public class Demo {
	public static void main(String args[]) {
		String password = "administrator";
		try {
			Demo.PrivEncrypt(password,"t.obj");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param oldStr
	 *            要加密的串
	 * @param keyFile
	 *            私有key所在的文件路径
	 * @throws Exception
	 */
	public static void PrivEncrypt(String oldStr,String keyFile) throws Exception {
		System.out.println("原始："+oldStr);
		byte[] plainText = oldStr.getBytes("GBK");
		Key key = getPriveKey(keyFile);
		// 获得一个私鈅加密类Cipher，ECB是加密方式，PKCS5Padding是填充方法
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		
		cipher.init(Cipher.ENCRYPT_MODE, key);// 使用私鈅加密
		byte[] cipherText = cipher.doFinal(plainText);
		System.out.println("加密："+new String(cipherText, "UTF8"));
		
		cipher.init(Cipher.DECRYPT_MODE, key);// 使用私钥解密
		byte[] newPlainText = cipher.doFinal(cipherText);
		System.out.println("解密："+new String(newPlainText, "UTF8"));
	}

	// 把Key 写到文件中：生成一个私有Key对象，保存在文件中
	public static void setPriveKey(String file) {
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(file);
			KeyGenerator keyGen = KeyGenerator.getInstance("DES");
			keyGen.init(128);
			Key key = keyGen.generateKey();// 生成私钥Key
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(key);
			oos.close();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
	// 从文件中读Key：客户端可以根据管理员提供的私钥Key文件提取Key对象
	public static Key getPriveKey(String file) throws Exception {
		FileInputStream fis = new FileInputStream(file);
		ObjectInputStream ois = new ObjectInputStream(fis);
		Key key = (Key) ois.readObject();
		return key;
	}
}
/* 运行结果：
 * 原始：administrator 
 * 加密：!Y????I?? ??R;?
 * 解密：administrator
 */

```