]>
Commit | Line | Data |
---|---|---|
1 | import * as jsonld from 'jsonld' | |
2 | import * as jsig from 'jsonld-signatures' | |
3 | jsig.use('jsonld', jsonld) | |
4 | ||
5 | import { | |
6 | PRIVATE_RSA_KEY_SIZE, | |
7 | BCRYPT_SALT_SIZE | |
8 | } from '../initializers' | |
9 | import { | |
10 | bcryptComparePromise, | |
11 | bcryptGenSaltPromise, | |
12 | bcryptHashPromise, | |
13 | createPrivateKey, | |
14 | getPublicKey | |
15 | } from './core-utils' | |
16 | import { logger } from './logger' | |
17 | import { AccountInstance } from '../models/account/account-interface' | |
18 | ||
19 | async function createPrivateAndPublicKeys () { | |
20 | logger.info('Generating a RSA key...') | |
21 | ||
22 | const { key } = await createPrivateKey(PRIVATE_RSA_KEY_SIZE) | |
23 | const { publicKey } = await getPublicKey(key) | |
24 | ||
25 | return { privateKey: key, publicKey } | |
26 | } | |
27 | ||
28 | function isSignatureVerified (fromAccount: AccountInstance, signedDocument: object) { | |
29 | const publicKeyObject = { | |
30 | '@context': jsig.SECURITY_CONTEXT_URL, | |
31 | '@id': fromAccount.url, | |
32 | '@type': 'CryptographicKey', | |
33 | owner: fromAccount.url, | |
34 | publicKeyPem: fromAccount.publicKey | |
35 | } | |
36 | ||
37 | const publicKeyOwnerObject = { | |
38 | '@context': jsig.SECURITY_CONTEXT_URL, | |
39 | '@id': fromAccount.url, | |
40 | publicKey: [ publicKeyObject ] | |
41 | } | |
42 | ||
43 | const options = { | |
44 | publicKey: publicKeyObject, | |
45 | publicKeyOwner: publicKeyOwnerObject | |
46 | } | |
47 | ||
48 | return jsig.promises.verify(signedDocument, options) | |
49 | .catch(err => { | |
50 | logger.error('Cannot check signature.', err) | |
51 | return false | |
52 | }) | |
53 | } | |
54 | ||
55 | function signObject (byAccount: AccountInstance, data: any) { | |
56 | const options = { | |
57 | privateKeyPem: byAccount.privateKey, | |
58 | creator: byAccount.url | |
59 | } | |
60 | ||
61 | return jsig.promises.sign(data, options) | |
62 | } | |
63 | ||
64 | function comparePassword (plainPassword: string, hashPassword: string) { | |
65 | return bcryptComparePromise(plainPassword, hashPassword) | |
66 | } | |
67 | ||
68 | async function cryptPassword (password: string) { | |
69 | const salt = await bcryptGenSaltPromise(BCRYPT_SALT_SIZE) | |
70 | ||
71 | return bcryptHashPromise(password, salt) | |
72 | } | |
73 | ||
74 | // --------------------------------------------------------------------------- | |
75 | ||
76 | export { | |
77 | isSignatureVerified, | |
78 | comparePassword, | |
79 | createPrivateAndPublicKeys, | |
80 | cryptPassword, | |
81 | signObject | |
82 | } |