PEMReader最新的使用方法



参考链接:http://bouncy-castle.1462172.n4.nabble.com/Problem-using-PEMReader-to-read-openssl-generated-private-key-td4382977.html

最近用到PEMReader,在官网下载最新的jar包之后,他的用法和以前不一样了,记录如下:  

新版:

  问题:

       final PemObject privatePemObject = new PEMReader(new
FileReader(new
File("/Users/edalquist/tmp/crypt/my.wisc.edu-private.pem"))).readPemObject();
         final PemObject publicPemObject = new PEMReader(new
FileReader(new
File("/Users/edalquist/tmp/crypt/my.wisc.edu-public.pem"))).readPemObject();

         final AsymmetricKeyParameter publicKey =
PublicKeyFactory.createKey(publicPemObject.getContent());
         final AsymmetricKeyParameter privateKey =
PrivateKeyFactory.createKey(privatePemObject.getContent());

The publicKey loads correctly but the privateKey fails with the
following stack trace:

java.lang.ClassCastException: org.bouncycastle.asn1.ASN1Integer cannot
be cast to org.bouncycastle.asn1.ASN1Sequence
     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
org.jasig.tokencrypt.TokenEncryptDecryptTest.testEncrypt(TokenEncryptDecryptTest.java:70)


回答:

An OpenSSL RSA private key is not encoded as a PrivateKeyInfo object,
it's just encoded as an RSAPrivateKey pkcs structure, without the
surrounding wrapper.

Under the current beta you could create the private key info as:

new PrivateKeyInfo(new
AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, new DERNull()),
RSAPrivateKey.getInstance(privatePemObject.getContent()));

You may need to use ASN1Object.fromByteArray() to convert the content in
earlier ones.



旧版:

import org.bouncycastle.openssl.PEMReader;

      //load client private key
      PEMReader mReader = new PEMReader(new InputStreamReader( new FileInputStream("/storage/qiyi-key.pem")));
      KeyPair mkey =(KeyPair) mReader.readObject();

      
      PrivateKey mPkey = (PrivateKey)mkey.getPrivateKey();


猜你喜欢

转载自blog.csdn.net/yhyqf/article/details/75336759