简体   繁体   English

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

[英]Importing PEM encrypted key pair in java using bouncycastle

I'm writing a program that uses RSA for various tasks.我正在编写一个使用 RSA 执行各种任务的程序。
I know how to generate and write the key pair to file, but I cannot load the encrypted (AES-256-CFB) key pair to a KeyPair object.我知道如何生成密钥对并将其写入文件,但我无法将加密的 (AES-256-CFB) 密钥对加载到 KeyPair 对象。

So the question is: how do I load/decrypt an encrypted PEM key pair as a java.security.KeyPair object using the BouncyCastle library?所以问题是:如何使用 BouncyCastle 库将加密的 PEM 密钥对加载/解密为 java.security.KeyPair 对象?

Thanks.谢谢。

Generation/export code:生成/导出代码:

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

I am assuming that you have set BouncyCastle as the security provider, for example with:我假设您已将 BouncyCastle 设置为安全提供者,例如:

Security.addProvider(new BouncyCastleProvider());

The code you provided creates two key files, one for the private key and one for the public key.您提供的代码创建了两个密钥文件,一个用于私钥,一个用于公钥。 However, the public key is implicitly contained in the private key, so we only have to read the private key file to reconstruct the key pair.但是,公钥隐含在私钥中,因此我们只需读取私钥文件即可重构密钥对。

The main steps then are:然后主要步骤是:

  • Creating a PEMParser to read from the key file.创建一个PEMParser以从密钥文件中读取。

  • Create a JcePEMDecryptorProvider with the passphrase required to decrypt the key.使用解密密钥所需的密码创建一个JcePEMDecryptorProvider

  • Create a JcaPEMKeyConverter to convert the decrypted key to a KeyPair .创建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());
}

Example usage:用法示例:

File privKeyFile = new File("priv.pem");
String passphrase = "abc";

try {
  KeyPair keyPair = loadEncryptedKeyPair(privKeyFile, passphrase);
} catch (IOException ex) {
  System.err.println(ex);
}

Reference: BouncyCastle unit test for key parsing ( link ).参考:用于密钥解析的 BouncyCastle 单元测试( 链接)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 AWS SDK 为 Java 创建密钥对时创建包含私钥的 file.pem - create a file.pem containing the private key when creating a Key Pair using AWS SDK for Java 从Java BouncyCastle输出加密的PK8私钥 - Outputting encrypted PK8 private key from Java BouncyCastle 使用 bouncycastle 从 CMS 封装数据中提取加密的 session 密钥 - Extract encrypted session key from CMS Enveloped data using bouncycastle 在 Java 中加载加密的 PCKS8 PEM 私钥 - Load an Encrypted PCKS8 PEM Private Key In Java 创建密钥对证书并使用BouncyCastle与外部CA签名 - Creating a Key Pair Certificate and Signing It with External CA using BouncyCastle 使用PEM编码的加密私钥本地签名消息 - Using a PEM encoded, encrypted private key to sign a message natively 使用 BouncyCastle 从 PEM Key 获取 KeyPair - Get KeyPair from PEM Key with BouncyCastle 使用 bouncycastle/spongycastle 读取加密的私钥 - Read an encrypted private key with bouncycastle/spongycastle 使用 Bouncycastle 加载加密私钥时出现 InvalidAlgorithmParameterException - InvalidAlgorithmParameterException When Loading Encrypted Private Key With Bouncycastle 如何使用BouncyCastle通过Java中的PEMParser读取没有BEGIN和END的PEM证书 - How to read a PEM certificate without BEGIN and END via PEMParser in Java using BouncyCastle
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM