]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/helpers/peertube-crypto.ts
Optimize account creation
[github/Chocobozzz/PeerTube.git] / server / helpers / peertube-crypto.ts
... / ...
CommitLineData
1import * as jsonld from 'jsonld'
2import * as jsig from 'jsonld-signatures'
3jsig.use('jsonld', jsonld)
4
5import {
6 PRIVATE_RSA_KEY_SIZE,
7 BCRYPT_SALT_SIZE
8} from '../initializers'
9import {
10 bcryptComparePromise,
11 bcryptGenSaltPromise,
12 bcryptHashPromise,
13 createPrivateKey,
14 getPublicKey
15} from './core-utils'
16import { logger } from './logger'
17import { AccountInstance } from '../models/account/account-interface'
18
19async 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
28function 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
55function 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
64function comparePassword (plainPassword: string, hashPassword: string) {
65 return bcryptComparePromise(plainPassword, hashPassword)
66}
67
68async function cryptPassword (password: string) {
69 const salt = await bcryptGenSaltPromise(BCRYPT_SALT_SIZE)
70
71 return bcryptHashPromise(password, salt)
72}
73
74// ---------------------------------------------------------------------------
75
76export {
77 isSignatureVerified,
78 comparePassword,
79 createPrivateAndPublicKeys,
80 cryptPassword,
81 signObject
82}