@icure/api 8.0.24 → 8.0.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/icc-x-api/crypto/AES.d.ts +54 -2
- package/icc-x-api/crypto/AES.js +5 -5
- package/icc-x-api/crypto/AES.js.map +1 -1
- package/icc-x-api/crypto/CryptoPrimitives.d.ts +21 -12
- package/icc-x-api/crypto/CryptoPrimitives.js +8 -19
- package/icc-x-api/crypto/CryptoPrimitives.js.map +1 -1
- package/icc-x-api/crypto/DelegationsDeAnonymization.js +1 -1
- package/icc-x-api/crypto/DelegationsDeAnonymization.js.map +1 -1
- package/icc-x-api/crypto/HMACUtils.d.ts +8 -1
- package/icc-x-api/crypto/HMACUtils.js +3 -3
- package/icc-x-api/crypto/HMACUtils.js.map +1 -1
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.d.ts +113 -0
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.js +477 -0
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.js.map +1 -0
- package/icc-x-api/crypto/RSA.d.ts +107 -4
- package/icc-x-api/crypto/RSA.js +4 -4
- package/icc-x-api/crypto/RSA.js.map +1 -1
- package/icc-x-api/crypto/shamir.d.ts +7 -3
- package/icc-x-api/crypto/shamir.js +14 -5
- package/icc-x-api/crypto/shamir.js.map +1 -1
- package/icc-x-api/index.d.ts +1 -0
- package/icc-x-api/index.js +5 -3
- package/icc-x-api/index.js.map +1 -1
- package/package.json +1 -1
- package/test/icc-api/api/IccMedicalLocationApi.js +6 -6
- package/test/icc-api/api/IccMedicalLocationApi.js.map +1 -1
- package/test/icc-x-api/crud/comprehensive-crud-test.js +1 -1
- package/test/icc-x-api/crud/comprehensive-crud-test.js.map +1 -1
- package/test/icc-x-api/crud/entities-crud-test-interface.js +1 -0
- package/test/icc-x-api/crud/entities-crud-test-interface.js.map +1 -1
- package/test/icc-x-api/crypto/anonymous-delegations-test.js +1 -2
- package/test/icc-x-api/crypto/anonymous-delegations-test.js.map +1 -1
- package/test/icc-x-api/crypto/crypto-utils.js +1 -2
- package/test/icc-x-api/crypto/crypto-utils.js.map +1 -1
- package/test/icc-x-api/crypto/exchange-data-manager-test.js +1 -1
- package/test/icc-x-api/crypto/exchange-data-manager-test.js.map +1 -1
- package/test/icc-x-api/crypto/full-crypto-test.js +1 -2
- package/test/icc-x-api/crypto/full-crypto-test.js.map +1 -1
- package/test/icc-x-api/crypto/secure-delegations-manager-test.js +1 -1
- package/test/icc-x-api/crypto/secure-delegations-manager-test.js.map +1 -1
- package/test/icc-x-api/crypto/secure-delegations-metadata-decryptor-test.js +2 -2
- package/test/icc-x-api/crypto/secure-delegations-metadata-decryptor-test.js.map +1 -1
- package/test/icc-x-api/crypto/shamir.js +6 -7
- package/test/icc-x-api/crypto/shamir.js.map +1 -1
- package/test/icc-x-api/crypto/signature-keys-manager-test.js +1 -1
- package/test/icc-x-api/crypto/signature-keys-manager-test.js.map +1 -1
- package/test/icc-x-api/icc-maintenance-task-x-api-test.js +3 -2
- package/test/icc-x-api/icc-maintenance-task-x-api-test.js.map +1 -1
- package/test/icc-x-api/icc-user-x-api-test.js +1 -1
- package/test/icc-x-api/icc-user-x-api-test.js.map +1 -1
- package/test/icc-x-api/patient-user.js +1 -2
- package/test/icc-x-api/patient-user.js.map +1 -1
- package/test/icc-x-api/test-legacy-data-support.js +2 -3
- package/test/icc-x-api/test-legacy-data-support.js.map +1 -1
- package/test/utils/FakeDataOwnerApi.js +1 -1
- package/test/utils/FakeDataOwnerApi.js.map +1 -1
- package/test/utils/FakeGenericApi.js +1 -1
- package/test/utils/FakeGenericApi.js.map +1 -1
- package/test/utils/TestApi.js +1 -1
- package/test/utils/TestApi.js.map +1 -1
- package/test/utils/TestCryptoStrategies.js +1 -1
- package/test/utils/TestCryptoStrategies.js.map +1 -1
- package/test/utils/test_utils.js +6 -6
- package/test/utils/test_utils.js.map +1 -1
- package/test/icc-api/api/IccArticleApi.d.ts +0 -1
- package/test/icc-api/api/IccArticleApi.js +0 -64
- package/test/icc-api/api/IccArticleApi.js.map +0 -1
|
@@ -1,4 +1,56 @@
|
|
|
1
|
-
export
|
|
1
|
+
export interface AESUtils {
|
|
2
|
+
encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>;
|
|
3
|
+
encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer>;
|
|
4
|
+
decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>;
|
|
5
|
+
/**
|
|
6
|
+
*
|
|
7
|
+
* @param cryptoKey (CryptoKey)
|
|
8
|
+
* @param encryptedData (ArrayBuffer)
|
|
9
|
+
* @param rawKey
|
|
10
|
+
* @returns {Promise} will be ArrayBuffer
|
|
11
|
+
*/
|
|
12
|
+
decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer>;
|
|
13
|
+
/**
|
|
14
|
+
* @deprecated this method is not correct: in some cases decryption may not fail even if the wrong key is used: if the
|
|
15
|
+
* first provided keys are wrong and the last one is correct the decryption will succeed for sure, but there is a small
|
|
16
|
+
* chance that you will get garbage
|
|
17
|
+
*/
|
|
18
|
+
decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer>;
|
|
19
|
+
/**
|
|
20
|
+
*
|
|
21
|
+
* @param toHex boolean, if true, it returns hex String
|
|
22
|
+
* @returns {Promise} either Hex string or CryptoKey
|
|
23
|
+
*/
|
|
24
|
+
generateCryptoKey(toHex: false): Promise<CryptoKey>;
|
|
25
|
+
generateCryptoKey(toHex: true): Promise<string>;
|
|
26
|
+
generateCryptoKey(toHex: boolean): Promise<string | CryptoKey>;
|
|
27
|
+
generateIV(ivByteLength: number): Uint8Array;
|
|
28
|
+
/**
|
|
29
|
+
* This function return a promise which will be the key Format will be either 'raw' or 'jwk'.
|
|
30
|
+
* JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)
|
|
31
|
+
*
|
|
32
|
+
* @param cryptoKey CryptoKey
|
|
33
|
+
* @param format will be 'raw' or 'jwk'
|
|
34
|
+
* @returns {Promise} will the AES Key
|
|
35
|
+
*/
|
|
36
|
+
exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>;
|
|
37
|
+
exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>;
|
|
38
|
+
exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey>;
|
|
39
|
+
/**
|
|
40
|
+
* the ability to import a key that have already been created elsewhere, for use within the web
|
|
41
|
+
* application that is invoking the import function, for use within the importing web application's
|
|
42
|
+
* origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be
|
|
43
|
+
* represented as octets.
|
|
44
|
+
*
|
|
45
|
+
* https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js
|
|
46
|
+
*
|
|
47
|
+
* @param format 'raw' or 'jwk'
|
|
48
|
+
* @param aesKey
|
|
49
|
+
* @returns {*}
|
|
50
|
+
*/
|
|
51
|
+
importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey>;
|
|
52
|
+
}
|
|
53
|
+
export declare class AESUtilsImpl implements AESUtils {
|
|
2
54
|
/********* AES Config **********/
|
|
3
55
|
ivLength: number;
|
|
4
56
|
aesAlgorithmEncryptName: string;
|
|
@@ -51,4 +103,4 @@ export declare class AESUtils {
|
|
|
51
103
|
*/
|
|
52
104
|
importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey>;
|
|
53
105
|
}
|
|
54
|
-
export declare const AES:
|
|
106
|
+
export declare const AES: AESUtilsImpl;
|
package/icc-x-api/crypto/AES.js
CHANGED
|
@@ -9,9 +9,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.AES = exports.
|
|
12
|
+
exports.AES = exports.AESUtilsImpl = void 0;
|
|
13
13
|
const utils_1 = require("../utils");
|
|
14
|
-
class
|
|
14
|
+
class AESUtilsImpl {
|
|
15
15
|
set debug(value) {
|
|
16
16
|
this._debug = value;
|
|
17
17
|
}
|
|
@@ -64,7 +64,7 @@ class AESUtils {
|
|
|
64
64
|
* @param rawKey
|
|
65
65
|
* @returns {Promise} will be ArrayBuffer
|
|
66
66
|
*/
|
|
67
|
-
decrypt(cryptoKey, encryptedData, rawKey
|
|
67
|
+
decrypt(cryptoKey, encryptedData, rawKey) {
|
|
68
68
|
return new Promise((resolve, reject) => {
|
|
69
69
|
if (!cryptoKey) {
|
|
70
70
|
return reject('No crypto key provided for decryption');
|
|
@@ -161,6 +161,6 @@ class AESUtils {
|
|
|
161
161
|
});
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
|
-
exports.
|
|
165
|
-
exports.AES = new
|
|
164
|
+
exports.AESUtilsImpl = AESUtilsImpl;
|
|
165
|
+
exports.AES = new AESUtilsImpl();
|
|
166
166
|
//# sourceMappingURL=AES.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AES.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/AES.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oCAAuD;AAEvD,MAAa,QAAQ;IAYnB,IAAI,KAAK,CAAC,KAAc;QACtB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,YAAY,SAAiB,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,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AS,CAAC,CAAA;YACpD,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM;iBACtB,SAAS,CAAC,MAAa,EAAE,MAAa,EAAE,IAAI,CAAC,eAAe,EAAE,WAAW,EAAE,SAAS,CAAC;iBACrF,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;gBACb,IAAI,MAAM,IAAI,KAAK,IAAI,CAAC,MAAM,YAAY,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE;oBACpF,OAAO,CAAC,IAAI,CAAC,iBAAiB,IAAA,cAAM,EAAC,MAAM,CAAC,SAAS,CAAC,CAAA;iBACvD;gBACD,MAAM,GAAG,CAAA;YACX,CAAC,CAAC;iBACD,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAC1B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AAhMD,4BAgMC;AAEY,QAAA,GAAG,GAAG,IAAI,QAAQ,EAAE,CAAA","sourcesContent":["import { appendBuffer, hex2ua, ua2hex } from '../utils'\n\nexport class AESUtils {\n /********* AES Config **********/\n ivLength = 16\n aesAlgorithmEncryptName = 'AES-CBC'\n\n aesKeyGenParams: AesKeyGenParams = {\n name: 'AES-CBC',\n length: 256,\n }\n private crypto: Crypto\n private _debug: boolean = false\n\n set debug(value: boolean) {\n this._debug = value\n }\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this.crypto = crypto\n }\n\n async encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.encrypt(\n await this.importKey('raw', hex2ua(rawKey.replace(/-/g, ''))),\n plainData,\n rawKey // Used for logging only if debug is enabled, ok to always pass\n )\n }\n\n encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey = '<NA>'): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (plainData instanceof Uint8Array) {\n const buffer = plainData.buffer\n plainData = (buffer.byteLength > plainData.byteLength ? buffer.slice(0, plainData.byteLength) : buffer) as ArrayBuffer\n }\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: this.generateIV(this.ivLength),\n }\n this._debug && console.log(`encrypt ${ua2hex(plainData)} with ${rawKey}`)\n this.crypto.subtle\n .encrypt(\n {\n ...aesAlgorithmEncrypt,\n } /* some ill behaved implementations change the values in place */,\n cryptoKey,\n plainData\n )\n .then(\n (cipherData) => {\n this._debug && console.log(`cipherData: ${ua2hex(cipherData)}`)\n return resolve(appendBuffer(aesAlgorithmEncrypt.iv.buffer as ArrayBuffer, cipherData))\n },\n (err) => reject('AES encryption failed: ' + err)\n )\n })\n }\n\n async decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.decrypt(\n await this.importKey('raw', hex2ua(rawKey.replace(/-/g, ''))),\n plainData,\n rawKey // Used for logging only if debug is enabled, ok to always pass\n )\n }\n\n /**\n *\n * @param cryptoKey (CryptoKey)\n * @param encryptedData (ArrayBuffer)\n * @param rawKey\n * @returns {Promise} will be ArrayBuffer\n */\n decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey = '<NA>'): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (!cryptoKey) {\n return reject('No crypto key provided for decryption')\n }\n const encryptedDataUint8 = encryptedData instanceof ArrayBuffer ? new Uint8Array(encryptedData) : encryptedData\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: encryptedDataUint8.subarray(0, this.ivLength),\n\n /*\n * IF THIS BIT OF CODE PRODUCES A DOMEXCEPTION CODE 0 ERROR, IT MIGHT BE RELATED TO THIS:\n *\n * NOTOK:\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[hcpartyId] && hcparty.hcPartyKeys[hcpartyId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + hcpartyId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[hcpartyId][1];\n *\n * SHOULD BE:\n * var delegatorId = patient.delegations[hcpartyId][0].owner;\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[delegatorId] && hcparty.hcPartyKeys[delegatorId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + delegatorId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[delegatorId][1];\n */\n }\n this._debug && console.log(`decrypt ${ua2hex(encryptedData)} with ${rawKey}`)\n this.crypto.subtle.decrypt(aesAlgorithmEncrypt, cryptoKey, encryptedDataUint8.subarray(this.ivLength, encryptedDataUint8.length)).then(\n (decipheredData) => {\n this._debug && console.log(`decipheredData: ${ua2hex(decipheredData)}`)\n resolve(decipheredData)\n },\n (err) => {\n reject(new Error('AES decryption failed: ' + err))\n }\n )\n })\n }\n\n async decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer> {\n try {\n return this.decrypt(cryptoKeys[0], uint8Array)\n } catch (e) {\n if (cryptoKeys.length > 1) {\n return this.decryptSome(cryptoKeys.slice(1), uint8Array)\n } else {\n throw e\n }\n }\n }\n\n // generate an AES key\n // noinspection JSUnusedGlobalSymbols\n /**\n *\n * @param toHex boolean, if true, it returns hex String\n * @returns {Promise} either Hex string or CryptoKey\n */\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n generateCryptoKey(toHex: true): Promise<string>\n generateCryptoKey(toHex: boolean): Promise<string | CryptoKey> {\n return new Promise((resolve: (value: CryptoKey | string) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n const cryptoKeyPromise: Promise<CryptoKey> = this.crypto.subtle.generateKey(this.aesKeyGenParams, extractable, keyUsages) as Promise<CryptoKey>\n return toHex === undefined || !toHex\n ? cryptoKeyPromise.then(resolve, reject)\n : cryptoKeyPromise.then((k) => this.exportKey(k, 'raw'), reject).then((raw) => resolve(ua2hex(raw)), reject)\n })\n }\n\n // noinspection JSMethodCanBeStatic\n generateIV(ivByteLength: number): Uint8Array {\n return new Uint8Array(this.crypto.getRandomValues(new Uint8Array(ivByteLength)))\n }\n\n /**\n * This function return a promise which will be the key Format will be either 'raw' or 'jwk'.\n * JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n *\n * @param cryptoKey CryptoKey\n * @param format will be 'raw' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey> {\n return new Promise((resolve: (value: ArrayBuffer | JsonWebKey) => any, reject: (reason: any) => any) => {\n return this.crypto.subtle.exportKey(format as any, cryptoKey).then(resolve, reject)\n })\n }\n\n /**\n * the ability to import a key that have already been created elsewhere, for use within the web\n * application that is invoking the import function, for use within the importing web application's\n * origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be\n * represented as octets.\n *\n * https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js\n *\n * @param format 'raw' or 'jwk'\n * @param aesKey\n * @returns {*}\n */\n importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey> {\n return new Promise((resolve: (value: CryptoKey) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n return this.crypto.subtle\n .importKey(format as any, aesKey as any, this.aesKeyGenParams, extractable, keyUsages)\n .catch((err) => {\n if (format == 'raw' && (aesKey instanceof ArrayBuffer || ArrayBuffer.isView(aesKey))) {\n console.warn(`Import of key ${ua2hex(aesKey)} failed`)\n }\n throw err\n })\n .then(resolve, reject)\n })\n }\n}\n\nexport const AES = new AESUtils()\n"]}
|
|
1
|
+
{"version":3,"file":"AES.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/AES.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oCAAuD;AAmEvD,MAAa,YAAY;IAYvB,IAAI,KAAK,CAAC,KAAc;QACtB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,YAAY,SAAiB,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAE,EAAa;QAfvI,iCAAiC;QACjC,aAAQ,GAAG,EAAE,CAAA;QACb,4BAAuB,GAAG,SAAS,CAAA;QAEnC,oBAAe,GAAoB;YACjC,IAAI,EAAE,SAAS;YACf,MAAM,EAAE,GAAG;SACZ,CAAA;QAEO,WAAM,GAAY,KAAK,CAAA;QAO7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IAEK,iBAAiB,CAAC,MAAc,EAAE,SAAmC;;YACzE,OAAO,IAAI,CAAC,OAAO,CACjB,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAA,cAAM,EAAC,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,EAC7D,SAAS,EACT,MAAM,CAAC,+DAA+D;aACvE,CAAA;QACH,CAAC;KAAA;IAED,OAAO,CAAC,SAAoB,EAAE,SAAmC,EAAE,MAAM,GAAG,MAAM;QAChF,OAAO,IAAI,OAAO,CAAC,CAAC,OAAoC,EAAE,MAA4B,EAAE,EAAE;YACxF,IAAI,SAAS,YAAY,UAAU,EAAE;gBACnC,MAAM,MAAM,GAAG,SAAS,CAAC,MAAM,CAAA;gBAC/B,SAAS,GAAG,CAAC,MAAM,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AI,OAAO,CAAC,CAAC,OAAiD,EAAE,MAA4B,EAAE,EAAE;YACrG,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,MAAa,EAAE,SAAS,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QACrF,CAAC,CAAC,CAAA;IACJ,CAAC;IAED;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,MAAqB,EAAE,MAA6C;QAC5E,OAAO,IAAI,OAAO,CAAC,CAAC,OAAkC,EAAE,MAA4B,EAAE,EAAE;YACtF,MAAM,WAAW,GAAG,IAAI,CAAA;YACxB,MAAM,SAAS,GAAe,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;YACpD,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM;iBACtB,SAAS,CAAC,MAAa,EAAE,MAAa,EAAE,IAAI,CAAC,eAAe,EAAE,WAAW,EAAE,SAAS,CAAC;iBACrF,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;gBACb,IAAI,MAAM,IAAI,KAAK,IAAI,CAAC,MAAM,YAAY,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE;oBACpF,OAAO,CAAC,IAAI,CAAC,iBAAiB,IAAA,cAAM,EAAC,MAAM,CAAC,SAAS,CAAC,CAAA;iBACvD;gBACD,MAAM,GAAG,CAAA;YACX,CAAC,CAAC;iBACD,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAC1B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AAhMD,oCAgMC;AAEY,QAAA,GAAG,GAAG,IAAI,YAAY,EAAE,CAAA","sourcesContent":["import { appendBuffer, hex2ua, ua2hex } from '../utils'\n\nexport interface AESUtils {\n encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>\n\n encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer>\n\n decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>\n\n /**\n *\n * @param cryptoKey (CryptoKey)\n * @param encryptedData (ArrayBuffer)\n * @param rawKey\n * @returns {Promise} will be ArrayBuffer\n */\n decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer>\n\n /**\n * @deprecated this method is not correct: in some cases decryption may not fail even if the wrong key is used: if the\n * first provided keys are wrong and the last one is correct the decryption will succeed for sure, but there is a small\n * chance that you will get garbage\n */\n decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer>\n\n /**\n *\n * @param toHex boolean, if true, it returns hex String\n * @returns {Promise} either Hex string or CryptoKey\n */\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n\n generateCryptoKey(toHex: true): Promise<string>\n\n generateCryptoKey(toHex: boolean): Promise<string | CryptoKey>\n\n generateIV(ivByteLength: number): Uint8Array\n\n /**\n * This function return a promise which will be the key Format will be either 'raw' or 'jwk'.\n * JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n *\n * @param cryptoKey CryptoKey\n * @param format will be 'raw' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n\n exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey>\n\n /**\n * the ability to import a key that have already been created elsewhere, for use within the web\n * application that is invoking the import function, for use within the importing web application's\n * origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be\n * represented as octets.\n *\n * https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js\n *\n * @param format 'raw' or 'jwk'\n * @param aesKey\n * @returns {*}\n */\n importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey>\n}\n\nexport class AESUtilsImpl implements AESUtils {\n /********* AES Config **********/\n ivLength = 16\n aesAlgorithmEncryptName = 'AES-CBC'\n\n aesKeyGenParams: AesKeyGenParams = {\n name: 'AES-CBC',\n length: 256,\n }\n private crypto: Crypto\n private _debug: boolean = false\n\n set debug(value: boolean) {\n this._debug = value\n }\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this.crypto = crypto\n }\n\n async encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.encrypt(\n await this.importKey('raw', hex2ua(rawKey.replace(/-/g, ''))),\n plainData,\n rawKey // Used for logging only if debug is enabled, ok to always pass\n )\n }\n\n encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey = '<NA>'): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (plainData instanceof Uint8Array) {\n const buffer = plainData.buffer\n plainData = (buffer.byteLength > plainData.byteLength ? buffer.slice(0, plainData.byteLength) : buffer) as ArrayBuffer\n }\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: this.generateIV(this.ivLength),\n }\n this._debug && console.log(`encrypt ${ua2hex(plainData)} with ${rawKey}`)\n this.crypto.subtle\n .encrypt(\n {\n ...aesAlgorithmEncrypt,\n } /* some ill behaved implementations change the values in place */,\n cryptoKey,\n plainData\n )\n .then(\n (cipherData) => {\n this._debug && console.log(`cipherData: ${ua2hex(cipherData)}`)\n return resolve(appendBuffer(aesAlgorithmEncrypt.iv.buffer as ArrayBuffer, cipherData))\n },\n (err) => reject('AES encryption failed: ' + err)\n )\n })\n }\n\n async decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.decrypt(\n await this.importKey('raw', hex2ua(rawKey.replace(/-/g, ''))),\n plainData,\n rawKey // Used for logging only if debug is enabled, ok to always pass\n )\n }\n\n /**\n *\n * @param cryptoKey (CryptoKey)\n * @param encryptedData (ArrayBuffer)\n * @param rawKey\n * @returns {Promise} will be ArrayBuffer\n */\n decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (!cryptoKey) {\n return reject('No crypto key provided for decryption')\n }\n const encryptedDataUint8 = encryptedData instanceof ArrayBuffer ? new Uint8Array(encryptedData) : encryptedData\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: encryptedDataUint8.subarray(0, this.ivLength),\n\n /*\n * IF THIS BIT OF CODE PRODUCES A DOMEXCEPTION CODE 0 ERROR, IT MIGHT BE RELATED TO THIS:\n *\n * NOTOK:\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[hcpartyId] && hcparty.hcPartyKeys[hcpartyId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + hcpartyId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[hcpartyId][1];\n *\n * SHOULD BE:\n * var delegatorId = patient.delegations[hcpartyId][0].owner;\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[delegatorId] && hcparty.hcPartyKeys[delegatorId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + delegatorId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[delegatorId][1];\n */\n }\n this._debug && console.log(`decrypt ${ua2hex(encryptedData)} with ${rawKey}`)\n this.crypto.subtle.decrypt(aesAlgorithmEncrypt, cryptoKey, encryptedDataUint8.subarray(this.ivLength, encryptedDataUint8.length)).then(\n (decipheredData) => {\n this._debug && console.log(`decipheredData: ${ua2hex(decipheredData)}`)\n resolve(decipheredData)\n },\n (err) => {\n reject(new Error('AES decryption failed: ' + err))\n }\n )\n })\n }\n\n async decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer> {\n try {\n return this.decrypt(cryptoKeys[0], uint8Array)\n } catch (e) {\n if (cryptoKeys.length > 1) {\n return this.decryptSome(cryptoKeys.slice(1), uint8Array)\n } else {\n throw e\n }\n }\n }\n\n // generate an AES key\n // noinspection JSUnusedGlobalSymbols\n /**\n *\n * @param toHex boolean, if true, it returns hex String\n * @returns {Promise} either Hex string or CryptoKey\n */\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n generateCryptoKey(toHex: true): Promise<string>\n generateCryptoKey(toHex: boolean): Promise<string | CryptoKey> {\n return new Promise((resolve: (value: CryptoKey | string) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n const cryptoKeyPromise: Promise<CryptoKey> = this.crypto.subtle.generateKey(this.aesKeyGenParams, extractable, keyUsages) as Promise<CryptoKey>\n return toHex === undefined || !toHex\n ? cryptoKeyPromise.then(resolve, reject)\n : cryptoKeyPromise.then((k) => this.exportKey(k, 'raw'), reject).then((raw) => resolve(ua2hex(raw)), reject)\n })\n }\n\n // noinspection JSMethodCanBeStatic\n generateIV(ivByteLength: number): Uint8Array {\n return new Uint8Array(this.crypto.getRandomValues(new Uint8Array(ivByteLength)))\n }\n\n /**\n * This function return a promise which will be the key Format will be either 'raw' or 'jwk'.\n * JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n *\n * @param cryptoKey CryptoKey\n * @param format will be 'raw' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey> {\n return new Promise((resolve: (value: ArrayBuffer | JsonWebKey) => any, reject: (reason: any) => any) => {\n return this.crypto.subtle.exportKey(format as any, cryptoKey).then(resolve, reject)\n })\n }\n\n /**\n * the ability to import a key that have already been created elsewhere, for use within the web\n * application that is invoking the import function, for use within the importing web application's\n * origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be\n * represented as octets.\n *\n * https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js\n *\n * @param format 'raw' or 'jwk'\n * @param aesKey\n * @returns {*}\n */\n importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey> {\n return new Promise((resolve: (value: CryptoKey) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n return this.crypto.subtle\n .importKey(format as any, aesKey as any, this.aesKeyGenParams, extractable, keyUsages)\n .catch((err) => {\n if (format == 'raw' && (aesKey instanceof ArrayBuffer || ArrayBuffer.isView(aesKey))) {\n console.warn(`Import of key ${ua2hex(aesKey)} failed`)\n }\n throw err\n })\n .then(resolve, reject)\n })\n }\n}\n\nexport const AES = new AESUtilsImpl()\n"]}
|
|
@@ -2,10 +2,30 @@ import { RSAUtils } from './RSA';
|
|
|
2
2
|
import { AESUtils } from './AES';
|
|
3
3
|
import { ShamirClass } from './shamir';
|
|
4
4
|
import { HMACUtils } from './HMACUtils';
|
|
5
|
+
export interface CryptoPrimitives {
|
|
6
|
+
readonly shamir: ShamirClass;
|
|
7
|
+
readonly RSA: RSAUtils;
|
|
8
|
+
readonly AES: AESUtils;
|
|
9
|
+
readonly HMAC: HMACUtils;
|
|
10
|
+
/**
|
|
11
|
+
* Generates a UUID using a cryptographically secure random number generator.
|
|
12
|
+
*/
|
|
13
|
+
randomUuid(): string;
|
|
14
|
+
/**
|
|
15
|
+
* @param data some data
|
|
16
|
+
* @return the sha256 hash of {@link data}
|
|
17
|
+
*/
|
|
18
|
+
sha256(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>;
|
|
19
|
+
/**
|
|
20
|
+
* @param n how many bytes to generate
|
|
21
|
+
* @return an array with n random bytes
|
|
22
|
+
*/
|
|
23
|
+
randomBytes(n: number): Uint8Array;
|
|
24
|
+
}
|
|
5
25
|
/**
|
|
6
26
|
* Gives access to cryptographic primitives.
|
|
7
27
|
*/
|
|
8
|
-
export declare class CryptoPrimitives {
|
|
28
|
+
export declare class CryptoPrimitivesImpl implements CryptoPrimitives {
|
|
9
29
|
private readonly _rsa;
|
|
10
30
|
private readonly _aes;
|
|
11
31
|
private readonly _shamir;
|
|
@@ -17,18 +37,7 @@ export declare class CryptoPrimitives {
|
|
|
17
37
|
get AES(): AESUtils;
|
|
18
38
|
get HMAC(): HMACUtils;
|
|
19
39
|
constructor(crypto?: Crypto);
|
|
20
|
-
/**
|
|
21
|
-
* Generates a UUID using a cryptographically secure random number generator.
|
|
22
|
-
*/
|
|
23
40
|
randomUuid(): string;
|
|
24
|
-
/**
|
|
25
|
-
* @param data some data
|
|
26
|
-
* @return the sha256 hash of {@link data}
|
|
27
|
-
*/
|
|
28
41
|
sha256(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>;
|
|
29
|
-
/**
|
|
30
|
-
* @param n how many bytes to generate
|
|
31
|
-
* @return an array with n random bytes
|
|
32
|
-
*/
|
|
33
42
|
randomBytes(n: number): Uint8Array;
|
|
34
43
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.CryptoPrimitivesImpl = void 0;
|
|
4
4
|
const RSA_1 = require("./RSA");
|
|
5
5
|
const AES_1 = require("./AES");
|
|
6
6
|
const shamir_1 = require("./shamir");
|
|
@@ -8,7 +8,7 @@ const HMACUtils_1 = require("./HMACUtils");
|
|
|
8
8
|
/**
|
|
9
9
|
* Gives access to cryptographic primitives.
|
|
10
10
|
*/
|
|
11
|
-
class
|
|
11
|
+
class CryptoPrimitivesImpl {
|
|
12
12
|
get crypto() {
|
|
13
13
|
return this._crypto;
|
|
14
14
|
}
|
|
@@ -26,35 +26,24 @@ class CryptoPrimitives {
|
|
|
26
26
|
}
|
|
27
27
|
constructor(crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : {}) {
|
|
28
28
|
this._crypto = crypto;
|
|
29
|
-
this._rsa = new RSA_1.
|
|
30
|
-
this._aes = new AES_1.
|
|
31
|
-
this._shamir = new shamir_1.
|
|
32
|
-
this._hmac = new HMACUtils_1.
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Generates a UUID using a cryptographically secure random number generator.
|
|
36
|
-
*/
|
|
29
|
+
this._rsa = new RSA_1.RSAUtilsImpl(crypto);
|
|
30
|
+
this._aes = new AES_1.AESUtilsImpl(crypto);
|
|
31
|
+
this._shamir = new shamir_1.WebcryptoShamir(crypto);
|
|
32
|
+
this._hmac = new HMACUtils_1.HMACUtilsImpl(crypto);
|
|
33
|
+
}
|
|
37
34
|
randomUuid() {
|
|
38
35
|
return ((1e7).toString() + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g,
|
|
39
36
|
//Keep next inlined or you will lose the random
|
|
40
37
|
(c) => (Number(c) ^ (this.crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (Number(c) / 4)))).toString(16));
|
|
41
38
|
}
|
|
42
|
-
/**
|
|
43
|
-
* @param data some data
|
|
44
|
-
* @return the sha256 hash of {@link data}
|
|
45
|
-
*/
|
|
46
39
|
sha256(data) {
|
|
47
40
|
return this.crypto.subtle.digest('SHA-256', data);
|
|
48
41
|
}
|
|
49
|
-
/**
|
|
50
|
-
* @param n how many bytes to generate
|
|
51
|
-
* @return an array with n random bytes
|
|
52
|
-
*/
|
|
53
42
|
randomBytes(n) {
|
|
54
43
|
const res = new Uint8Array(n);
|
|
55
44
|
this.crypto.getRandomValues(res);
|
|
56
45
|
return res;
|
|
57
46
|
}
|
|
58
47
|
}
|
|
59
|
-
exports.
|
|
48
|
+
exports.CryptoPrimitivesImpl = CryptoPrimitivesImpl;
|
|
60
49
|
//# sourceMappingURL=CryptoPrimitives.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CryptoPrimitives.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/CryptoPrimitives.ts"],"names":[],"mappings":";;;AAAA,+
|
|
1
|
+
{"version":3,"file":"CryptoPrimitives.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/CryptoPrimitives.ts"],"names":[],"mappings":";;;AAAA,+BAA8C;AAC9C,+BAA8C;AAC9C,qCAAuD;AACvD,2CAAsD;AAuBtD;;GAEG;AACH,MAAa,oBAAoB;IAO/B,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,IAAI,CAAA;IAClB,CAAC;IAED,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,IAAI,CAAA;IAClB,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,KAAK,CAAA;IACnB,CAAC;IAED,YAAY,SAAiB,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAE,EAAa;QACrI,IAAI,CAAC,OAAO,GAAG,MAAM,CAAA;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,kBAAY,CAAC,MAAM,CAAC,CAAA;QACpC,IAAI,CAAC,IAAI,GAAG,IAAI,kBAAY,CAAC,MAAM,CAAC,CAAA;QACpC,IAAI,CAAC,OAAO,GAAG,IAAI,wBAAe,CAAC,MAAM,CAAC,CAAA;QAC1C,IAAI,CAAC,KAAK,GAAG,IAAI,yBAAa,CAAC,MAAM,CAAC,CAAA;IACxC,CAAC;IAED,UAAU;QACR,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC,OAAO,CAC5D,QAAQ;QACR,+CAA+C;QAC/C,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAE,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,CAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CACjI,CAAA;IACH,CAAC;IAED,MAAM,CAAC,IAA8B;QACnC,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;IACnD,CAAC;IAED,WAAW,CAAC,CAAS;QACnB,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAA;QAC7B,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,GAAG,CAAC,CAAA;QAChC,OAAO,GAAG,CAAA;IACZ,CAAC;CACF;AApDD,oDAoDC","sourcesContent":["import { RSAUtils, RSAUtilsImpl } from './RSA'\nimport { AESUtils, AESUtilsImpl } from './AES'\nimport { ShamirClass, WebcryptoShamir } from './shamir'\nimport { HMACUtils, HMACUtilsImpl } from './HMACUtils'\n\nexport interface CryptoPrimitives {\n readonly shamir: ShamirClass\n readonly RSA: RSAUtils\n readonly AES: AESUtils\n readonly HMAC: HMACUtils\n /**\n * Generates a UUID using a cryptographically secure random number generator.\n */\n randomUuid(): string\n /**\n * @param data some data\n * @return the sha256 hash of {@link data}\n */\n sha256(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>\n /**\n * @param n how many bytes to generate\n * @return an array with n random bytes\n */\n randomBytes(n: number): Uint8Array\n}\n\n/**\n * Gives access to cryptographic primitives.\n */\nexport class CryptoPrimitivesImpl implements CryptoPrimitives {\n private readonly _rsa: RSAUtils\n private readonly _aes: AESUtils\n private readonly _shamir: ShamirClass\n private readonly _crypto: Crypto\n private readonly _hmac: HMACUtils\n\n get crypto(): Crypto {\n return this._crypto\n }\n\n get shamir(): ShamirClass {\n return this._shamir\n }\n\n get RSA(): RSAUtils {\n return this._rsa\n }\n\n get AES(): AESUtils {\n return this._aes\n }\n\n get HMAC(): HMACUtils {\n return this._hmac\n }\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this._crypto = crypto\n this._rsa = new RSAUtilsImpl(crypto)\n this._aes = new AESUtilsImpl(crypto)\n this._shamir = new WebcryptoShamir(crypto)\n this._hmac = new HMACUtilsImpl(crypto)\n }\n\n randomUuid() {\n return ((1e7).toString() + -1e3 + -4e3 + -8e3 + -1e11).replace(\n /[018]/g,\n //Keep next inlined or you will lose the random\n (c) => (Number(c) ^ ((this.crypto.getRandomValues(new Uint8Array(1))! as Uint8Array)[0] & (15 >> (Number(c) / 4)))).toString(16)\n )\n }\n\n sha256(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.crypto.subtle.digest('SHA-256', data)\n }\n\n randomBytes(n: number): Uint8Array {\n const res = new Uint8Array(n)\n this.crypto.getRandomValues(res)\n return res\n }\n}\n"]}
|
|
@@ -221,7 +221,7 @@ class DelegationsDeAnonymization {
|
|
|
221
221
|
// Usually either the delegator or delegate are the current data owner, but sometimes also the child of the delegator or delegate can do it.
|
|
222
222
|
const initialDelegates = [delegationMembersDetails.delegate, delegationMembersDetails.delegator, ...delegates].filter((x) => x != selfDoId);
|
|
223
223
|
const initalisedMapInfo = yield this.xapis.entityWithInitialisedEncryptedMetadata({
|
|
224
|
-
id: this.cryptoPrimitives.
|
|
224
|
+
id: this.cryptoPrimitives.randomUuid(),
|
|
225
225
|
delegate: delegationMembersDetails.delegate,
|
|
226
226
|
delegator: delegationMembersDetails.delegator,
|
|
227
227
|
delegationKey: delegationKey,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DelegationsDeAnonymization.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/DelegationsDeAnonymization.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,2EAAuE;AACvE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAEzD,gGAA4F;AAE5F,qEAAiE;AACjE,wFAAoF;AACpF,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAE3E,oCAAwE;AACxE,0GAAsG;AACtG,+CAA2C;AAC3C,2EAAiG;AACjG,yFAAiH;AAIjH,6CAA6C;AAC7C,MAAa,0BAA0B;IAIrC,YACmB,YAA8B,EAC9B,kCAA8E,EAC9E,KAAwB,EACxB,gBAAkC,EAClC,wBAAkD,EACnE,IAAY,EACZ,OAAkC,EAClC,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK,EACQ,gCAAkE;QAblE,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,uCAAkC,GAAlC,kCAAkC,CAA4C;QAC9E,UAAK,GAAL,KAAK,CAAmB;QACxB,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,6BAAwB,GAAxB,wBAAwB,CAA0B;QASlD,qCAAgC,GAAhC,gCAAgC,CAAkC;QAEnF,IAAI,CAAC,+BAA+B,GAAG,IAAA,4BAAoB,EAAC,CAAC,UAAU,EAAE,WAAW,CAAC,EAAE,wBA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B,EACD,UAAU,EACV,SAAS,EACT,SAAS,EACT,IAAI,EACJ,KAAK,EACL,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAC3E,CAAA;YACD,MAAM,eAAe,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,gBAAgB,CACvD,iBAAiB,CAAC,aAAa,EAC/B,UAAU,EACV,IAAI,CAAC,+BAA+B,EACpC,KAAK,EACL,IAAI,EACJ,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,+CAAsB,CAAC,CAAC,CAAC,CACrC,CAAA;YACD,MAAM,IAAI,CAAC,mBAAmB,CAAC,MAAM,CACnC,eAAe,EACf,IAAI,SAAG,CAAC,MAAM,CACZ,6DAA0B,EAC1B,MAAM,IAAI,CAAC,wBAAwB,CAAC,2BAA2B,CAAC,CAAC,wBAAwB,CAAC,mBAAmB,CAAC,EAAE,UAAU,CAAC,CAC5H,CACF,CAAA;QACH,CAAC;KAAA;CACF;AA3QD,gEA2QC","sourcesContent":["import { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { DelegationMembersDetails, SecureDelegationsSecurityMetadataDecryptor } from './SecureDelegationsSecurityMetadataDecryptor'\nimport { SecureDelegationKeyMap } from '../../icc-api/model/internal/SecureDelegationKeyMap'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedFieldsManifest, parseEncryptedFields } from '../utils'\nimport { IccSecureDelegationKeyMapApi } from '../../icc-api/api/internal/IccSecureDelegationKeyMapApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { AuthenticationProvider, NoAuthenticationProvider } from '../auth/AuthenticationProvider'\nimport { ACCESS_CONTROL_KEYS_HEADER, AccessControlKeysHeadersProvider } from './AccessControlKeysHeadersProvider'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\n\n// TODO could be optimised using bulk methods\nexport class DelegationsDeAnonymization {\n private readonly delegationKeyMapFieldsToEncrypt: EncryptedFieldsManifest\n private readonly delegationKeyMapApi: IccSecureDelegationKeyMapApi\n\n constructor(\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly secureDelegationsMetadataDecryptor: SecureDelegationsSecurityMetadataDecryptor,\n private readonly xapis: ExtendedApisUtils,\n private readonly cryptoPrimitives: CryptoPrimitives,\n private readonly accessControlSecretUtils: AccessControlSecretUtils,\n host: string,\n headers: { [key: string]: string },\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n private readonly accessControlKeysHeadersProvider: AccessControlKeysHeadersProvider\n ) {\n this.delegationKeyMapFieldsToEncrypt = parseEncryptedFields(['delegate', 'delegator'], 'SecureDelegationKeyMap')\n this.delegationKeyMapApi = new IccSecureDelegationKeyMapApi(host, headers, authenticationProvider, fetchImpl)\n }\n\n /**\n * Creates / updates information to allow the data owners in {@link shareWithDataOwners} to de-anonymize the delegations contained within\n * {@link entity}.\n * Note that the delegation de-anonymization information may be used also with other entities of the same type.\n */\n async createOrUpdateDeAnonymizationInfo(entityWithType: EncryptedEntityWithType, shareWithDataOwners: string[]) {\n const delegationsDetails = Object.entries(await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails(entityWithType)).flatMap(\n ([canonicalKey, delegation]) => {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [[canonicalKey, delegation], ...aliases.map((alias) => [alias, delegation])] as [string, DelegationMembersDetails][]\n }\n )\n const delegationsForDeanonInfoSharing = delegationsDetails.filter(([_, delegationInfo]) => {\n // Drop fully explicit ones: they don't need de-anonymization info\n return !delegationInfo.fullyExplicit\n })\n // A subset of delegations for which deanon info is relevant AND for which we can also create new info instead of sharing only existing one.\n const delegationsForNewDeanonInfoCreation = delegationsForDeanonInfoSharing.filter(([_, delegationInfo]) => {\n // Drop those for which we don't have the full information needed for the creation of new data.\n return !!delegationInfo.delegate && !!delegationInfo.delegator && !!delegationInfo.accessControlSecret\n })\n const existingDelegationsMap = await this.getDecryptedSecureDelegationKeyMaps(\n delegationsForDeanonInfoSharing.map((x) => x[0]),\n entityWithType.type\n )\n for (const delMapToShare of existingDelegationsMap) {\n await this.ensureDelegationKeyMapSharedWith(entityWithType.type, delMapToShare, shareWithDataOwners)\n }\n const existingDelegationsMapKeys = new Set(existingDelegationsMap.map((x) => x.delegationKey))\n const delegationsToCreate = delegationsForNewDeanonInfoCreation.filter(([k, _]) => !existingDelegationsMapKeys.has(k))\n for (const [delKey, membersDetails] of delegationsToCreate) {\n await this.createSecureDelegationKeyMap(entityWithType.type, delKey, membersDetails, shareWithDataOwners)\n }\n }\n\n /**\n * Get the data owners which can access the entity. See {@link EncryptedEntityXApi.getDataOwnersWithAccessTo} for more details.\n * @param entityWithType an entity.\n */\n async getDataOwnersWithAccessTo(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return this.mergePermissions([\n await this.getDataOwnersWithAccessToSecureDelegations(entityWithType),\n {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entityWithType.entity.delegations ?? {}).map((k) => [k, AccessLevelEnum.WRITE])),\n hasUnknownAnonymousDataOwners: false,\n },\n ])\n }\n\n private async getDataOwnersWithAccessToSecureDelegations(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const secureDelegationDetails = await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const secureDelegationWithUnknownMembers = Object.entries(secureDelegationDetails).flatMap(([canonicalKey, delegation]) => {\n if (!delegation.delegate || !delegation.delegator) {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [{ keys: [canonicalKey, ...aliases], delegation }]\n } else {\n return []\n }\n })\n const secureDelegationKeyMapsByDelegationKey = Object.fromEntries(\n (\n await this.getDecryptedSecureDelegationKeyMaps(\n secureDelegationWithUnknownMembers.flatMap(({ keys }) => keys),\n entityWithType.type\n )\n ).map((x) => [x.delegationKey, x])\n )\n const permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n function addAccess(dataOwnerId: string, level: AccessLevelEnum) {\n if (permissionsByDataOwnerId[dataOwnerId] !== AccessLevelEnum.WRITE) {\n permissionsByDataOwnerId[dataOwnerId] = level\n }\n }\n for (const delegation of Object.values(secureDelegationDetails)) {\n if (delegation.delegate) addAccess(delegation.delegate, delegation.accessLevel)\n if (delegation.delegator) addAccess(delegation.delegator, delegation.accessLevel)\n }\n for (const { keys, delegation } of secureDelegationWithUnknownMembers) {\n const bestKey = keys.find((k) => {\n const currMap = secureDelegationKeyMapsByDelegationKey[k]\n return currMap && !!currMap.delegator && !!currMap.delegate\n })\n if (bestKey) {\n const keyMap = secureDelegationKeyMapsByDelegationKey[bestKey]\n addAccess(keyMap.delegate!, delegation.accessLevel)\n addAccess(keyMap.delegator!, delegation.accessLevel)\n } else {\n hasUnknownAnonymousDataOwners = true\n }\n }\n return { permissionsByDataOwnerId, hasUnknownAnonymousDataOwners }\n }\n\n private async mergePermissions(\n values: {\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }[]\n ): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const accumulatedPermissions: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n for (const v of values) {\n hasUnknownAnonymousDataOwners = hasUnknownAnonymousDataOwners || v.hasUnknownAnonymousDataOwners\n for (const [dataOwnerId, level] of Object.entries(v.permissionsByDataOwnerId)) {\n if (accumulatedPermissions[dataOwnerId] !== AccessLevelEnum.WRITE) {\n accumulatedPermissions[dataOwnerId] = level\n }\n }\n }\n return {\n permissionsByDataOwnerId: accumulatedPermissions,\n hasUnknownAnonymousDataOwners,\n }\n }\n\n private async getDecryptedSecureDelegationKeyMaps(\n delegationIds: string[],\n entityType: EntityWithDelegationTypeName\n ): Promise<SecureDelegationKeyMap[]> {\n if (delegationIds.length) {\n const encryptedMaps = await this.delegationKeyMapApi.getByDelegationKeys(\n { ids: delegationIds },\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n const res: SecureDelegationKeyMap[] = []\n for (const encryptedMap of encryptedMaps) {\n // Use the original entity type\n const decryptionResult = await this.xapis.decryptEntity(encryptedMap, entityType, (x) => new SecureDelegationKeyMap(x))\n if (decryptionResult.decrypted) {\n res.push(decryptionResult.entity)\n }\n }\n return res\n } else return []\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async ensureDelegationKeyMapSharedWith(entityType: EntityWithDelegationTypeName, keyMap: SecureDelegationKeyMap, delegates: string[]) {\n if (!keyMap.delegator || !keyMap.delegate) throw new Error('Illegal state: key map is missing delegator or delegate info.')\n const dataOwnersWithAccessToMapThroughDelegation = Object.values(\n await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails({\n type: entityType,\n entity: keyMap,\n })\n )\n .flatMap((x) => [x.delegate, x.delegator])\n .filter((x) => !!x) as string[]\n // Delegator and delegate got access to the entity when it was first created: no need to share with them ever.\n const dataOwnersWithAccessToMap = new Set([keyMap.delegate, keyMap.delegator, ...dataOwnersWithAccessToMapThroughDelegation])\n const dataOwnersNeedingShare = delegates.filter((x) => !dataOwnersWithAccessToMap.has(x))\n if (dataOwnersNeedingShare.length) {\n ;(\n await this.xapis.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity: keyMap, type: entityType },\n false,\n Object.fromEntries(\n dataOwnersNeedingShare.map((x) => [\n x,\n {\n shareSecretIds: [],\n shareEncryptionKeys: ShareMetadataBehaviour.REQUIRED,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n requestedPermissions: RequestedPermissionEnum.FULL_READ,\n },\n ])\n ),\n async (request) =>\n this.delegationKeyMapApi.bulkShareSecureDelegationKeyMap(\n request,\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n )\n ).updatedEntityOrThrow\n }\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async createSecureDelegationKeyMap(\n entityType: EntityWithDelegationTypeName,\n delegationKey: string,\n delegationMembersDetails: DelegationMembersDetails,\n delegates: string[]\n ) {\n if (!delegationMembersDetails.delegate || !delegationMembersDetails.delegator || !delegationMembersDetails.accessControlSecret)\n throw new Error('Illegal state: delegation members details are missing delegate, delegator or access control secret info.')\n const selfDoId = await this.dataOwnerApi.getCurrentDataOwnerId()\n // Ensure that both the delegator and delegate of the delegation this map refers tho can share it later on, even if they did not create it.\n // Usually either the delegator or delegate are the current data owner, but sometimes also the child of the delegator or delegate can do it.\n const initialDelegates = [delegationMembersDetails.delegate, delegationMembersDetails.delegator, ...delegates].filter((x) => x != selfDoId)\n const initalisedMapInfo = await this.xapis.entityWithInitialisedEncryptedMetadata<SecureDelegationKeyMap>(\n {\n id: this.cryptoPrimitives.crypto.randomUUID(),\n delegate: delegationMembersDetails.delegate,\n delegator: delegationMembersDetails.delegator,\n delegationKey: delegationKey,\n },\n entityType,\n undefined,\n undefined,\n true,\n false,\n Object.fromEntries(initialDelegates.map((x) => [x, AccessLevelEnum.READ]))\n )\n const encryptedKeyMap = await this.xapis.tryEncryptEntity(\n initalisedMapInfo.updatedEntity,\n entityType,\n this.delegationKeyMapFieldsToEncrypt,\n false,\n true,\n (x) => new SecureDelegationKeyMap(x)\n )\n await this.delegationKeyMapApi.create(\n encryptedKeyMap,\n new XHR.Header(\n ACCESS_CONTROL_KEYS_HEADER,\n await this.accessControlSecretUtils.getEncodedAccessControlKeys([delegationMembersDetails.accessControlSecret], entityType)\n )\n )\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"DelegationsDeAnonymization.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/DelegationsDeAnonymization.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,2EAAuE;AACvE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAEzD,gGAA4F;AAE5F,qEAAiE;AACjE,wFAAoF;AACpF,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAE3E,oCAAwE;AACxE,0GAAsG;AACtG,+CAA2C;AAC3C,2EAAiG;AACjG,yFAAiH;AAIjH,6CAA6C;AAC7C,MAAa,0BAA0B;IAIrC,YACmB,YAA8B,EAC9B,kCAA8E,EAC9E,KAAwB,EACxB,gBAAkC,EAClC,wBAAkD,EACnE,IAAY,EACZ,OAAkC,EAClC,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CA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AC,SAAS,EAAE,GAAG,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,QAAQ,CAAC,CAAA;YAC3I,MAAM,iBAAiB,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,sCAAsC,CAC/E;gBACE,EAAE,EAAE,IAAI,CAAC,gBAAgB,CAAC,UAAU,EAAE;gBACtC,QAAQ,EAAE,wBAAwB,CAAC,QAAQ;gBAC3C,SAAS,EAAE,wBAAwB,CAAC,SAAS;gBAC7C,aAAa,EAAE,aAAa;aAC7B,EACD,UAAU,EACV,SAAS,EACT,SAAS,EACT,IAAI,EACJ,KAAK,EACL,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAC3E,CAAA;YACD,MAAM,eAAe,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,gBAAgB,CACvD,iBAAiB,CAAC,aAAa,EAC/B,UAAU,EACV,IAAI,CAAC,+BAA+B,EACpC,KAAK,EACL,IAAI,EACJ,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,+CAAsB,CAAC,CAAC,CAAC,CACrC,CAAA;YACD,MAAM,IAAI,CAAC,mBAAmB,CAAC,MAAM,CACnC,eAAe,EACf,IAAI,SAAG,CAAC,MAAM,CACZ,6DAA0B,EAC1B,MAAM,IAAI,CAAC,wBAAwB,CAAC,2BAA2B,CAAC,CAAC,wBAAwB,CAAC,mBAAmB,CAAC,EAAE,UAAU,CAAC,CAC5H,CACF,CAAA;QACH,CAAC;KAAA;CACF;AA3QD,gEA2QC","sourcesContent":["import { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { DelegationMembersDetails, SecureDelegationsSecurityMetadataDecryptor } from './SecureDelegationsSecurityMetadataDecryptor'\nimport { SecureDelegationKeyMap } from '../../icc-api/model/internal/SecureDelegationKeyMap'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedFieldsManifest, parseEncryptedFields } from '../utils'\nimport { IccSecureDelegationKeyMapApi } from '../../icc-api/api/internal/IccSecureDelegationKeyMapApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { AuthenticationProvider, NoAuthenticationProvider } from '../auth/AuthenticationProvider'\nimport { ACCESS_CONTROL_KEYS_HEADER, AccessControlKeysHeadersProvider } from './AccessControlKeysHeadersProvider'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\n\n// TODO could be optimised using bulk methods\nexport class DelegationsDeAnonymization {\n private readonly delegationKeyMapFieldsToEncrypt: EncryptedFieldsManifest\n private readonly delegationKeyMapApi: IccSecureDelegationKeyMapApi\n\n constructor(\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly secureDelegationsMetadataDecryptor: SecureDelegationsSecurityMetadataDecryptor,\n private readonly xapis: ExtendedApisUtils,\n private readonly cryptoPrimitives: CryptoPrimitives,\n private readonly accessControlSecretUtils: AccessControlSecretUtils,\n host: string,\n headers: { [key: string]: string },\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n private readonly accessControlKeysHeadersProvider: AccessControlKeysHeadersProvider\n ) {\n this.delegationKeyMapFieldsToEncrypt = parseEncryptedFields(['delegate', 'delegator'], 'SecureDelegationKeyMap')\n this.delegationKeyMapApi = new IccSecureDelegationKeyMapApi(host, headers, authenticationProvider, fetchImpl)\n }\n\n /**\n * Creates / updates information to allow the data owners in {@link shareWithDataOwners} to de-anonymize the delegations contained within\n * {@link entity}.\n * Note that the delegation de-anonymization information may be used also with other entities of the same type.\n */\n async createOrUpdateDeAnonymizationInfo(entityWithType: EncryptedEntityWithType, shareWithDataOwners: string[]) {\n const delegationsDetails = Object.entries(await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails(entityWithType)).flatMap(\n ([canonicalKey, delegation]) => {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [[canonicalKey, delegation], ...aliases.map((alias) => [alias, delegation])] as [string, DelegationMembersDetails][]\n }\n )\n const delegationsForDeanonInfoSharing = delegationsDetails.filter(([_, delegationInfo]) => {\n // Drop fully explicit ones: they don't need de-anonymization info\n return !delegationInfo.fullyExplicit\n })\n // A subset of delegations for which deanon info is relevant AND for which we can also create new info instead of sharing only existing one.\n const delegationsForNewDeanonInfoCreation = delegationsForDeanonInfoSharing.filter(([_, delegationInfo]) => {\n // Drop those for which we don't have the full information needed for the creation of new data.\n return !!delegationInfo.delegate && !!delegationInfo.delegator && !!delegationInfo.accessControlSecret\n })\n const existingDelegationsMap = await this.getDecryptedSecureDelegationKeyMaps(\n delegationsForDeanonInfoSharing.map((x) => x[0]),\n entityWithType.type\n )\n for (const delMapToShare of existingDelegationsMap) {\n await this.ensureDelegationKeyMapSharedWith(entityWithType.type, delMapToShare, shareWithDataOwners)\n }\n const existingDelegationsMapKeys = new Set(existingDelegationsMap.map((x) => x.delegationKey))\n const delegationsToCreate = delegationsForNewDeanonInfoCreation.filter(([k, _]) => !existingDelegationsMapKeys.has(k))\n for (const [delKey, membersDetails] of delegationsToCreate) {\n await this.createSecureDelegationKeyMap(entityWithType.type, delKey, membersDetails, shareWithDataOwners)\n }\n }\n\n /**\n * Get the data owners which can access the entity. See {@link EncryptedEntityXApi.getDataOwnersWithAccessTo} for more details.\n * @param entityWithType an entity.\n */\n async getDataOwnersWithAccessTo(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return this.mergePermissions([\n await this.getDataOwnersWithAccessToSecureDelegations(entityWithType),\n {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entityWithType.entity.delegations ?? {}).map((k) => [k, AccessLevelEnum.WRITE])),\n hasUnknownAnonymousDataOwners: false,\n },\n ])\n }\n\n private async getDataOwnersWithAccessToSecureDelegations(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const secureDelegationDetails = await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const secureDelegationWithUnknownMembers = Object.entries(secureDelegationDetails).flatMap(([canonicalKey, delegation]) => {\n if (!delegation.delegate || !delegation.delegator) {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [{ keys: [canonicalKey, ...aliases], delegation }]\n } else {\n return []\n }\n })\n const secureDelegationKeyMapsByDelegationKey = Object.fromEntries(\n (\n await this.getDecryptedSecureDelegationKeyMaps(\n secureDelegationWithUnknownMembers.flatMap(({ keys }) => keys),\n entityWithType.type\n )\n ).map((x) => [x.delegationKey, x])\n )\n const permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n function addAccess(dataOwnerId: string, level: AccessLevelEnum) {\n if (permissionsByDataOwnerId[dataOwnerId] !== AccessLevelEnum.WRITE) {\n permissionsByDataOwnerId[dataOwnerId] = level\n }\n }\n for (const delegation of Object.values(secureDelegationDetails)) {\n if (delegation.delegate) addAccess(delegation.delegate, delegation.accessLevel)\n if (delegation.delegator) addAccess(delegation.delegator, delegation.accessLevel)\n }\n for (const { keys, delegation } of secureDelegationWithUnknownMembers) {\n const bestKey = keys.find((k) => {\n const currMap = secureDelegationKeyMapsByDelegationKey[k]\n return currMap && !!currMap.delegator && !!currMap.delegate\n })\n if (bestKey) {\n const keyMap = secureDelegationKeyMapsByDelegationKey[bestKey]\n addAccess(keyMap.delegate!, delegation.accessLevel)\n addAccess(keyMap.delegator!, delegation.accessLevel)\n } else {\n hasUnknownAnonymousDataOwners = true\n }\n }\n return { permissionsByDataOwnerId, hasUnknownAnonymousDataOwners }\n }\n\n private async mergePermissions(\n values: {\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }[]\n ): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const accumulatedPermissions: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n for (const v of values) {\n hasUnknownAnonymousDataOwners = hasUnknownAnonymousDataOwners || v.hasUnknownAnonymousDataOwners\n for (const [dataOwnerId, level] of Object.entries(v.permissionsByDataOwnerId)) {\n if (accumulatedPermissions[dataOwnerId] !== AccessLevelEnum.WRITE) {\n accumulatedPermissions[dataOwnerId] = level\n }\n }\n }\n return {\n permissionsByDataOwnerId: accumulatedPermissions,\n hasUnknownAnonymousDataOwners,\n }\n }\n\n private async getDecryptedSecureDelegationKeyMaps(\n delegationIds: string[],\n entityType: EntityWithDelegationTypeName\n ): Promise<SecureDelegationKeyMap[]> {\n if (delegationIds.length) {\n const encryptedMaps = await this.delegationKeyMapApi.getByDelegationKeys(\n { ids: delegationIds },\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n const res: SecureDelegationKeyMap[] = []\n for (const encryptedMap of encryptedMaps) {\n // Use the original entity type\n const decryptionResult = await this.xapis.decryptEntity(encryptedMap, entityType, (x) => new SecureDelegationKeyMap(x))\n if (decryptionResult.decrypted) {\n res.push(decryptionResult.entity)\n }\n }\n return res\n } else return []\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async ensureDelegationKeyMapSharedWith(entityType: EntityWithDelegationTypeName, keyMap: SecureDelegationKeyMap, delegates: string[]) {\n if (!keyMap.delegator || !keyMap.delegate) throw new Error('Illegal state: key map is missing delegator or delegate info.')\n const dataOwnersWithAccessToMapThroughDelegation = Object.values(\n await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails({\n type: entityType,\n entity: keyMap,\n })\n )\n .flatMap((x) => [x.delegate, x.delegator])\n .filter((x) => !!x) as string[]\n // Delegator and delegate got access to the entity when it was first created: no need to share with them ever.\n const dataOwnersWithAccessToMap = new Set([keyMap.delegate, keyMap.delegator, ...dataOwnersWithAccessToMapThroughDelegation])\n const dataOwnersNeedingShare = delegates.filter((x) => !dataOwnersWithAccessToMap.has(x))\n if (dataOwnersNeedingShare.length) {\n ;(\n await this.xapis.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity: keyMap, type: entityType },\n false,\n Object.fromEntries(\n dataOwnersNeedingShare.map((x) => [\n x,\n {\n shareSecretIds: [],\n shareEncryptionKeys: ShareMetadataBehaviour.REQUIRED,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n requestedPermissions: RequestedPermissionEnum.FULL_READ,\n },\n ])\n ),\n async (request) =>\n this.delegationKeyMapApi.bulkShareSecureDelegationKeyMap(\n request,\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n )\n ).updatedEntityOrThrow\n }\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async createSecureDelegationKeyMap(\n entityType: EntityWithDelegationTypeName,\n delegationKey: string,\n delegationMembersDetails: DelegationMembersDetails,\n delegates: string[]\n ) {\n if (!delegationMembersDetails.delegate || !delegationMembersDetails.delegator || !delegationMembersDetails.accessControlSecret)\n throw new Error('Illegal state: delegation members details are missing delegate, delegator or access control secret info.')\n const selfDoId = await this.dataOwnerApi.getCurrentDataOwnerId()\n // Ensure that both the delegator and delegate of the delegation this map refers tho can share it later on, even if they did not create it.\n // Usually either the delegator or delegate are the current data owner, but sometimes also the child of the delegator or delegate can do it.\n const initialDelegates = [delegationMembersDetails.delegate, delegationMembersDetails.delegator, ...delegates].filter((x) => x != selfDoId)\n const initalisedMapInfo = await this.xapis.entityWithInitialisedEncryptedMetadata<SecureDelegationKeyMap>(\n {\n id: this.cryptoPrimitives.randomUuid(),\n delegate: delegationMembersDetails.delegate,\n delegator: delegationMembersDetails.delegator,\n delegationKey: delegationKey,\n },\n entityType,\n undefined,\n undefined,\n true,\n false,\n Object.fromEntries(initialDelegates.map((x) => [x, AccessLevelEnum.READ]))\n )\n const encryptedKeyMap = await this.xapis.tryEncryptEntity(\n initalisedMapInfo.updatedEntity,\n entityType,\n this.delegationKeyMapFieldsToEncrypt,\n false,\n true,\n (x) => new SecureDelegationKeyMap(x)\n )\n await this.delegationKeyMapApi.create(\n encryptedKeyMap,\n new XHR.Header(\n ACCESS_CONTROL_KEYS_HEADER,\n await this.accessControlSecretUtils.getEncodedAccessControlKeys([delegationMembersDetails.accessControlSecret], entityType)\n )\n )\n }\n}\n"]}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
export
|
|
1
|
+
export interface HMACUtils {
|
|
2
|
+
generateKey(): Promise<CryptoKey>;
|
|
3
|
+
exportKey(key: CryptoKey): Promise<ArrayBuffer>;
|
|
4
|
+
importKey(key: ArrayBuffer): Promise<CryptoKey>;
|
|
5
|
+
sign(key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
|
|
6
|
+
verify(key: CryptoKey, data: ArrayBuffer, signature: ArrayBuffer): Promise<boolean>;
|
|
7
|
+
}
|
|
8
|
+
export declare class HMACUtilsImpl implements HMACUtils {
|
|
2
9
|
private readonly _crypto;
|
|
3
10
|
private readonly recommendedKeyLengthBytes;
|
|
4
11
|
private readonly params;
|
|
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.
|
|
13
|
-
class
|
|
12
|
+
exports.HMACUtilsImpl = void 0;
|
|
13
|
+
class HMACUtilsImpl {
|
|
14
14
|
constructor(crypto) {
|
|
15
15
|
this.recommendedKeyLengthBytes = 128;
|
|
16
16
|
this.params = {
|
|
@@ -54,5 +54,5 @@ class HMACUtils {
|
|
|
54
54
|
});
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
|
-
exports.
|
|
57
|
+
exports.HMACUtilsImpl = HMACUtilsImpl;
|
|
58
58
|
//# sourceMappingURL=HMACUtils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HMACUtils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/HMACUtils.ts"],"names":[],"mappings":";;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"HMACUtils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/HMACUtils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAQA,MAAa,aAAa;IASxB,YAAY,MAAc;QAPT,8BAAyB,GAAG,GAAG,CAAA;QAC/B,WAAM,GAAqB;YAC1C,IAAI,EAAE,MAAM;YACZ,IAAI,EAAE,SAAS;YACf,MAAM,EAAE,IAAI,CAAC,yBAAyB,GAAG,CAAC,EAAE,uFAAuF;SACpI,CAAA;QAGC,IAAI,CAAC,OAAO,GAAG,MAAM,CAAA;IACvB,CAAC;IAEK,WAAW;;YACf,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW,mBAAM,IAAI,C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AAE,SAAS,EAAE,IAAI,CAAC,CAAA;QAC7E,CAAC;KAAA;CACF;AAxCD,sCAwCC","sourcesContent":["export interface HMACUtils {\n generateKey(): Promise<CryptoKey>\n exportKey(key: CryptoKey): Promise<ArrayBuffer>\n importKey(key: ArrayBuffer): Promise<CryptoKey>\n sign(key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>\n verify(key: CryptoKey, data: ArrayBuffer, signature: ArrayBuffer): Promise<boolean>\n}\n\nexport class HMACUtilsImpl implements HMACUtils {\n private readonly _crypto: Crypto\n private readonly recommendedKeyLengthBytes = 128\n private readonly params: HmacKeyGenParams = {\n name: 'HMAC',\n hash: 'SHA-512',\n length: this.recommendedKeyLengthBytes * 8, // Recommended length in bits. Adding this because not all implementations behave well.\n }\n\n constructor(crypto: Crypto) {\n this._crypto = crypto\n }\n\n async generateKey(): Promise<CryptoKey> {\n const generatedKey = await this._crypto.subtle.generateKey({ ...this.params }, true, ['sign', 'verify'])\n const exportedKey = await this._crypto.subtle.exportKey('raw', generatedKey)\n if (exportedKey.byteLength !== this.recommendedKeyLengthBytes) {\n throw new Error(`Generated key has unexpected length - expected ${this.recommendedKeyLengthBytes} bytes, got ${exportedKey.byteLength} bytes`)\n }\n return generatedKey\n }\n\n async exportKey(key: CryptoKey): Promise<ArrayBuffer> {\n return this._crypto.subtle.exportKey('raw', key)\n }\n\n async importKey(key: ArrayBuffer): Promise<CryptoKey> {\n if (key.byteLength !== this.recommendedKeyLengthBytes) {\n throw new Error(`Key has unexpected length - expected ${this.recommendedKeyLengthBytes} bytes, got ${key.byteLength} bytes`)\n }\n return this._crypto.subtle.importKey('raw', key, { ...this.params }, true, ['sign', 'verify'])\n }\n\n async sign(key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer> {\n return this._crypto.subtle.sign({ ...this.params }, key, data)\n }\n\n async verify(key: CryptoKey, data: ArrayBuffer, signature: ArrayBuffer): Promise<boolean> {\n return this._crypto.subtle.verify({ ...this.params }, key, signature, data)\n }\n}\n"]}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { CryptoPrimitives } from './CryptoPrimitives';
|
|
2
|
+
import { HMACUtils } from './HMACUtils';
|
|
3
|
+
import { ShamirClass } from './shamir';
|
|
4
|
+
import { AESUtils } from './AES';
|
|
5
|
+
import { RSAUtils } from './RSA';
|
|
6
|
+
/**
|
|
7
|
+
* Allows to use the expo-kryptom module as crypto primitives. This is necessary when building expo (react native) apps.
|
|
8
|
+
*/
|
|
9
|
+
export declare class NativeCryptoPrimitivesBridge implements CryptoPrimitives {
|
|
10
|
+
constructor(expoKryptomModule: {
|
|
11
|
+
Aes: AesService;
|
|
12
|
+
Rsa: RsaService;
|
|
13
|
+
Hmac: HmacService;
|
|
14
|
+
StrongRandom: StrongRandomService;
|
|
15
|
+
Digest: DigestService;
|
|
16
|
+
});
|
|
17
|
+
readonly AES: AESUtils;
|
|
18
|
+
readonly HMAC: HMACUtils;
|
|
19
|
+
readonly RSA: RSAUtils;
|
|
20
|
+
readonly shamir: ShamirClass;
|
|
21
|
+
private readonly strongRandom;
|
|
22
|
+
private readonly digest;
|
|
23
|
+
randomBytes(n: number): Uint8Array;
|
|
24
|
+
randomUuid(): string;
|
|
25
|
+
sha256(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>;
|
|
26
|
+
}
|
|
27
|
+
declare enum AesAlgorithm {
|
|
28
|
+
AesCbcPkcs7 = "AesCbcPkcs7"
|
|
29
|
+
}
|
|
30
|
+
declare enum RsaEncryptionAlgorithm {
|
|
31
|
+
OaepWithSha1 = "OaepWithSha1",
|
|
32
|
+
OaepWithSha256 = "OaepWithSha256"
|
|
33
|
+
}
|
|
34
|
+
declare enum RsaSignatureAlgorithm {
|
|
35
|
+
PssWithSha256 = "PssWithSha256"
|
|
36
|
+
}
|
|
37
|
+
type RsaAlgorithm = RsaEncryptionAlgorithm | RsaSignatureAlgorithm;
|
|
38
|
+
declare enum HmacAlgorithm {
|
|
39
|
+
HmacSha512 = "HmacSha512"
|
|
40
|
+
}
|
|
41
|
+
interface HmacKey {
|
|
42
|
+
algorithmIdentifier: HmacAlgorithm;
|
|
43
|
+
}
|
|
44
|
+
interface AesKey {
|
|
45
|
+
algorithmIdentifier: AesAlgorithm;
|
|
46
|
+
}
|
|
47
|
+
interface RsaKeyPair {
|
|
48
|
+
algorithmIdentifier: RsaAlgorithm;
|
|
49
|
+
}
|
|
50
|
+
interface RsaPrivateKey {
|
|
51
|
+
algorithmIdentifier: RsaAlgorithm;
|
|
52
|
+
}
|
|
53
|
+
interface RsaPublicKey {
|
|
54
|
+
algorithmIdentifier: RsaAlgorithm;
|
|
55
|
+
}
|
|
56
|
+
type PrivateRsaKeyJwk = {
|
|
57
|
+
alg: string;
|
|
58
|
+
d: string;
|
|
59
|
+
dp: string;
|
|
60
|
+
dq: string;
|
|
61
|
+
e: string;
|
|
62
|
+
ext: boolean;
|
|
63
|
+
key_ops: string[];
|
|
64
|
+
n: string;
|
|
65
|
+
p: string;
|
|
66
|
+
q: string;
|
|
67
|
+
qi: string;
|
|
68
|
+
};
|
|
69
|
+
type PublicRsaKeyJwk = {
|
|
70
|
+
alg: string;
|
|
71
|
+
e: string;
|
|
72
|
+
ext: boolean;
|
|
73
|
+
key_ops: string[];
|
|
74
|
+
n: string;
|
|
75
|
+
};
|
|
76
|
+
interface AesService {
|
|
77
|
+
generateKey(algorithmIdentifier: AesAlgorithm, size: number): Promise<AesKey>;
|
|
78
|
+
encrypt(data: Uint8Array, key: AesKey, iv: Uint8Array | null): Promise<Uint8Array>;
|
|
79
|
+
decrypt(ivAndEncryptedData: Uint8Array, key: AesKey): Promise<Uint8Array>;
|
|
80
|
+
exportRawKey(key: AesKey): Promise<Uint8Array>;
|
|
81
|
+
importRawKey(rawKey: Uint8Array, algorithmIdentifier: AesAlgorithm): Promise<AesKey>;
|
|
82
|
+
}
|
|
83
|
+
interface RsaService {
|
|
84
|
+
generateKey(algorithmIdentifier: RsaAlgorithm, size: number): Promise<RsaKeyPair>;
|
|
85
|
+
encrypt(data: Uint8Array, key: RsaPublicKey): Promise<Uint8Array>;
|
|
86
|
+
decrypt(data: Uint8Array, key: RsaPrivateKey): Promise<Uint8Array>;
|
|
87
|
+
signature(data: Uint8Array, key: RsaPrivateKey): Promise<Uint8Array>;
|
|
88
|
+
verify(signature: Uint8Array, data: Uint8Array, key: RsaPublicKey): Promise<boolean>;
|
|
89
|
+
exportPrivateKeyPkcs8(key: RsaPrivateKey): Promise<Uint8Array>;
|
|
90
|
+
exportPrivateKeyJwk(key: RsaPrivateKey): Promise<PrivateRsaKeyJwk>;
|
|
91
|
+
exportPublicKeySpki(key: RsaPublicKey): Promise<Uint8Array>;
|
|
92
|
+
exportPublicKeyJwk(key: RsaPublicKey): Promise<PublicRsaKeyJwk>;
|
|
93
|
+
importPrivateKeyPkcs8(privateKeyPkcs8: Uint8Array, algorithmIdentifier: RsaAlgorithm): Promise<RsaPrivateKey>;
|
|
94
|
+
importPrivateKeyJwk(privateKey: PrivateRsaKeyJwk, algorithmIdentifier: RsaAlgorithm): Promise<RsaPrivateKey>;
|
|
95
|
+
importPublicKeySpki(publicKeySpki: Uint8Array, algorithmIdentifier: RsaAlgorithm): Promise<RsaPublicKey>;
|
|
96
|
+
importPublicKeyJwk(publicKey: PublicRsaKeyJwk, algorithmIdentifier: RsaAlgorithm): Promise<RsaPublicKey>;
|
|
97
|
+
importKeyPair(privateKeyPkcs8: Uint8Array, algorithmIdentifier: RsaAlgorithm): Promise<RsaKeyPair>;
|
|
98
|
+
}
|
|
99
|
+
interface HmacService {
|
|
100
|
+
generateKey(algorithmIdentifier: HmacAlgorithm): Promise<HmacKey>;
|
|
101
|
+
sign(data: Uint8Array, key: HmacKey): Promise<Uint8Array>;
|
|
102
|
+
verify(signature: Uint8Array, data: Uint8Array, key: HmacKey): Promise<boolean>;
|
|
103
|
+
exportRawKey(key: HmacKey): Promise<Uint8Array>;
|
|
104
|
+
importRawKey(rawKey: Uint8Array, algorithmIdentifier: HmacAlgorithm): Promise<HmacKey>;
|
|
105
|
+
}
|
|
106
|
+
interface StrongRandomService {
|
|
107
|
+
randomBytes(length: number): Uint8Array;
|
|
108
|
+
randomUUID(): string;
|
|
109
|
+
}
|
|
110
|
+
interface DigestService {
|
|
111
|
+
sha256(data: Uint8Array): Promise<Uint8Array>;
|
|
112
|
+
}
|
|
113
|
+
export {};
|