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.