Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hard coding public key in code Rather than picking it from public.der

Tags:

java-8

rsa

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.

like image 305
Maddy8381 Avatar asked Jan 20 '26 03:01

Maddy8381


1 Answers

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.

To print the content of the file

byte [] keyBytes = readFileBytes(filename);
String keyString = Base64.getEncoder().encodeToString(key);
System.out.println(keyString);

To decode the key from a String

byte[] keyBytes = Base64.getDecoder().decode(keyString);

(instead of keyBytes = (new BASE64Decoder()).decodeBuffer(str);)

like image 181
Benoit Avatar answered Jan 22 '26 01:01

Benoit