Java RSA私钥的格式pkcs1和pkcs8、PrivateKey转换

()一、私钥格式

(1)pkcs1

格式:

-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----

(2)pkcs8

格式:

-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----

pkcs1私钥生成openssl genrsa -out pkcs1.pem 1024

pkcs1转pkcs8私钥 :openssl pkcs8 -in pkcs8.pem -nocrypt -out pkcs1.pem

二、私钥java代码转换

       <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.52</version>
        </dependency>

(1)pkcs1 to pkcs8

        byte[] encodeByte = Base64.decodeBase64(pkcs1Base64);
        AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag); 
        ASN1Object asn1Object = ASN1ObjectIdentifier.fromByteArray(encodeByte);
        PrivateKeyInfo privKeyInfo = new PrivateKeyInfo(algorithmIdentifier, asn1Object);
        byte[] pkcs8Bytes = privKeyInfo.getEncoded();

(2) pkcs8 to pkcs1

        byte[] encodeByte = Base64.decodeBase64(pkcs8Base64);
        //pkcs8Bytes 
        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(encodeByte);
        RSAPrivateKey pkcs1Key = RSAPrivateKey.getInstance(pki.parsePrivateKey());
        byte[] pkcs1Bytes = pkcs1Key.getEncoded();

三、 转PrivateKey

(1) pkcs1 to PrivateKey对象

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(keyBase64));
DerValue[] seq = derReader.getSequence(0);
BigInteger modulus = seq[1].getBigInteger();
BigInteger publicExp = seq[2].getBigInteger();
BigInteger privateExp = seq[3].getBigInteger();
BigInteger prime1 = seq[4].getBigInteger();
BigInteger prime2 = seq[5].getBigInteger();
BigInteger exp1 = seq[6].getBigInteger();
BigInteger exp2 = seq[7].getBigInteger();
BigInteger crtCoef = seq[8].getBigInteger();
RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

(2) pkcs8 to PrivateKey对象

byte[] key64 = Base64.decodeBase64(privateKey.getBytes()); 
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); 
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);