summaryrefslogtreecommitdiff
path: root/core/crypto/dh.js
blob: bd705d9bf1dad9f18f3faf2adcdefafe1014fe31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { modPow, bigIntToU8Array, u8ArrayToBigInt } from "./bigint.js";

class DHPublicKey {
    constructor(key) {
        this._key = key;
    }

    get algorithm() {
        return { name: "DH" };
    }

    exportKey() {
        return this._key;
    }
}

export class DHCipher {
    constructor() {
        this._g = null;
        this._p = null;
        this._gBigInt = null;
        this._pBigInt = null;
        this._privateKey = null;
    }

    get algorithm() {
        return { name: "DH" };
    }

    static generateKey(algorithm, _extractable) {
        const cipher = new DHCipher;
        cipher._generateKey(algorithm);
        return { privateKey: cipher, publicKey: new DHPublicKey(cipher._publicKey) };
    }

    _generateKey(algorithm) {
        const g = algorithm.g;
        const p = algorithm.p;
        this._keyBytes = p.length;
        this._gBigInt = u8ArrayToBigInt(g);
        this._pBigInt = u8ArrayToBigInt(p);
        this._privateKey = window.crypto.getRandomValues(new Uint8Array(this._keyBytes));
        this._privateKeyBigInt = u8ArrayToBigInt(this._privateKey);
        this._publicKey = bigIntToU8Array(modPow(
            this._gBigInt, this._privateKeyBigInt, this._pBigInt), this._keyBytes);
    }

    deriveBits(algorithm, length) {
        const bytes = Math.ceil(length / 8);
        const pkey = new Uint8Array(algorithm.public);
        const len = bytes > this._keyBytes ? bytes : this._keyBytes;
        const secret = modPow(u8ArrayToBigInt(pkey), this._privateKeyBigInt, this._pBigInt);
        return bigIntToU8Array(secret, len).slice(0, len);
    }
}