简体   繁体   中英

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

How to read DER file with private DSA key (4096 bit) into AsymmetricKeyParameter for usage in DSASigner ?

The following code I tried:

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

Result is an exception:

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)

The workaround solution I have finally used was to convert key to PEM format and use the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM