使用bouncycastle在java中导入PEM加密密钥对



我正在编写一个使用RSA完成各种任务的程序。
我知道如何生成密钥对并将其写入文件,但我无法将加密的(AES-256-CFB)密钥对加载到KeyPair对象。

所以问题是:我如何加载/解密加密的PEM密钥对作为java.security.KeyPair对象使用BouncyCastle库?

谢谢。

代/导出代码:

public void generateKeyPair(int keysize, File publicKeyFile, File privateKeyFile, String passphrase) throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    SecureRandom random = new SecureRandom();
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");
    generator.initialize(keysize, random);
    KeyPair pair = generator.generateKeyPair();
    Key pubKey = pair.getPublic();
    PEMWriter pubWriter = new PEMWriter(new FileWriter(publicKeyFile));
    pubWriter.writeObject(pubKey);
    pubWriter.close();
    PEMWriter privWriter = new PEMWriter(new FileWriter(privateKeyFile));
    if (passphrase == null) {
        privWriter.writeObject(pair);
    } else {
        PEMEncryptor penc = (new JcePEMEncryptorBuilder("AES-256-CFB"))
                .build(passphrase.toCharArray());
        privWriter.writeObject(pair, penc);
    }
    privWriter.close();
}

我假设您已将BouncyCastle设置为安全提供者,例如:

Security.addProvider(new BouncyCastleProvider());

您提供的代码创建了两个密钥文件,一个用于私钥,一个用于公钥。但是,公钥隐式地包含在私钥中,因此我们只需要读取私钥文件来重建密钥对。

主要步骤如下:

  • 创建PEMParser读取密钥文件

  • 创建包含解密密钥所需口令的JcePEMDecryptorProvider

  • 创建JcaPEMKeyConverter,将解密后的密钥转换为KeyPair

KeyPair loadEncryptedKeyPair(File privateKeyFile, String passphrase)
      throws FileNotFoundException, IOException {
  FileReader reader = new FileReader(privateKeyFile);
  PEMParser parser = new PEMParser(reader);
  Object o = parser.readObject();
  if (o == null) {
    throw new IllegalArgumentException(
        "Failed to read PEM object from file!");
  }
  JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
  if (o instanceof PEMKeyPair) {
    PEMKeyPair keyPair = (PEMKeyPair)o;
    return converter.getKeyPair(keyPair);
  }
  if (o instanceof PEMEncryptedKeyPair) {
    PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair)o;
    PEMDecryptorProvider decryptor =
        new JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray());
    return converter.getKeyPair(encryptedKeyPair.decryptKeyPair(decryptor));
  }
  throw new IllegalArgumentException("Invalid object type: " + o.getClass());
}

使用例子:

File privKeyFile = new File("priv.pem");
String passphrase = "abc";
try {
  KeyPair keyPair = loadEncryptedKeyPair(privKeyFile, passphrase);
} catch (IOException ex) {
  System.err.println(ex);
}

参考:BouncyCastle单元测试键解析(链接)

最新更新