java keysore操作

package com.eca.mind.bmw.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Encoder;

public class KeyStoreUtils {

private static final Logger logger = LoggerFactory.getLogger(KeyStoreUtils.class);

	  /**
	   *从文件中获得keystore
	  * @Title: getKeyStore  
	  * @Description: 从文件中获得 keystore
	  * @param @param keyStorePath 路径
	  * @param @param password  密码
	  * @param @param type 类型
	  * @param @return
	  * @param @throws Exception    参数  
	  * @return KeyStore    返回类型  
	  * @throws
	   */
	 public static KeyStore getKeyStore(String keyStorePath, String password,String type) throws Exception {
	   FileInputStream is = new FileInputStream(keyStorePath);
	   KeyStore ks = KeyStore.getInstance(type);
	   ks.load(is, password.toCharArray());
	   is.close();
	   return ks;
	 }

	 /**
	  * 把字符串转化为公钥证书
	 * @Title: tranString2cer  
	 * @Description: 把字符串转化为公钥证书  
	 * @param @param certStrign
	 * @param @return
	 * @param @throws Exception    参数  
	 * @return Certificate    返回类型  
	 * @throws
	  */
	 public static Certificate tranString2cer(String certStrign) throws Exception {
			CertificateFactory cf = CertificateFactory.getInstance("X.509");
			Certificate ca = cf.generateCertificate(new ByteArrayInputStream(certStrign.getBytes()));
	         return ca;
		}
	/**
	 *  
	* @Title: setPublicKeyCer2Privatekey  
	* @Description: 将公钥导入到私钥中
	* @param @param privatkeypath 私钥路径
	* @param @param privatekeyPassword 私钥密码
	* @param @param publicKeyCerPath 公钥路径
	* @param @param alias  别名
	* @param @return    参数  
	* @return Boolean    返回类型  
	* @throws
	 */
	 public static Boolean setPublicKeyCer2Privatekey(String privatkeypath,String privatekeyPassword,String publicKeyCerPath,String alias)  {
		try {
			//获得公钥流
			InputStream certIn = new FileInputStream(new File(publicKeyCerPath));
			File file = new File(privatkeypath);
			 //获得私钥流
			InputStream localCertIn = new FileInputStream(file);
			KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
			//获得keystore
			keystore.load(localCertIn, privatekeyPassword.toCharArray());
			if (keystore.containsAlias(alias)) {
				certIn.close();
				localCertIn.close();
				keystore.deleteEntry(alias);
			}
			localCertIn.close();
			BufferedInputStream bis = new BufferedInputStream(certIn);
			CertificateFactory cf = CertificateFactory.getInstance("X.509");
			while (bis.available() > 0) {
				Certificate cert = cf.generateCertificate(bis);
				keystore.setCertificateEntry(alias, cert);
			}
			certIn.close();
			OutputStream out = new FileOutputStream(file);
			keystore.store(out, privatekeyPassword.toCharArray());
			out.close();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
			return false;
	 }
	    return true;
	 }
	 /**
	  * 删除公钥
	 * @Title: deletePublicKeyCer2Privatekey  
	 * @Description: 删除公钥
	 * @param @param privatkeypath
	 * @param @param privatekeyPassword
	 * @param @param alias
	 * @param @return    参数  
	 * @return Boolean    返回类型  
	 * @throws
	  */
	 public static Boolean deletePublicKeyCer2Privatekey(String privatkeypath,String privatekeyPassword,String alias)  {
		 try {
			 File file = new File(privatkeypath);
			 //获得私钥流
			 InputStream localCertIn = new FileInputStream(file);
			 KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
			 //获得keystore
			 keystore.load(localCertIn, privatekeyPassword.toCharArray());
			 if (keystore.containsAlias(alias)) {
				 localCertIn.close();
				 keystore.deleteEntry(alias);
			 }else {
				 logger.info("别名{}不存在",alias);
			 }
			 localCertIn.close();
			 OutputStream out = new FileOutputStream(file);
			 keystore.store(out, privatekeyPassword.toCharArray());
			 out.close();
		 } catch (Exception e) {
			 logger.error(e.getMessage(), e);
			 e.printStackTrace();
			 return false;
		 }
		 return true;
	 }
	 /**
	  * 
	 * @Title: setPublicKeyCerString2Privatekey  
	 * @Description: 公钥字符串 导入私钥
	 * @param @param privatkeypath 私钥路径
	 * @param @param privatekeyPassword 私钥密码
	 * @param @param publicKeystring 公钥字符串
	 * @param @param alias
	 * @param @return    参数  
	 * @return Boolean    返回类型  
	 * @throws
	  */
	 public static Boolean setPublicKeyCerString2Privatekey(String privatkeypath,String privatekeyPassword,String publicKeystring,String alias)  {
		 try {
			 //获得公钥
			 File file = new File(privatkeypath);
			 publicKeystring= new String(publicKeystring.getBytes("UTF-8"));
			 publicKeystring= publicKeystring.replace(" ", "\n");
			 publicKeystring = publicKeystring.trim();
			 publicKeystring=publicKeystring.replace(publicKeystring.substring(0, 27), "-----BEGIN CERTIFICATE-----");
			 // \r\n-----END CERTIFICATE-----
			 publicKeystring=publicKeystring.replace(publicKeystring.substring(publicKeystring.length()-25), "\r\n-----END CERTIFICATE-----");
			 //获得私钥流
		     InputStream localCertIn = new FileInputStream(file);
			 KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
			 //获得keystore
			 keystore.load(localCertIn, privatekeyPassword.toCharArray());
			 if (keystore.containsAlias(alias)) {
				 keystore.deleteEntry(alias);
			 }
			 localCertIn.close();
			Certificate cert = tranString2cer(publicKeystring);
			keystore.setCertificateEntry(alias, cert);
			 OutputStream out = new FileOutputStream(file);
			 keystore.store(out, privatekeyPassword.toCharArray());
			 out.close();
		 } catch (Exception e) {
			 e.printStackTrace();
			 return false;
		 }
		 return true;
	 }
	 /**
	  * 导出公钥cer证书
	 * @Title: exportPublic4keystore  
	 * @Description: 继续base64 导出cer文件
	 * @param @param privatekeystorepath
	 * @param @param privatekeystorePassword
	 * @param @param alias
	 * @param @return    参数  
	 * @return String    返回类型  
	 * @throws
	  */
	 public static String exportPublic4keystore(String privatekeystorepath,String privatekeystorePassword,String alias,String exportFilePath) {
		 try {
			 File file = new File(privatekeystorepath);
			 //获得私钥流
		     InputStream localCertIn = new FileInputStream(file);
			 KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
			 keystore.load(localCertIn, privatekeystorePassword.toCharArray());
			 KeyStoreUtils.exportCert(keystore,alias,exportFilePath);
			 InputStream certIn = new FileInputStream(new File(exportFilePath));
			 StringBuilder sb = new StringBuilder();
			 String line;
			 BufferedReader br = new BufferedReader(new InputStreamReader(certIn));
				while ((line = br.readLine()) != null) {
				    sb.append(line);
				}
			 certIn.close();
			 localCertIn.close();
  			return  sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	 }  
		//导出公钥
		public static void exportPublicKey(PublicKey publicKey,String exportFile) throws Exception {
			BASE64Encoder encoder = new BASE64Encoder();
			String encoded = encoder.encode(publicKey.getEncoded());
			FileWriter fw = new FileWriter(exportFile);
			fw.write("—–BEGIN PUBLIC KEY—–\r\n");		//非必须
			fw.write(encoded);
			fw.write("\r\n—–END PUBLIC KEY—–");		//非必须
			fw.close();
		}
		//导出证书 base64格式
		public static void exportCert(KeyStore keystore, String alias, String exportFile) throws Exception {
			Certificate cert = keystore.getCertificate(alias);
			BASE64Encoder encoder = new BASE64Encoder();
			String encoded = encoder.encode(cert.getEncoded());
			FileWriter fw = new FileWriter(exportFile);
			fw.write("-----BEGIN CERTIFICATE-----\r\n");	//非必须
			fw.write(encoded);
			fw.write("\r\n-----END CERTIFICATE-----");	//非必须
			fw.close();
		}
		//得到KeyPair
		public static KeyPair getKeyPair(KeyStore keystore, String alias,char[] password) {
			try {
				Key key = keystore.getKey(alias, password);
				if (key instanceof PrivateKey) {
					Certificate cert = keystore.getCertificate(alias);
					PublicKey publicKey = cert.getPublicKey();
					return new KeyPair(publicKey, (PrivateKey) key);
				}
			} catch (Exception e) {
			} 
			return null;
		}

		//导出私钥
		public static void exportPrivateKey(PrivateKey privateKey,String exportFile) throws Exception {
			BASE64Encoder encoder = new BASE64Encoder();
			String encoded = encoder.encode(privateKey.getEncoded());
			FileWriter fw = new FileWriter(exportFile);
			fw.write("—–BEGIN PRIVATE KEY—–\r\n");	//非必须
			fw.write(encoded);
			fw.write("\r\n—–END PRIVATE KEY—–");		//非必须
			fw.close();
		}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_37749055

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值