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