Java导入OpenSSL生成的公私钥文件

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值