How to use the createHash function from crypto

Find comprehensive JavaScript crypto.createHash code examples handpicked from public code repositorys.

crypto.createHash is a Node.js method that creates a Hash object, which is used to generate a cryptographic hash of the provided data.

4
5
6
7
8
9
10
11
12
13
const { getCookies, saveCookies } = require('../../../utils/util')

const app_key = 'bca7e84c2d947ac6'
var calc_sign = (params) => {
  let str = `${params}60698ba2f68e01ce44738920a0ffe768`
  return crypto.createHash('md5').update(str).digest('hex');
}
var transParams = (data) => {
  let params = new URLSearchParams();
  for (let item in data) {
fork icon640
star icon209
watch icon12

+ 3 other calls in file

98
99
100
101
102
103
104
105
106
107
108
109
    return hmac.digest('base64');
};


// get md5
exports.getMd5 = function (data) {
    var md5 = crypto.createHash('md5');
    return md5.update(data).digest('hex');
};


// 创建 AccessToken 凭证
fork icon189
star icon577
watch icon38

How does crypto.createHash work?

crypto.createHash is a method in Node.js that creates a hash object that can be used to generate hash digests of data using various algorithms such as MD5, SHA-1, SHA-256, etc. When creating a hash object using crypto.createHash, you can pass in the algorithm you want to use as a parameter, and then call the update method to update the hash with data to be hashed. Finally, calling the digest method returns the final hash digest.

299
300
301
302
303
304
305
306
307
308
if(files[i].path.indexOf("#") > -1) {
  // console.log("skipping file '"+files[i].path+"' (path contains #)");
  this.log_exclusion("path contains #");
  continue;
}
const curr_key = crypto.createHash("md5").update(files[i].path).digest("hex");
// skip if file already has embedding and embedding.mtime is greater than or equal to file.mtime
if((this.embeddings[curr_key]) && (this.embeddings[curr_key].meta.mtime >= files[i].stat.mtime)) {
  // log skipping file
  //console.log("skipping file (mtime)");
fork icon21
star icon263
watch icon7

+ 31 other calls in file

Ai Example

1
2
3
4
5
6
const crypto = require("crypto");

const message = "This is a secret message";
const hash = crypto.createHash("sha256").update(message).digest("hex");

console.log(hash); // output: 63f63b59a0b25dcb2b6dd63b56c2d00f127e7c71e6d8b7f83d2693d3c855b3a3

In this example, we first import the crypto module. We then create a string variable message containing our message to be hashed. We then call crypto.createHash('sha256') to create a SHA-256 hash object. We can specify different hash algorithms by passing a different string argument to createHash. We then call .update(message) to add the message to the hash object. We could call .update multiple times to add additional data to the hash, but in this case we're just adding the message once. Finally, we call .digest('hex') to compute the hash and return it as a hexadecimal string. The hash is stored in the hash variable and is logged to the console.

689
690
691
692
693
694
695
696
697
698
699
700
    })
}


const getFileHash = (path, hashName) => {
    return new Promise((resolve, reject) => {
        const hash = crypto.createHash(hashName.toLowerCase())
        const stream = fs.createReadStream(pathModule.normalize(normalizeRNFilePath(path)))


        stream.on("error", reject)
        stream.on("data", (chunk) => hash.update(chunk))
fork icon24
star icon118
watch icon8

45
46
47
48
49
50
51
52
53
54
  ...data
};

const keys = Object.keys(newData).filter(key => newData[key] !== '').sort();
const signData = keys.map(key => `${key}=${newData[key]}`).join('&');
const sign = crypto.createHash('md5').update(`${signData}&key=${SIGN_KEY}`).digest('hex').toUpperCase();

return {
  ...newData,
  sign
fork icon22
star icon130
watch icon1

+ 2 other calls in file

917
918
919
920
921
922
923
924
925
926
if (!('out' in argv)) {
  fd = fs.openSync(argv.inBin, 'r+')
  size = fs.fstatSync(fd).size
  const bin = Buffer.alloc(size)
  fs.readSync(fd, bin, 0, size)
  digest = crypto.createHash('sha256').update(bin).digest()
} else {
  fd = fs.readFileSync(argv.inBin)
  size = fd.length
  digest = crypto.createHash('sha256').update(fd).digest()
fork icon19
star icon68
watch icon12

+ 7 other calls in file

74
75
76
77
78
79
80
81
82
83
const ParsedStats = fs.statSync(file);

return res.json([{
    "uniqueFilename": "ClientSettings.Sav",
    "filename": "ClientSettings.Sav",
    "hash": crypto.createHash('sha1').update(ParsedFile).digest('hex'),
    "hash256": crypto.createHash('sha256').update(ParsedFile).digest('hex'),
    "length": Buffer.byteLength(ParsedFile),
    "contentType": "application/octet-stream",
    "uploaded": ParsedStats.mtime,
fork icon16
star icon31
watch icon0

+ 3 other calls in file

91
92
93
94
95
96
97
98
99
100
101
102
});




// update() should only take buffers / strings
assert.throws(
  () => crypto.createHash('sha1').update({ foo: 'bar' }),
  {
    code: 'ERR_INVALID_ARG_TYPE',
    name: 'TypeError'
  });
fork icon42
star icon19
watch icon0

+ 7 other calls in file

14
15
16
17
18
19
20
21
22
23
24


exports.md5 = function (str) {
  if (typeof str !== 'string') {
    throw new Error('md5 only support string');
  }
  let hash = crypto.createHash('md5');
  hash.update(str);
  return hash.digest('hex');
};

fork icon12
star icon36
watch icon7

+ 11 other calls in file

1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
	return new Promise(resolve => setTimeout(resolve, ms));
}

createHash(str) {
  try {
    return crypto.createHash('sha256').update(str).digest("hex");
  } catch (error) {
    console.error(error);
  }
}
fork icon11
star icon18
watch icon7

+ 2 other calls in file

36
37
38
39
40
41
42
43
44
45
  tokenOf: (user: UserModel) => string | undefined
  from: (req: Request) => ResponseWithUser | undefined
  updateFrom: (req: Request, user: ResponseWithUser) => any
}

exports.hash = (data: string) => crypto.createHash('md5').update(data).digest('hex')
exports.hmac = (data: string) => crypto.createHmac('sha256', 'pa4qacea4VK9t9nGv7yZtwmj').update(data).digest('hex')

exports.cutOffPoisonNullByte = (str: string) => {
  const nullByte = '%00'
fork icon10
star icon0
watch icon0

+ 9 other calls in file

41
42
43
44
45
46
47
48
49
50
function isElectron() {
    return !!process.versions['electron'];
}

function hash(text) {
    return crypto.createHash('sha1').update(text).digest('base64');
}

function isEmptyOrWhitespace(str) {
    return str === null || str.match(/^ *$/) !== null;
fork icon0
star icon190
watch icon8

+ 27 other calls in file

62
63
64
65
66
67
68
69
70
71
if (opts.validateUrl) {
  if (!('url_hash' in result.payload)) {
    throw new Error('invalid signature: missing url_hash claim');
  }

  let computedURLHash = createHash('sha256').update(url).digest();
  let validUrlHash = Buffer.compare(
    Buffer.from(result.payload.url_hash, 'hex'),
    computedURLHash
  ) === 0;
fork icon41
star icon101
watch icon13

+ 7 other calls in file

10
11
12
13
14
15
16
17
18
19
this._api = api;
this._hmac_hash = '';

this._public_key = '';
this._iv = crypto.randomBytes(16);
this._key = crypto.createHash('sha256').update(crypto.randomBytes(16).toString('hex')).digest();
this._session_key;

this._salt_bytes = 16;
this._current_salt = this._get_salt();
fork icon23
star icon32
watch icon18

+ 3 other calls in file

292
293
294
295
296
297
298
299
300
const key = "MY_SECRET_KEY";


// 'digest' is the output of hash function containing  
// only hexadecimal digits
hashPwd = crypto.createHash('sha1').update(key).digest('hex');
  
console.log(hashPwd); //ef5225a03e4f9cc953ab3c4dd41f5c4db7dc2e5b
```
fork icon926
star icon0
watch icon52

+ 3 other calls in file

221
222
223
224
225
226
227
228
229
230
for (let i = 0; i < integrityEntries.length; i++) {
  const {
    algorithm,
    value: expected
  } = integrityEntries[i];
  const hash = createHash(algorithm);
  hash.update(src);
  const digest = hash.digest();
  if (digest.length === expected.length &&
    timingSafeEqual(digest, expected)) {
fork icon209
star icon0
watch icon80

33
34
35
36
37
38
39
40
41
        });
}

function upload(uploadStream) {
        return crypto.randomBytesAsync(15).then(function (bytes) {
                var hash = crypto.createHash('sha256');
                var temporaryPath = path.join(temporaryDirectory, bytes.toString('base64').replace(/\//g, '-'));
                var temporaryFileStream = fs.createWriteStream(temporaryPath, { flags: 'wx', mode: 6 << 6 });
                var identifyStream = new IdentifyStream();
fork icon6
star icon0
watch icon1

36
37
38
39
40
41
42
43
44
 * Calculates the MD5 sum of the given text string.
 * @param {string} text - The input text.
 * @returns {string} The md5 hash of the given string.
 */
module.exports.createHash = function (text) {
    return crypto.createHash('md5').update(text).digest('hex')
};

//**********************************************************************
fork icon3
star icon5
watch icon3

21
22
23
24
25
26
27
28
29
30
    return { certificate, privateKey }
  }
}

function hashEmail (email) {
  return crypto.createHash('sha256').update(email.toLowerCase()).digest('base64')
}

async function createSelfSignedCertificate (name = 'localhost', number = '01') {
  x509.cryptoProvider.set(crypto.webcrypto)
fork icon3
star icon90
watch icon8