简体   繁体   中英

RSA signature in JavaScript

I am new to encryption. I would like to sign a piece of data using a JavaScript RSA library before sending it to the server.

I am trying to use the JavaScript library jsrsasign: http://kjur.github.io/jsrsasign/ to sign the data.

I have generated a modulus (n), public exponent (e) and a private exponent (d) and trying to them to sign the data.

var privateExponent = "4B48F60D02460811DABF74D79770E8DD72B5EEFF1324F651D4543D98B8C9F0F7ED3E245C49D967A30B279564AFF4FE53E2D92704FB4D6E923732F4AF8CFDA2114A49B6E425FD44AEACB80F00125AF6468F1A666EDDD5CFD6BFAB27950EF3DFB78671734BF1BB782CBB654A7FBB9BFB897E37F0324710360E1515B1FF0EE7FAF1";

var modulus = "00A68A945DE1175E4EBA23C53B8A1237CE9AA292020ECB373D90837FBD8DB8164687B7913543EA838E2B669BD1626FA9872397C5398485D951CFC229E102A78654B61E9EB2BC3B36BD2624ACF5C8B82ABD33A5AF4144C55034A3E5BF8282F3D5CB0CF9F550844E68A58DADC3BCC7CF726F227F8EC5FAC2494F1FBDEEF39212B5FF";

var publicExponent = "10001";

I have been trying to use them to sign a piece of the data as follows:

var signature = "Hello world";
var rsa = new RSAKey();
rsa.setPrivate(modulus, publicExponent, privateExponent);

var result = rsa.signString(signature, 'sha256');
rsa.setPublic(modulus, publicExponent);

console.log(result);
console.log(rsa.verifyString(result, 'sha256'));

However the verify function keeps returning false. I have no idea what I am doing wrong.

The functions setPublic and setPrivate are part rsa2.js

There is an error in the verifyString call. The API says:

verifyString(sMsg, hSig)
  verifies a sigature for a message string with RSA public key.
  Parameters:
    {String} sMsg
        message string to be verified.
    {String} hSig
        hexadecimal string of siganture.
        non-hexadecimal charactors including new lines will be ignored.

    Returns:
        returns 1 if valid, otherwise 0

It means that the code you need to call is:

rsa.verifyString(signature, result)

However the variable names are confusing. The result var is actually the signature.

signString function is using PCSK#1 v1.5 padding therefore you do not need to pass the digest algorithm to the verify function. This information is already present in the signature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM