forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.ts
More file actions
45 lines (42 loc) · 1.35 KB
/
crypto.ts
File metadata and controls
45 lines (42 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
// tslint:disable: no-any
import { createHash } from 'crypto';
import { injectable } from 'inversify';
import { traceError } from './logger';
import { ICryptoUtils, IHashFormat } from './types';
/**
* Implements tools related to cryptography
*/
@injectable()
export class CryptoUtils implements ICryptoUtils {
public createHash<E extends keyof IHashFormat>(
data: string,
hashFormat: E,
algorithm: 'SHA512' | 'SHA256' | 'FNV' = 'FNV'
): IHashFormat[E] {
let hash: string;
if (algorithm === 'FNV') {
// tslint:disable-next-line:no-require-imports
const fnv = require('@enonic/fnv-plus');
hash = fnv.fast1a32hex(data) as string;
} else if (algorithm === 'SHA256') {
hash = createHash('sha256')
.update(data)
.digest('hex');
} else {
hash = createHash('sha512')
.update(data)
.digest('hex');
}
if (hashFormat === 'number') {
const result = parseInt(hash, 16);
if (isNaN(result)) {
traceError(`Number hash for data '${data}' is NaN`);
}
return result as any;
}
return hash as any;
}
}