淘先锋技术网

首页 1 2 3 4 5 6 7

Java读取公钥和私钥的方法类似,只需要将公钥或私钥文件的路径传入程序并读取。

读取公钥

public static PublicKey getPublicKey(String publicKeyPath) throws Exception {
byte[] publicKeyBytes = readKeyBytes(publicKeyPath);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
return publicKey;
}
private static byte[] readKeyBytes(String keyPath) throws IOException {
InputStream inputStream = new FileInputStream(keyPath);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
inputStream.close();
return bytes;
}

其中,使用X509EncodedKeySpec类来处理公钥的ASN.1格式,使用KeyFactory类来产生公钥对象。

读取私钥

public static PrivateKey getPrivateKey(String privateKeyPath, String password) throws Exception {
byte[] privateKeyBytes = readKeyBytes(privateKeyPath);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
char[] passwordChars = password.toCharArray();
EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(privateKeyBytes);
Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
PBEKeySpec pbeKeySpec = new PBEKeySpec(passwordChars);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
AlgorithmParameters algorithmParameters = encryptedPrivateKeyInfo.getAlgParameters();
cipher.init(Cipher.DECRYPT_MODE, secretKey, algorithmParameters);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
return privateKey;
}
private static byte[] readKeyBytes(String keyPath) throws IOException {
InputStream inputStream = new FileInputStream(keyPath);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
inputStream.close();
return bytes;
}

其中,使用PKCS8EncodedKeySpec类来处理私钥的ASN.1格式,使用EncryptedPrivateKeyInfo类和PBEKeySpec类来获取加密算法名称和密码。