1. 生成2048-bit RSA私钥
$ openssl genrsa -out private_key.pem 2048
2. 导出RSA公钥
$ openssl rsa -in private_key.pem -pubout -out public_key.pem
3. 将公私钥文件private_key.pem和public_key.pem的头尾注释去掉
即:
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
4. 读取公私钥文件内容
// filePath即为private_key.pem和public_key.pem
public static String getKeyFromFile(String filePath) throws Exception {
File file = new File(filePath);
InputStream ins = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(ins));
String readLine = null;
StringBuffer sb = new StringBuffer();
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
}
br.close();
ins.close();
return new String(sb);
}
5. 读取私钥
public static PrivateKey getPrivateKey(String privateKey) throws Exception {
// 解码由base64编码的私钥
byte[] keyBytes = decryptBASE64(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取得私钥
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
return priKey;
}
6. 读取公钥
public static PublicKey getPublicKey(String publicKeyStr) throws Exception {
// 解码由base64编码的公钥
byte[] keyBytes = decryptBASE64(publicKeyStr);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
return publicKey;
}