如何将 DER DSA 私钥读取到充气城堡中的 AsymmetricKeyParameter (Java)

How to read DER DSA private key to AsymmetricKeyParameter in bouncy castle (Java)

如何将带有 DSA 私钥(4096 位)的 DER 文件读入 AsymmetricKeyParameter 以便在 DSASigner 中使用?

我尝试了以下代码:

 byte[] privateKeyBytes = FileUtils.readFileToByteArray(new File(
                    "sign-key-private.der"));
 AsymmetricKeyParameter privateKey = PrivateKeyFactory
                    .createKey(privateKeyBytes);

结果异常:

java.lang.IllegalArgumentException: unknown object in getInstance: org.bouncycastle.asn1.ASN1Integer
    at org.bouncycastle.asn1.ASN1Sequence.getInstance(Unknown Source)
    at org.bouncycastle.asn1.x509.AlgorithmIdentifier.getInstance(Unknown Source)
    at org.bouncycastle.asn1.pkcs.PrivateKeyInfo.<init>(Unknown Source)
    at org.bouncycastle.asn1.pkcs.PrivateKeyInfo.getInstance(Unknown Source)
    at org.bouncycastle.crypto.util.PrivateKeyFactory.createKey(Unknown Source)
    at test.security.core.Program.main(Program.java:41)

我最终使用的解决方法是将密钥转换为 PEM 格式并使用以下内容:

 @Cleanup
 FileReader privateKeyReader = new FileReader(new File("key.pem"));
 @Cleanup
 PEMParser parser = new PEMParser(privateKeyReader);

 PEMKeyPair keyPair = (PEMKeyPair) parser.readObject();
 AsymmetricKeyParameter privateKey = PrivateKeyFactory
     .createKey(keyPair.getPrivateKeyInfo());
 AsymmetricKeyParameter publicKey = PublicKeyFactory
     .createKey(keyPair.getPublicKeyInfo());
byte[] privateKeyBytes = FileUtils.readFileToByteArray(new File("sign-key-private.der"));
KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
RSAPrivateKey rsaKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
AsymmetricKeyParameter privateKeyParameter = new RSAKeyParameters(true, rsaKey.getModulus(), rsaKey.getPrivateExponent());