Node.js和WebCrypto之间的ECDSA签名似乎不兼容?

时间:2016-09-18 04:39:02

标签: node.js cryptography ecdsa webcryptoapi

我使用以下示例在Node.js中进行签名+验证:https://github.com/nodejs/node-v0.x-archive/issues/6904。验证在Node.js中成功,但在WebCrypto中失败。同样,使用WebCrypto签名的消息无法在Node.js中进行验证。

这是我用来验证使用WebCrypto - https://jsfiddle.net/aj49e8sj/从Node.js脚本生成的签名的代码。已在Chrome 54.0.2840.27和Firefox 48.0.2中进行了测试

// From https://github.com/nodejs/node-v0.x-archive/issues/6904
var keys = {
  priv: '-----BEGIN EC PRIVATE KEY-----\n' +
        'MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49\n' +
        'AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2\n' +
        'pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n' +
        '-----END EC PRIVATE KEY-----\n',
  pub: '-----BEGIN PUBLIC KEY-----\n' +
       'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNh\n' +
       'B8i3mXyIMq704m2m52FdfKZ2pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n' +
       '-----END PUBLIC KEY-----\n'
};
var message = (new TextEncoder('UTF-8')).encode('hello');

// Algorithm used in Node.js script is ecdsa-with-SHA1, key generated with prime256v1
var algorithm = {
    name: 'ECDSA',
    namedCurve: 'P-256',
    hash: {
        name: 'SHA-1'
    }
};

// Signature from obtained via above Node.js script
var sig64 = 'MEUCIQDkAtiomagyHFi7dNfxMrzx/U0Gk/ZhmwCqaL3TimvlswIgPgeDqgZNqfR5/FZZASYsczUAhGSXjuycLhWnvk20qKc=';

// Decode base64 string into ArrayBuffer
var b64Decode = (str) => Uint8Array.from(atob(str), x => x.charCodeAt(0));

// Get base64 string from public key
const key64 = keys.pub.split('\n')
    .filter(x => x.length > 0 && !x.startsWith('-----'))
    .join('');

// Convert to buffers
var sig = b64Decode(sig64);
var keySpki = b64Decode(key64);

// Import and verify
// Want 'Verification result: true' but will get 'false'
var importKey = crypto.subtle.importKey('spki', keySpki, algorithm, true, ['verify'])
    .then(key => crypto.subtle.verify(algorithm, key, sig, message))
    .then(result => console.log('Verification result: ' + result));

使用SHA-256而不是SHA-1的类似问题的相关问题:Generating ECDSA signature with Node.js/crypto

我检查过的事情:

  • 我解码了Node.js密钥并验证它们与通过WebCrypto生成的密钥具有相同的OID。这告诉我,我正在使用正确的曲线。
  • SHA-1被明确标识为在两个位置使用的哈希。
  • 在Node.js和WebCrypto中明确标识了ECDSA。

如何成功验证从Node.js收到的签名,反之亦然 - 验证从WebCrypto生成的Node.js中的签名?或者标准的实现是否以某种方式略有不同,使它们不兼容?

编辑:

  • WebCrypto签名(64字节):uTaUWTfF + AjN3aPj0b5Z2d1HybUEpV / phv / P9RtfKaGXtcYnbgfO43IRg46rznG3 / WnWwJ2sV6mPOEnEPR0vWw ==
  • Node.js签名(71字节):MEUCIQDkAtiomagyHFi7dNfxMrzx / U0Gk / ZhmwCqaL3TimvlswIgPgeDqgZNqfR5 / FZZASYsczUAhGSXjuycLhWnvk20qKc =

已验证的Node.js签名是DER编码的,而WebCrypto签名则不是。

3 个答案:

答案 0 :(得分:3)

没有使用这些库中的任何一个我无法肯定地说,但有一种可能性是它们不会使用相同的编码类型进行签名。对于DSA / ECDSA,有两种主要格式,IEEE P1363(由Windows使用)和DER(由OpenSSL使用)。

" Windows"格式是具有预设大小(由Q表示DSA和P表示ECDSA(Windows不支持Char-2,但如果它确实如此,则可能是M表示Char-2 ECDSA))。然后,rs都会用0进行左边填充,直到达到该长度。

r = 0x305s = 0x810522的小于合法的例子中,sizeof(Q)为3个字节:

// r
000305
// s
810522

对于" OpenSSL"格式它根据DER的规则编码为SEQUENCE(INTEGER(r),INTEGER(s)),看起来像

// SEQUENCE
30
  // (length of payload)
  0A
  // INTEGER(r)
  02
    // (length of payload)
    02
    // note the leading 0x00 is omitted
    0305
  // INTEGER(s)
  02
    // (length of payload)
    04
    // Since INTEGER is a signed type, but this represented a positive number,
    // a 0x00 has to be inserted to keep the sign bit clear.
    00810522

或紧凑地:

  • Windows:000305810522
  • OpenSSL:300A02020305020400810522

" Windows"格式始终是偶数,总长度相同。 " OpenSSL"格式通常大约6个字节,但在中间可以获得或丢失一个字节;所以它有时甚至是奇怪的。

Base64解码您的sig64值表明它正在使用DER编码。使用WebCrypto生成几个签名;如果没有以0x30开头,那么您就会遇到IEEE / DER问题。

答案 1 :(得分:1)

几个小时后终于找到零依赖的解决方案!

在浏览器中:

      // Tip: Copy & Paste in the console for test.

      // Text to sign:
      var source = 'test';

      // Auxs
      function length(hex) {
        return ('00' + (hex.length / 2).toString(16)).slice(-2).toString();
      }

      function pubKeyToPEM(key) {
        var pem = '-----BEGIN PUBLIC KEY-----\n',
            keydata = '',
            bytes = new Uint8Array( key );

        for (var i = 0; i < bytes.byteLength; i++) {
          keydata += String.fromCharCode( bytes[ i ] );
        }

        keydata = window.btoa(keydata);

        while(keydata.length > 0) {
          pem += keydata.substring(0, 64) + '\n';
          keydata = keydata.substring(64);
        }

        pem = pem + "-----END PUBLIC KEY-----";

        return pem;
      }

      // Generate new keypair.
      window.crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-384" }, true, ["sign", "verify"])
            .then(function(keypair) {

              // Encode as UTF-8
              var enc = new TextEncoder('UTF-8'),
                  digest = enc.encode(source);
              
              // Sign with subtle
              window.crypto.subtle.sign({ name: "ECDSA", hash: {name: "SHA-1"} }, keypair.privateKey, digest)
                    .then(function(signature) {
                        signature = new Uint8Array(signature);

                        // Extract r & s and format it in ASN1 format.
                        var signHex = Array.prototype.map.call(signature, function(x) { return ('00' + x.toString(16)).slice(-2); }).join(''),
                            r = signHex.substring(0, 96),
                            s = signHex.substring(96),
                            rPre = true,
                            sPre = true;

                        while(r.indexOf('00') === 0) {
                          r = r.substring(2);
                          rPre = false;
                        }

                        if (rPre && parseInt(r.substring(0, 2), 16) > 127) {
                          r = '00' + r;
                        }

                        while(s.indexOf('00') === 0) {
                          s = s.substring(2);
                          sPre = false;
                        }

                        if(sPre && parseInt(s.substring(0, 2), 16) > 127) {
                          s = '00' + s;
                        }

                        var payload = '02' + length(r) + r +
                                      '02' + length(s) + s,
                            der = '30' + length(payload) + payload;
                        
                        // Export public key un PEM format (needed by node)
                        window.crypto.subtle.exportKey('spki', keypair.publicKey)
                                                   .then(function(key) {
                                                      var pubKey = pubKeyToPEM(key);
                                                      
                                                      console.log('This is pubKey -> ', pubKey);
                                                      console.log('This is signature -> ', der);                                                      
                                                   });
                                         
                        
                        // For test, we verify the signature, nothing, anecdotal.
                        window.crypto.subtle.verify({ name: "ECDSA", hash: {name: "SHA-1"} }, keypair.publicKey, signature, digest)
                              .then(console.log);
                    });
                    
            });

在节点中:

const crypto = require('crypto');

// ----------------------------------------------------------------------------

// Paste from browser!

var puKeyPem = '-----BEGIN PUBLIC KEY-----\n' +
               'MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEmDubwJuORpMMoMnvv59W8tU8PxPChh75\n' +
               'vjlfVB2+tPY5KDy1I0ohz2US+2K1T/ROcDCSRAjyONRzzwVBm9S6bqbk3KuaT2KG\n' +
               'ikoe0KLfTeQtdEUyq8J0aEOKRXoCJLZq\n' +
               '-----END PUBLIC KEY-----';
               
var hexSign = '306402305df22aa5f4e7200b7c264c891cd3a8c5b4622c25872020832d5bb3d251773592020249a46a8349754dc58c47c4cbb7c9023053b929a98f5c8cccf2c1a4746d82fc751e044b1f76dffdf9ef73f73bee1499c5e20aadddda41e3373760b8b0f3c1bbb2';

// ----------------------------------------------------------------------------

var verifier = crypto.createVerify('sha1'),
    digest   = 'test';
    
verifier.update(digest);
verifier.end();

console.log(verifier.verify(puKeyPem, hexSign, 'hex'));

// ----------------------------------------------------------------------------

答案 2 :(得分:0)

现在,您无需修改​​即可生成兼容的(nodejs与webcrypto)密钥和签名。以下示例适用于RSA,但ECDSA应该非常相似-本质在于类型/格式/编码。

生成密钥对(nodejs):

const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: 'spki',
    format: 'der'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'der'
  }
});
    
console.log('PRIVATE', Buffer.from(privateKey).toString('base64'));
console.log('PUBLIC', Buffer.from(publicKey).toString('base64'));

签名消息(nodejs):

const signature = crypto.sign(
  'sha256',
  Buffer.from('The quick brown fox jumps over the lazy dog', 'utf8'),
  {
    key: crypto.createPrivateKey({
      key: Buffer.from('...base64 encoded private key', 'base64'),
      format: 'der',
      type: 'pkcs8'
    }),
    padding: crypto.constants.RSA_PKCS1_PADDING,
    dsaEncoding: 'ieee-p1363'
  }
);

console.log('SIGNATURE', signature.toString('base64'));

验证消息(webcrypto)-您必须更改普通js中的Buffer函数

  (async () => console.log(await crypto.subtle.verify(
    { name: 'RSASSA-PKCS1-v1_5' },
    await crypto.subtle.importKey(
      'spki',
      Buffer.from('...base64 encoded public key', 'base64'),
      { name: 'RSASSA-PKCS1-v1_5', hash: {name: 'SHA-256'} },
      false,
      [ 'verify' ]
    ),
    Buffer.from('...base64 encoded signature', 'base64'),
    Buffer.from('The quick brown fox jumps over the lazy dog', 'utf8')
  )))();