I created public.der and private.der using openssl. I need to hard code the generated public key into code rather than reading that key from public.der file. When I read key from file into byte[] and printing that byte array gives me output like "[B@74a14482". I can run program by reading key from file but it is taking time for execution so I want to hard code key directly into program.
I have the following function
public PublicKey readPublicKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, URISyntaxException {
String str = "[B@74a14482";
byte[] b = str.getBytes();
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(b);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(publicSpec);
}
but it is giving me error as
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: Detect premature EOF
I referred to this and run but I got the same error.
Code which prints the byte array:
public byte[] readFileBytes(String filename) throws IOException, URISyntaxException {
return ByteStreams.toByteArray(ResourceLoader.loadFile(filename));
}
public PublicKey readPublicKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, URISyntaxException {
System.out.println(readFileBytes(filename));
String str = "[B@74a14482";
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(str);
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(publicSpec);
}
Can you please help me with this. Where I m going wrong.
As pointed by @michalk, what you print is the result of the toString() method applied on the byte array. This method does not print the content of the array.
Another problem is that not all bytes can be converted to printable characters.
I would recommend to encore the key with Base64, this will give you a printable version of your key. Then you can decode this String it before using it.
byte [] keyBytes = readFileBytes(filename);
String keyString = Base64.getEncoder().encodeToString(key);
System.out.println(keyString);
byte[] keyBytes = Base64.getDecoder().decode(keyString);
(instead of keyBytes = (new BASE64Decoder()).decodeBuffer(str);)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With