]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/peertube-crypto.ts
Begin moving video channel to actor
[github/Chocobozzz/PeerTube.git] / server / helpers / peertube-crypto.ts
1 import { BCRYPT_SALT_SIZE, PRIVATE_RSA_KEY_SIZE } from '../initializers'
2 import { ActorModel } from '../models/activitypub/actor'
3 import { bcryptComparePromise, bcryptGenSaltPromise, bcryptHashPromise, createPrivateKey, getPublicKey } from './core-utils'
4 import { jsig } from './custom-jsonld-signature'
5 import { logger } from './logger'
6
7 async function createPrivateAndPublicKeys () {
8 logger.info('Generating a RSA key...')
9
10 const { key } = await createPrivateKey(PRIVATE_RSA_KEY_SIZE)
11 const { publicKey } = await getPublicKey(key)
12
13 return { privateKey: key, publicKey }
14 }
15
16 function isSignatureVerified (fromActor: ActorModel, signedDocument: object) {
17 const publicKeyObject = {
18 '@context': jsig.SECURITY_CONTEXT_URL,
19 '@id': fromActor.url,
20 '@type': 'CryptographicKey',
21 owner: fromActor.url,
22 publicKeyPem: fromActor.publicKey
23 }
24
25 const publicKeyOwnerObject = {
26 '@context': jsig.SECURITY_CONTEXT_URL,
27 '@id': fromActor.url,
28 publicKey: [ publicKeyObject ]
29 }
30
31 const options = {
32 publicKey: publicKeyObject,
33 publicKeyOwner: publicKeyOwnerObject
34 }
35
36 return jsig.promises.verify(signedDocument, options)
37 .catch(err => {
38 logger.error('Cannot check signature.', err)
39 return false
40 })
41 }
42
43 function signObject (byActor: ActorModel, data: any) {
44 const options = {
45 privateKeyPem: byActor.privateKey,
46 creator: byActor.url
47 }
48
49 return jsig.promises.sign(data, options)
50 }
51
52 function comparePassword (plainPassword: string, hashPassword: string) {
53 return bcryptComparePromise(plainPassword, hashPassword)
54 }
55
56 async function cryptPassword (password: string) {
57 const salt = await bcryptGenSaltPromise(BCRYPT_SALT_SIZE)
58
59 return bcryptHashPromise(password, salt)
60 }
61
62 // ---------------------------------------------------------------------------
63
64 export {
65 isSignatureVerified,
66 comparePassword,
67 createPrivateAndPublicKeys,
68 cryptPassword,
69 signObject
70 }