[openssl-users] Java Snippet output is not equal to command line openssl command output , Why ?

timmy pony tim.fortinbras at gmail.com
Wed Aug 1 08:24:38 UTC 2018


Hi,

Could some openssl expert please advise  ?

Trying to get the equivalent Openssl command-line version of the following
java snippet.

I have tried this  openssl dgst -sha256 -sign my_private.key -out
/tmp/sign.sha256 codeTosign.txt

But the  the results do not match ?

```
From: "tim.fortinbras" <tim.fortinbras at gmail.com>
To: openssl-users at openssl.org
Cc:
Bcc:
Date: Tue, 31 Jul 2018 06:48:59 -0700 (MST)
Subject: Looking for exact openssl commands to do the following from
command line ?
import java.security.KeyFactory;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class SHA256RSA {

    public static void main(String[] args) throws Exception {
        String input = "sample input";

        // Not a real private key! Replace with your private key!
        String strPk = "-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9"
                + "w0BAQEFAASCBKkwggSlAgEAAoIBAQDJUGqaRB11KjxQ\nKHDeG"
                + "........................................................"
                + "Ldt0hAPNl4QKYWCfJm\nNf7Afqaa/RZq0+y/36v83NGENQ==\n"
                + "-----END PRIVATE KEY-----\n";

        String base64Signature = signSHA256RSA(input,strPk);
        System.out.println("Signature="+base64Signature);
    }

    // Create base64 encoded signature using SHA256/RSA.
    private static String signSHA256RSA(String input, String strPk) throws
Exception {
        // Remove markers and new line characters in private key
        String realPK = strPk.replaceAll("-----END PRIVATE KEY-----", "")
                             .replaceAll("-----BEGIN PRIVATE KEY-----", "")
                             .replaceAll("\n", "");

        byte[] b1 = Base64.getDecoder().decode(realPK);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(b1);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        Signature privateSignature = Signature.getInstance("SHA256withRSA");
        privateSignature.initSign(kf.generatePrivate(spec));
        privateSignature.update(input.getBytes("UTF-8"));
        byte[] s = privateSignature.sign();
        return Base64.getEncoder().encodeToString(s);
    }
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mta.openssl.org/pipermail/openssl-users/attachments/20180801/136dbfa5/attachment.html>


More information about the openssl-users mailing list