I'am trying to generate signatures from files, in order to verify them by clients using OpenSSL, so to implement the corresponding openSSL command in Java using Bouncy Castle :
openssl.exe dgst -sha256 -sign privateKey.pem -out \data.txt.sig \data.txt
using bouncy castle 1.57 and java, we get bytes array signature from file, which i could verify it in the code. Private, public and certificate are generated from openSSL.
so to generate certificates :
read the private key from the pem private key file:
PEMParser pemParser = new PEMParser(new FileReader(PRIVATE_FILE_PATH));
PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemParser.readObject();
JceOpenSSLPKCS8DecryptorProviderBuilder jce = new JceOpenSSLPKCS8DecryptorProviderBuilder();
jce.setProvider("BC");
InputDecryptorProvider decProv = jce.build(password.toCharArray());
PrivateKeyInfo info = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(decProv);
JcaPEMKeyConverter pemKeyConverter = new JcaPEMKeyConverter();
PrivateKey pk = pemKeyConverter.getPrivateKey(info);
and generate the RSA SHA 256 signature and write the result in the signature file:
byte[] data = Files.readAllBytes(Paths.get(txtFileToSignPath));
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(pk);
sig.update(data);
byte[] signature = sig.sign();
FileOutputStream dfis = new FileOutputStream(SignaturefilePath);
dfis.write(bytesToWrite);
dfis.close();
programmatically i could verify signatures generated from the code above as well as from open SSL:
Signature verifySignature = Signature.getInstance("SHA256withRSA");
byte[] signatureBytes =
Files.readAllBytes(Paths.get(SignaturefilePath);
verifySignature.initVerify(getPublicKeyFromCertFile(CERT_PEM));
verifySignature.update(data);
verifySignature.verify(signatureBytes);
on the other hand openSSL is getting always "verification failure" by verifiying signatures generated from code.
is OpenSSL able to verify array of bytes signatures directly, or am I missing anything ?
code above works fine, was verifying the signature against another file. Question maitained for learning purpose.