java 读取使用keytool生产的keystore文件

windows 环境下,使用keytool 生产keystore文件

keytool -genkeypair -keyalg RSA -keysize 1024 -sigalg SHA1withRSA -validity 36000 -alias www.kunlunsoft.com -storepass abcdefg -keystore zlex.keystore -dname "CN=localhost, OU=zlex,O=zlex, L=BJ, ST=BJ, C=CN"

说明:-keyalg :指定key的加密算法;

-sigalg:指定签名算法;

-storepass:指定key的密码

注意keystore 密码和主密码必须相同

操作结果如下:

 

上述命令会生产一个文件zlex.keystore

keystore文件中既包含公钥,也包含私钥。

使用java 读取zlex.keystore 文件:

用于保存私钥和公钥的bean:

 

package com.common.bean;

import java.io.Serializable;
import java.security.PrivateKey;
import java.security.PublicKey;

/***
 * 
 * @author huangwei
 * @since 2013-10-28
 */
public class PrivPubKeyBean implements Serializable {

	private static final long serialVersionUID = 1888415926054715509L;
	/***
	 * 私钥
	 */
	private PrivateKey privKey;
	/***
	 * 公钥
	 */
	private PublicKey publKey;
	/***
	 * 签名算法
	 */
	private String sigAlgName;
	public PrivateKey getPrivKey() {
		return privKey;
	}
	public void setPrivKey(PrivateKey privKey) {
		this.privKey = privKey;
	}
	public PublicKey getPublKey() {
		return publKey;
	}
	public void setPublKey(PublicKey publKey) {
		this.publKey = publKey;
	}
	public String getSigAlgName() {
		return sigAlgName;
	}
	public void setSigAlgName(String sigAlgName) {
		this.sigAlgName = sigAlgName;
	}
	
	
}

 

 

读取keystore文件获取私钥和公钥:

 

/***
	 * 
	 * @param keyStorePath
	 * @param password
	 * @param alias
	 * @return
	 * @throws Exception
	 */
	public static PrivPubKeyBean getPrivPubKeyBean(String keyStorePath,String password,String alias) throws Exception{
		PrivPubKeyBean privPubKeyBean=new PrivPubKeyBean();
		// 获得密钥库
		KeyStore ks =SystemUtil. getKeyStore(keyStorePath, password);
		// 获得私钥
		PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password.toCharArray());
		privPubKeyBean.setPrivKey(privateKey);
		
		// 获得证书
		X509Certificate x509Certificate = (X509Certificate) ks.getCertificate(alias);
		PublicKey pubKey=x509Certificate.getPublicKey();
		privPubKeyBean.setPublKey(pubKey);
		privPubKeyBean.setSigAlgName(x509Certificate.getSigAlgName());
		return privPubKeyBean;
	}

 

 

测试:

 

@Test
	public void test_03() {
		try {
			String message = "whuang";
			String keyStorePath = "d:\\Temp\\a\\a\\ca\\zlex.keystore";
			String password = "abcdefg";
			String alias = "www.kunlunsoft.com";
			PrivPubKeyBean privPubKeyBean = SystemUtil.getPrivPubKeyBean(
					keyStorePath, password, alias);
			byte[] result = SystemUtil.encrypt(message,
					privPubKeyBean.getPublKey());
			byte[] deResult = SystemUtil.decrypt(result,
					privPubKeyBean.getPrivKey());
			System.out.println(new String(deResult));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

 运行结果:whuang

 

SystemUtil 见附件,路径:src\main\java\com\common\util\SystemUtil.java

 

你可能感兴趣的:(keystore,keytool,生成证书,获取私钥,解析keystore文件)