EN
Node.js - encode text to md5
6 points
In this article, we would like to show how to calculate md5 sum for indicated text in Node.js.
Quick solution:
xxxxxxxxxx
1
const crypto = require('crypto'); // built-in node module
2
3
const text = 'Some input text ...';
4
const result = crypto.createHash('md5').update(text).digest('hex');
5
6
console.log(result); // ac57cdeee28c017e7afd39a579dab8fd
Node.js has a built-in crypto module that provides md5 sum implementation.
1.1. Reusable util
This section contains a simple function that with one call calculate md5 sum for the indicated text.
xxxxxxxxxx
1
const crypto = require('crypto');
2
3
const calculateMD5Sum = (text) => {
4
return crypto.createHash('md5').update(text).digest('hex');
5
};
6
7
8
// Usage example:
9
10
const text = 'dirask';
11
console.log(calculateMD5Sum(text)); // 47b3201569d2797c6e0432b71e3bb9e0
This approach lets to make calculations on small data parts. It is useful when we work on big files or stream data, reducing the amount of RAM that is needed to store data.
xxxxxxxxxx
1
const crypto = require('crypto');
2
3
const md5 = crypto.createHash('md5');
4
5
md5.update('d');
6
md5.update('ir');
7
md5.update('ask');
8
9
const sum = md5.digest('hex');
10
11
console.log(sum); // 47b3201569d2797c6e0432b71e3bb9e0
Simple steps:
1. install md5
module with the following command:
xxxxxxxxxx
1
npm install md5
2. run the following source code:
xxxxxxxxxx
1
const md5 = require('md5');
2
3
const text = 'dirask';
4
console.log(md5(data)); // 47b3201569d2797c6e0432b71e3bb9e0