Answering my own question:
Thanks to @bestbeforetoday's comment, I managed to rewrite the signing code and now it looks like this, for anyone having the same problem as I had:
function getPrivKey(pemFile) {
const pemContent = fs.readFileSync(pemFile, 'utf8');
const key = crypto.createPrivateKey(pemContent);
const jwk = key.export({ format: 'jwk' });
const d = jwk.d;
return Buffer.from(d, 'base64url');
}
function fabricSign(message, privateKeyPemFile) {
const privateKeyBytes = getPrivKey(privateKeyPemFile);
const msgHash = crypto.createHash('sha256').update(message).digest();
const signature = p256.sign(msgHash, privateKeyBytes);
const signaturep1 = signature.normalizeS();
const signaturep2 = signaturep1.toDERRawBytes();
return signaturep2;
}