1

I currently have a public/private key pair in as two separate strings that I am trying to convert back into public/private key format.

I am currently reading in the string from a .auth file, not a public key file and private key file so I can't use openssl pkcs8 -topk8... to get rid of the algid parse error. I am reading in the keys like so:

BufferedReader br = new BufferedReader(new FileReader(authFileName));
String publicK = br.readLine();
String privateK = br.readLine();
br.close();

From there, I am converting the files back into byte arrays like so using the Base64 Decoder like so:

byte[] privateBytes = Base64.getDecoder().decode(privateK);
byte[] publicBytes = Base64.getDecoder().decode(publicK);

Lastly I am converting those byte arrays into Public and Private keys using a key factory. Here is the code:

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateBytes));
PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicBytes));

When my code tries to generate the private and public keys using the key factory, that is when it throws the InvalidKeyException algid parse error

I have looked online and noticed many people saying adding the following line to my code should fix the problem:

Security.addProvider(new BouncyCastleProvider());

But it didn't. Is there any other solution, besides bouncy castle and openssl, that I should try that worked for anyone else?

Community
  • 1
  • 1
user1842633
  • 305
  • 1
  • 4
  • 15
  • What format are these key values? Are they PKCS8 and X.509 SPKI? The Java type for `PKCS8` only works for PKCS8 and the Java type for `X509` only works for X.509, with or without BouncyCastle provider; that's why they are named `PKCS8` and `X509`. If they are something else, you need to explain what that something else is. _Some_ other things can be handled by _other_ BC APIs _not_ the provider API, as in the question you link. – dave_thompson_085 Dec 09 '16 at 02:39
  • Is there a way to tell? To create these keys I'm just using the KeyPairGenerator in Java – user1842633 Dec 09 '16 at 03:14
  • `KeyPairGenerator` creates only internal objects. If you are then doing `.getPublic(),.getPrivate()` and `.getEncoded()`, those should indeed by X509SPKI and PKCS8 encodings, at least in desktop Java (I don't know for Android). Try printing the length and first 15-20 bytes _before_ base64 and store, and again after read and unbase64, and check they're the same. If that doesn't help, post a hex dump of your public key and say the first 20 bytes of your private key (that should be enough to see format without exposing your actual key). – dave_thompson_085 Dec 09 '16 at 21:35

0 Answers0