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