]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/helpers/peertube-crypto.ts
Correctly fix the webtorrent redundancy bug
[github/Chocobozzz/PeerTube.git] / server / helpers / peertube-crypto.ts
... / ...
CommitLineData
1import { BCRYPT_SALT_SIZE, PRIVATE_RSA_KEY_SIZE } from '../initializers'
2import { ActorModel } from '../models/activitypub/actor'
3import { bcryptComparePromise, bcryptGenSaltPromise, bcryptHashPromise, createPrivateKey, getPublicKey } from './core-utils'
4import { jsig } from './custom-jsonld-signature'
5import { logger } from './logger'
6
7async 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
16function 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
43function signObject (byActor: ActorModel, data: any) {
44 const options = {
45 privateKeyPem: byActor.privateKey,
46 creator: byActor.url,
47 algorithm: 'RsaSignature2017'
48 }
49
50 return jsig.promises.sign(data, options)
51}
52
53function comparePassword (plainPassword: string, hashPassword: string) {
54 return bcryptComparePromise(plainPassword, hashPassword)
55}
56
57async function cryptPassword (password: string) {
58 const salt = await bcryptGenSaltPromise(BCRYPT_SALT_SIZE)
59
60 return bcryptHashPromise(password, salt)
61}
62
63// ---------------------------------------------------------------------------
64
65export {
66 isSignatureVerified,
67 comparePassword,
68 createPrivateAndPublicKeys,
69 cryptPassword,
70 signObject
71}