Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Front-end performed RSA signature on the HMAC using SHA256, but the length was incorrect, causing the server to fail to verify it. #293

Open
stdzwei opened this issue Apr 20, 2023 · 1 comment

Comments

@stdzwei
Copy link

stdzwei commented Apr 20, 2023

My Code

rawGenerateEncryptData(rsa, obj, function sign(hmac) {
  let rsa = new JSEncrypt()
  rsa.setPrivateKey(privateKey)
  return rsa.sign(hmac, CryptoJS.SHA256, "sha256");
})

Where the error occurred

 RSAKey.prototype.sign = function (text, digestMethod, digestName) {
    // ....
    var h = c.toString(16);
    if ((h.length & 1) == 0) {
        return h;
    }
    else {
        return "0" + h;
   }
}

The cause of the problem:
The digestName is SHA-256, but the length of h may not be 512. If you use the operator &, it will not append 0 to the start of the string when the length is 510, but SHA-256 requires 256. Additionally, 510 >> 1 is 255.

Fix it

if(digestName === 'sha256' && (h.length >> 1) != 256){
  const arr = []
  for (let i = 0; i < ((256 << 1) - h.length); i++) {
    arr.push('0')
  }
  return arr.join('') + h;
} else if ((h.length & 1) == 0) {
  return h;
} else {
  return "0" + h;
}
@ChenHanHui
Copy link

Yes, I had this problem too. It happened by accident.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants