i'll try verify signature from opensll generate with command :
openssl pkeyutl -in mess.txt -out sign.txt -inkey priv.pem -sign
and my script:
const fs = require('fs');
const forge = require('node-forge');
function verifySignature(publicKeyPem, message, signatureFile) {
try {
const publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
const signatureBytes = fs.readFileSync(signatureFile,'binary');
const md = forge.md.sha256.create();
md.update(message);
const verified = publicKey.verify(md.digest().getBytes(), signatureBytes);
if (verified) {
console.log('Signature is valid. Message is authenticated.');
} else {
console.error('Signature is invalid. Message could not be authenticated.');
}
} catch (error) {
console.error('Error during signature verification:', error);
}
}
const publicKeyPem = fs.readFileSync('pub.pem', 'utf-8');
const messageToSign = fs.readFileSync('mess.txt', 'utf-8');
const signatureFile = 'sign.txt';
verifySignature(publicKeyPem, messageToSign, signatureFile);
Error: Too few bytes to read ASN.1 value.
how can i fix this issued
So that verification is successful, the message itself (and not the message hash) must be passed in the first parameter of
verify()and'NONE'must be specified as scheme in the third parameter (so that the default valueRSASSA-PKCS1-V1_5is not used), as in the following sample code (the signature was generated with your OpenSSL statement):With these changes, verification is successful.
Explanation:
The OpenSSL statement pads and signs the message directly and not the DER encoding of the DigestInfo value (consisting of the OID of the digest and the hash value of the message).
For this reason, the message to be verified must not be hashed in the JavaScript code. And
'NONE'specifies that the data determined from the signature represents the message itself and not the DER encoding of the DigestInfo value and is to be processed accordingly during verification.Comparison with RSASSA-PKCS1-v1_5:
Note that before padding and signing, the message is commonly hashed and the resulting hash is completed to the DER encoding of the DigestInfo value, as described in RFC8017.
Your OpenSSL statement deviates from this. If you want to adhere to the standard, the OpenSSL statement must be adapted.
Here are a few possibilities (using SHA256 as an example):
-pkeyopt digest:sha256to the OpenSSL statement:-rawin -digest sha256to the OpenSSL satement (from v3.0):With these changes, it is not required to adapt the JavaScript code.