How to convert a PKCS#8 encoded RSA key into PKCS#1 in Java?
Asked Answered
D

3

6

Is it possible to convert a PKCS#8 encoded RSA private key into PKCS#1? I know this can be done easily via openssl, but can it be done in Java?

Demagoguery answered 11/3, 2011 at 9:34 Comment(1)
take a look at bouncy castle bouncycastle.orgDame
S
4

Use BouncyCastle 1.50

PrivateKeyInfo pkInfo = PrivateKeyInfo.getInstance(pkPair.getPrivateKey().getEncodedKey());
ASN1Encodable privateKeyPKCS1ASN1Encodable = pkInfo.parsePrivateKey();
ASN1Primitive privateKeyPKCS1ASN1 = privateKeyPKCS1ASN1Encodable.toASN1Primitive();

byte[] privateKeyPKCS1 = privateKeyPKCS1ASN1.getEncoded();
Spencerianism answered 7/9, 2016 at 6:50 Comment(0)
P
3

Use KeyFactory with PKCS8EncodedKeySpec (algorithm "RSA") to convert the PKCS #8 encoded private key bytes into Java objects.

Use Cipher and SecretKeyFactory (algorithm "PBEWithMD5AndDES") with PBEKeySpec, and PBEParameterSpec to create PKCS #5 encoded stuff.

Pterous answered 23/3, 2011 at 15:36 Comment(0)
E
0

also use BouncyCastle

 public static String convertPkcs8To1(String content, String privateKey, String charset) throws Exception {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey priKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey.getBytes())));
    PrivateKeyInfo pkInfo = PrivateKeyInfo.getInstance(priKey.getEncoded());
    ASN1Encodable privateKeyPKCS1ASN1Encodable = pkInfo.parsePrivateKey();
    ASN1Primitive privateKeyPKCS1ASN1 = privateKeyPKCS1ASN1Encodable.toASN1Primitive();

    byte[] privateKeyPKCS1 = privateKeyPKCS1ASN1.getEncoded();

    System.out.println(Base64.encodeBase64String(privateKeyPKCS1));
}
Eviaevict answered 23/6 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.