有些响应https请求的接口,需要在客户端添加证书的情况,其目的是加密在网络之间传输的请求报文,保证信息安全;
证书的加密方式多种多样,本案例以JKS加密的证书为例:
1.获取证书私钥PrivateKey
private static PrivateKey getPrivateKey(String priKeyFile, String storePassword) throws Exception {
char[] storePwdArr;
int i;
BufferedInputStream bis = null;
try {
KeyStore ks = KeyStore.getInstance("JKS");
//加载证书
FileInputStream fis = new FileInputStream(priKeyFile);
bis = new BufferedInputStream(fis);
//证书中的加密key
String storeAlias = "signKey";
storePwdArr = new char[storePassword.length()];// store password
for (i = 0; i < storePassword.length(); i++) {
storePwdArr[i] = storePassword.charAt(i);
}
ks.load(bis, storePwdArr);
PrivateKey priv = (PrivateKey) ks.getKey(storeAlias, storePwdArr);
return priv;
} catch (KeyStoreException e) {
e.printStackTrace();
throw new Exception("1");
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new Exception("2", e);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new Exception("3", e);
} catch (CertificateException e) {
e.printStackTrace();
throw new Exception("4", e);
} catch (IOException e) {
e.printStackTrace();
throw new Exception("5", e);
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
throw new Exception("6", e);
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.