Search code examples
javaopenssldigital-signatureverify

Java verify digital signature in openssl


Using this tutorial, I created a Java program what can sign a document with SHA256withRSA algorithm. In the output I get a public key and a signature file.

I try to verify my file with openssl, but I can't... I was searching on the net and I found that I need to have a standard .pem key maybe, so my question is: How can I convert my key to pem format? Or can I generate a .pem key in Java? And if it's a wrong way, how can I verify my signature?


Solution

  • A PEM file contains the public key binary data encoded in base64 and splitted in lines of 64 characters. The file has also the header -----BEGIN PUBLIC KEY----- and the footer -----END PUBLIC KEY-----

    Java has not a native converter to PEM but you can use bouncycastle

    PEMWriter pemWriter = new PEMWriter(new FileWriter(file));
    pemWriter.writeObject(publicKey);
    pemWriter.flush();
    pemWriter.close();
    

    Alternatively you can verify a signature with openssl using a binary key format using

      -keyform DER
    

    Then save the content of your publicKey in a file

     byte publicKeyDer[] = publicKey.getEncoded()