Node JS crypto, cannot create hmac on chars with accents

前端 未结 1 831
时光说笑
时光说笑 2021-01-04 08:08

I am having an issue generating the correct signature in NodeJS (using crypto.js) when the text I am trying to encrypt has accented characters (such as ä,ï,ë)



        
相关标签:
1条回答
  • 2021-01-04 08:43

    The default encoding used by the crypto module is usually 'binary'. So, you'll have to specify 'utf-8' via a Buffer to use it as the encoding:

    var sig = hmac.update(new Buffer(str, 'utf-8')).digest('hex');
    

    That's what the answer for the other question was demonstrating, just for the key:

    var hmac = crypto.createHmac('sha1', new Buffer(secKey, 'utf-8'));
    

    You can also use Buffer to view the differences:

    new Buffer('äïë', 'binary')
    // <Buffer e4 ef eb>
    
    new Buffer('äïë', 'utf-8')
    // <Buffer c3 a4 c3 af c3 ab>
    

    [Edit]

    Running the example code you provided, I get:

    Sig:      094b2ba039775bbf970a58e4a0a61b248953d30b
    Expected: 094b2ba039775bbf970a58e4a0a61b248953d30b
    

    And, modifying it slightly, I get true:

    var crypto = require('crypto');
    
    function sig(str, key) {
      return crypto.createHmac('sha1', key)
        .update(new Buffer(str, 'utf-8'))
        .digest('hex');
    }
    
    console.log(sig('äïë', 'secret') === '094b2ba039775bbf970a58e4a0a61b248953d30b');
    
    0 讨论(0)
提交回复
热议问题