Quantcast
Channel: chris-rock
Viewing all articles
Browse latest Browse all 33

SHA 512 Hashs with nodejs

$
0
0

Quite often you need to encrypt files. Recently I updated an application from encryption to authenticated encryption and used the encrypt-then-mac approach.

Update: I created a node module that simplifies the process for you: password-hasher

To create a hash from strings you just need a few lines in nodejs:

// generate a hash from stringvar crypto = require('crypto'),
        text = 'hello bob',
        key = 'mysecret key'// create hahsvar hash = crypto.createHmac('sha512', key)
    hash.update(text)
    var value = hash.digest('hex')

    // print result
    console.log(value);

The great thing about the nodejs implementation of Hash is the possibility to stream data directly into the hash:

// generate a hash from file streamvar crypto = require('crypto'),
        fs = require('fs'),
        key = 'mysecret key'// open file streamvar fstream = fs.createReadStream('./test/hmac.js');
    var hash = crypto.createHash('sha512', key);
    hash.setEncoding('hex');

    // once the stream is done, we read the values
    fstream.on('end', function() {
        hash.end();
        // print result
        console.log(hash.read());
    });

    // pipe file to hash generator
    fstream.pipe(hash);

Happy Hashing.

If you have any questions contact me via Twitter @chri_hartmann or Github

See also:


Viewing all articles
Browse latest Browse all 33

Trending Articles