/**
* 获取RSA私钥对象
*
* @param filePath
* RSA私钥路径
* @param keyAlgorithm
* 密钥算法
* @return RSA私钥对象
* @throws Exception
*/
public static PrivateKey getRSAPrivateKeyByFileSuffix(String filePath, String keyAlgorithm) throws Exception {
InputStream in = null;
try {
BASE64Decoder base64decoder = new BASE64Decoder();
in = new FileInputStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String readLine = null;
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
byte[] b = base64decoder.decodeBuffer(sb.toString());
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(b);
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
PrivateKey priKey = keyFactory.generatePrivate(priPKCS8);
return priKey;
} catch (FileNotFoundException e) {
throw new Exception("私钥路径文件不存在");
} catch (IOException e) {
throw new Exception("读取私钥异常");
} catch (NoSuchAlgorithmException e) {
throw new Exception("生成私钥对象异常");
} catch (InvalidKeySpecException e) {
throw new Exception("生成私钥对象异常");
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
}
}
}
/**
* 获取RSA公钥对象
*
* @param filePath
* RSA公钥路径
* @param keyAlgorithm
* 密钥算法
* @return RSA公钥对象
* @throws Exception
*/
public static PublicKey getRSAPublicKeyByFileSuffix(String filePath, String keyAlgorithm) throws Exception {
InputStream in = null;
try {
BASE64Decoder base64decoder = new BASE64Decoder();
in = new FileInputStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String readLine = null;
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
byte[] b = base64decoder.decodeBuffer(sb.toString());
X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(b);
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
PublicKey pubKey = keyFactory.generatePublic(pubX509);
return pubKey;
} catch (FileNotFoundException e) {
throw new Exception("公钥路径文件不存在");
} catch (IOException e) {
throw new Exception("读取公钥异常");
} catch (NoSuchAlgorithmException e) {
throw new Exception(String.format("生成密钥工厂时没有[%s]此类算法", keyAlgorithm));
} catch (InvalidKeySpecException e) {
throw new Exception("生成公钥对象异常");
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
}
}
}