@icure/api 8.6.2 → 8.6.4
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-api/model/ModelHelper.d.ts +1 -1
- package/icc-api/model/ModelHelper.js +15 -2
- package/icc-api/model/ModelHelper.js.map +1 -1
- package/icc-api/model/User.d.ts +1 -0
- package/icc-api/model/User.js.map +1 -1
- package/icc-x-api/crypto/AES.js +1 -1
- package/icc-x-api/crypto/AES.js.map +1 -1
- package/icc-x-api/crypto/BaseExchangeDataManager.js +14 -14
- package/icc-x-api/crypto/BaseExchangeDataManager.js.map +1 -1
- package/icc-x-api/crypto/BaseExchangeKeysManager.js +1 -1
- package/icc-x-api/crypto/BaseExchangeKeysManager.js.map +1 -1
- package/icc-x-api/crypto/CryptoPrimitives.js +3 -2
- package/icc-x-api/crypto/CryptoPrimitives.js.map +1 -1
- package/icc-x-api/crypto/ExchangeDataManager.js +3 -3
- package/icc-x-api/crypto/ExchangeDataManager.js.map +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
- package/icc-x-api/crypto/KeyRecovery.js +3 -3
- package/icc-x-api/crypto/KeyRecovery.js.map +1 -1
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.js +13 -13
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.js.map +1 -1
- package/icc-x-api/crypto/RSA.js +2 -2
- package/icc-x-api/crypto/RSA.js.map +1 -1
- package/icc-x-api/crypto/RecoveryDataEncryption.js +5 -5
- package/icc-x-api/crypto/RecoveryDataEncryption.js.map +1 -1
- package/icc-x-api/crypto/SecureDelegationsManager.js +1 -1
- package/icc-x-api/crypto/SecureDelegationsManager.js.map +1 -1
- package/icc-x-api/crypto/ShamirKeysManager.js +1 -1
- package/icc-x-api/crypto/ShamirKeysManager.js.map +1 -1
- package/icc-x-api/crypto/utils.js +1 -1
- package/icc-x-api/crypto/utils.js.map +1 -1
- package/icc-x-api/filters/HealthElementByHcPartyCodeFilter.d.ts +24 -0
- package/icc-x-api/filters/HealthElementByHcPartyCodeFilter.js +24 -0
- package/icc-x-api/filters/HealthElementByHcPartyCodeFilter.js.map +1 -0
- package/icc-x-api/filters/HealthElementByHcPartyIdentifiersVersioningFilter.d.ts +22 -0
- package/icc-x-api/filters/HealthElementByHcPartyIdentifiersVersioningFilter.js +24 -0
- package/icc-x-api/filters/HealthElementByHcPartyIdentifiersVersioningFilter.js.map +1 -0
- package/icc-x-api/filters/HealthElementByHcPartyStatusVersioningFilter.d.ts +21 -0
- package/icc-x-api/filters/HealthElementByHcPartyStatusVersioningFilter.js +24 -0
- package/icc-x-api/filters/HealthElementByHcPartyStatusVersioningFilter.js.map +1 -0
- package/icc-x-api/filters/HealthElementByHcPartyTagFilter.d.ts +24 -0
- package/icc-x-api/filters/HealthElementByHcPartyTagFilter.js +24 -0
- package/icc-x-api/filters/HealthElementByHcPartyTagFilter.js.map +1 -0
- package/icc-x-api/filters/VersionFiltering.d.ts +14 -0
- package/icc-x-api/filters/VersionFiltering.js +19 -0
- package/icc-x-api/filters/VersionFiltering.js.map +1 -0
- package/icc-x-api/filters/filters.d.ts +8 -4
- package/icc-x-api/filters/filters.js +4 -0
- package/icc-x-api/filters/filters.js.map +1 -1
- package/icc-x-api/icc-receipt-x-api.js +1 -1
- package/icc-x-api/icc-receipt-x-api.js.map +1 -1
- package/icc-x-api/index.d.ts +9 -6
- package/icc-x-api/index.js +4 -0
- package/icc-x-api/index.js.map +1 -1
- package/icc-x-api/utils/binary-utils.js +1 -1
- package/icc-x-api/utils/binary-utils.js.map +1 -1
- package/package.json +1 -1
- package/test/icc-api/api/IccAnonymousAccessApi.js +1 -1
- package/test/icc-api/api/IccAnonymousAccessApi.js.map +1 -1
- package/test/icc-api/api/IccDocumentApi.js +13 -12
- package/test/icc-api/api/IccDocumentApi.js.map +1 -1
- package/test/icc-x-api/crud/comprehensive-crud-test.js +2 -2
- package/test/icc-x-api/crud/comprehensive-crud-test.js.map +1 -1
- package/test/icc-x-api/crypto/crypto-utils.js +1 -1
- package/test/icc-x-api/crypto/crypto-utils.js.map +1 -1
- package/test/icc-x-api/crypto/soft-deleted-data-owners.js +1 -1
- package/test/icc-x-api/crypto/soft-deleted-data-owners.js.map +1 -1
- package/test/icc-x-api/crypto/user-encryption-keys-manager-test.js +1 -1
- package/test/icc-x-api/crypto/user-encryption-keys-manager-test.js.map +1 -1
- package/test/icc-x-api/filters/healthelement.d.ts +1 -0
- package/test/icc-x-api/filters/healthelement.js +333 -0
- package/test/icc-x-api/filters/healthelement.js.map +1 -0
- package/test/icc-x-api/test-legacy-data-support.js +4 -4
- package/test/icc-x-api/test-legacy-data-support.js.map +1 -1
- package/test/utils/TestCryptoStrategies.js +1 -1
- package/test/utils/TestCryptoStrategies.js.map +1 -1
- package/test/utils/roles.d.ts +1 -0
- package/test/utils/roles.js +1 -0
- package/test/utils/roles.js.map +1 -1
- package/test/utils/test_utils.js +2 -2
- package/test/utils/test_utils.js.map +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export declare function ua2string(_ua: Uint8Array | ArrayBuffer): string;
|
|
2
2
|
export declare function string2ua(s: string): Uint8Array;
|
|
3
3
|
export declare function string2ab(s: string): ArrayBuffer;
|
|
4
|
-
export declare function ua2ab(ua: Uint8Array): ArrayBuffer;
|
|
4
|
+
export declare function ua2ab(ua: ArrayBuffer | Uint8Array): ArrayBuffer;
|
|
5
5
|
export declare function decodeStringOrArrayBuffer(value: string | ArrayBuffer): ArrayBuffer;
|
|
6
6
|
export declare function b64_2ab(s: string): ArrayBuffer;
|
|
7
7
|
export declare function b64_2ua(s: string): Uint8Array;
|
|
@@ -33,9 +33,22 @@ function string2ua(s) {
|
|
|
33
33
|
function string2ab(s) {
|
|
34
34
|
return ua2ab(string2ua(s));
|
|
35
35
|
}
|
|
36
|
+
// Get an array buffer matching the content of the input, copying only when necessary
|
|
36
37
|
function ua2ab(ua) {
|
|
37
|
-
|
|
38
|
-
|
|
38
|
+
if (ua instanceof ArrayBuffer)
|
|
39
|
+
return ua;
|
|
40
|
+
const { buffer, byteOffset, byteLength } = ua;
|
|
41
|
+
if (buffer instanceof ArrayBuffer) {
|
|
42
|
+
if (byteOffset === 0 && byteLength === buffer.byteLength) {
|
|
43
|
+
// zero-copy fast path
|
|
44
|
+
return buffer;
|
|
45
|
+
}
|
|
46
|
+
return buffer.slice(byteOffset, byteOffset + byteLength);
|
|
47
|
+
}
|
|
48
|
+
// buffer is SharedArrayBuffer → must copy
|
|
49
|
+
const copy = new Uint8Array(byteLength);
|
|
50
|
+
copy.set(ua);
|
|
51
|
+
return copy.buffer;
|
|
39
52
|
}
|
|
40
53
|
function decodeStringOrArrayBuffer(value) {
|
|
41
54
|
if (typeof value === 'string') {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ModelHelper.js","sourceRoot":"","sources":["../../../icc-api/model/ModelHelper.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"ModelHelper.js","sourceRoot":"","sources":["../../../icc-api/model/ModelHelper.ts"],"names":[],"mappings":";;AAEA,8BAYC;AAED,8BAMC;AAED,8BAEC;AAGD,sBAiBC;AAED,8DAQC;AAED,0BAEC;AAED,0BAEC;AAED,wBAEC;AAED,kBAoBC;AAED,kBAqBC;AA/GD,SAAgB,SAAS,CAAC,GAA6B;IACrD,IAAI,GAAG,GAAG,EAAE,CAAA;IACZ,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAA;IAC9B,MAAM,KAAK,GAAG,EAAE,CAAC,MAAM,CAAA;IACvB,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;IACjC,IAAI,MAAM,EAAE,GAAG,EAAE,KAAK,CAAA;IACtB,KAAK,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,KAAK,EAAE,MAAM,IAAI,UAAU,EAAE,CAA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2BAA2B,CAAC,CAAA;AAC9C,CAAC","sourcesContent":["import { readUInt24BE } from 'rsocket-core'\n\nexport function ua2string(_ua: Uint8Array | ArrayBuffer): string {\n let str = ''\n const ab = new Uint8Array(_ua)\n const abLen = ab.length\n const CHUNK_SIZE = Math.pow(2, 8)\n let offset, len, subab\n for (offset = 0; offset < abLen; offset += CHUNK_SIZE) {\n len = Math.min(CHUNK_SIZE, abLen - offset)\n subab = ab.subarray(offset, offset + len)\n str += String.fromCharCode.apply(null, subab as any)\n }\n return str\n}\n\nexport function string2ua(s: string): Uint8Array {\n const ua = new Uint8Array(s.length)\n for (let i = 0; i < s.length; i++) {\n ua[i] = s.charCodeAt(i) & 0xff\n }\n return ua\n}\n\nexport function string2ab(s: string): ArrayBuffer {\n return ua2ab(string2ua(s))\n}\n\n// Get an array buffer matching the content of the input, copying only when necessary\nexport function ua2ab(ua: ArrayBuffer | Uint8Array): ArrayBuffer {\n if (ua instanceof ArrayBuffer) return ua\n const { buffer, byteOffset, byteLength } = ua\n\n if (buffer instanceof ArrayBuffer) {\n if (byteOffset === 0 && byteLength === buffer.byteLength) {\n // zero-copy fast path\n return buffer\n }\n\n return buffer.slice(byteOffset, byteOffset + byteLength)\n }\n\n // buffer is SharedArrayBuffer → must copy\n const copy = new Uint8Array(byteLength)\n copy.set(ua)\n return copy.buffer\n}\n\nexport function decodeStringOrArrayBuffer(value: string | ArrayBuffer): ArrayBuffer {\n if (typeof value === 'string') {\n return b64_2ab(value)\n } else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n return value as ArrayBuffer\n } else {\n throw new Error(`Invalid type : ${typeof value}`)\n }\n}\n\nexport function b64_2ab(s: string): ArrayBuffer {\n return ua2ab(string2ua(a2b(s)))\n}\n\nexport function b64_2ua(s: string): Uint8Array {\n return string2ua(a2b(s))\n}\n\nexport function ua2b64(_ua: Uint8Array | ArrayBuffer): string {\n return b2a(ua2string(_ua))\n}\n\nexport function b2a(a: string): string {\n if (typeof window !== 'undefined') {\n //Favour btoa in browser\n if (typeof btoa !== 'undefined') {\n return btoa(a)\n }\n if (typeof Buffer !== 'undefined') {\n const buf = Buffer.from(a, 'latin1')\n return buf.toString('base64')\n }\n } else {\n if (typeof Buffer !== 'undefined') {\n const buf = Buffer.from(a, 'latin1')\n return buf.toString('base64')\n }\n if (typeof btoa !== 'undefined') {\n return btoa(a)\n }\n }\n throw new Error('Unsupported operation b2a')\n}\n\nexport function a2b(s: string): string {\n const urlUnsafeString = s.replace(/_/g, '/').replace(/-/g, '+')\n if (typeof window !== 'undefined') {\n //Favour atob in browser\n if (typeof atob !== 'undefined') {\n return atob(urlUnsafeString)\n }\n if (typeof Buffer !== 'undefined') {\n const buf = new Buffer(urlUnsafeString, 'base64')\n return buf.toString('latin1')\n }\n } else {\n if (typeof Buffer !== 'undefined') {\n const buf = new Buffer(urlUnsafeString, 'base64')\n return buf.toString('latin1')\n }\n if (typeof atob !== 'undefined') {\n return atob(urlUnsafeString)\n }\n }\n throw new Error('Unsupported operation a2b')\n}\n"]}
|
package/icc-api/model/User.d.ts
CHANGED
|
@@ -95,6 +95,7 @@ export declare class User {
|
|
|
95
95
|
[key in User.AutoDelegationTagEnum]?: Array<string>;
|
|
96
96
|
};
|
|
97
97
|
/**
|
|
98
|
+
* @deprecated use created instead
|
|
98
99
|
* the timestamp (unix epoch in ms) of creation of the user, will be filled automatically if missing. Not enforced by the application server.
|
|
99
100
|
*/
|
|
100
101
|
createdDate?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"User.js","sourceRoot":"","sources":["../../../icc-api/model/User.ts"],"names":[],"mappings":";;;AAgBA;;GAEG;AACH,MAAa,IAAI;IACf,YAAY,IAAgB;QAC1B,MAAM,CAAC,MAAM,CAAC,IAAY,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;
|
|
1
|
+
{"version":3,"file":"User.js","sourceRoot":"","sources":["../../../icc-api/model/User.ts"],"names":[],"mappings":";;;AAgBA;;GAEG;AACH,MAAa,IAAI;IACf,YAAY,IAAgB;QAC1B,MAAM,CAAC,MAAM,CAAC,IAAY,EAAE,IAAI,CAAC,CAAA;IACnC,CAAC;CAsGF;AAzGD,oBAyGC;AACD,WAAiB,IAAI;IAEN,aAAQ,GAAG;QACtB,QAAQ,EAAE,UAAsB;QAChC,IAAI,EAAE,MAAkB;QACxB,KAAK,EAAE,OAAmB;KAC3B,CAAA;IAEY,eAAU,GAAG;QACxB,MAAM,EAAE,QAAsB;QAC9B,QAAQ,EAAE,UAAwB;QAClC,WAAW,EAAE,aAA2B;KACzC,CAAA;IAqBY,0BAAqB,GAAG;QACnC,GAAG,EAAE,KAA8B;QACnC,kBAAkB,EAAE,oBAA6C;QACjE,kBAAkB,EAAE,oBAA6C;QACjE,oBAAoB,EAAE,sBAA+C;QACrE,kBAAkB,EAAE,oBAA6C;QACjE,oBAAoB,EAAE,sBAA+C;QACrE,uBAAuB,EAAE,yBAAkD;QAC3E,UAAU,EAAE,YAAqC;QACjD,gBAAgB,EAAE,kBAA2C;QAC7D,uBAAuB,EAAE,yBAAkD;QAC3E,wBAAwB,EAAE,0BAAmD;QAC7E,aAAa,EAAE,eAAwC;QACvD,eAAe,EAAE,iBAA0C;QAC3D,SAAS,EAAE,WAAoC;QAC/C,YAAY,EAAE,cAAuC;QACrD,eAAe,EAAE,iBAA0C;QAC3D,gBAAgB,EAAE,kBAA2C;QAC7D,eAAe,EAAE,iBAA0C;QAC3D,aAAa,EAAE,eAAwC;KACxD,CAAA;IAED,MAAa,cAAc;QACzB,YAAY,IAAgB;YAC1B,MAAM,CAAC,MAAM,CAAC,IAAY,EAAE,IAAI,CAAC,CAAA;QACnC,CAAC;KAkBF;IArBY,mBAAc,iBAqB1B,CAAA;AACH,CAAC,EA7EgB,IAAI,oBAAJ,IAAI,QA6EpB","sourcesContent":["/**\n * iCure Data Stack API Documentation\n * The iCure Data Stack Application API is the native interface to iCure. This version is obsolete, please use v2.\n *\n * OpenAPI spec version: v1\n *\n *\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen.git\n * Do not edit the class manually.\n */\nimport { AuthenticationToken } from './AuthenticationToken'\nimport { Permission } from './Permission'\nimport { PropertyStub } from './PropertyStub'\nimport { Identifier } from './Identifier'\n\n/**\n * This entity is a root level object. It represents an user that can log in to the iCure platform. It is serialized in JSON and saved in the underlying icure-base CouchDB database.\n */\nexport class User {\n constructor(json: JSON | any) {\n Object.assign(this as User, json)\n }\n\n /**\n * the Id of the user. We encourage using either a v4 UUID or a HL7 Id.\n */\n id?: string\n /**\n * the revision of the user in the database, used for conflict management / optimistic locking.\n */\n rev?: string\n identifier?: Array<Identifier>\n /**\n * hard delete (unix epoch in ms) timestamp of the object. Filled automatically when deletePatient is called.\n */\n deletionDate?: number\n created?: number\n /**\n * Last name of the user. This is the official last name that should be used for official administrative purposes.\n */\n name?: string\n /**\n * Extra properties for the user. Those properties are typed (see class Property)\n */\n properties?: Array<PropertyStub>\n /**\n * If permission to modify patient data is granted or revoked\n */\n permissions?: Array<Permission>\n /**\n * Roles specified for the user\n */\n roles?: Array<string>\n /**\n * Authorization source for user. 'Database', 'ldap' or 'token'\n */\n type?: User.TypeEnum\n /**\n * State of user's activeness: 'Active', 'Disabled' or 'Registering'\n */\n status?: User.StatusEnum\n /**\n * Username for this user. We encourage using an email address\n */\n login?: string\n /**\n * Hashed version of the password (BCrypt is used for hashing)\n */\n passwordHash?: string\n /**\n * Secret token used to verify 2fa\n */\n secret?: string\n /**\n * Whether the user has activated two factors authentication\n */\n use2fa?: boolean\n /**\n * id of the group (practice/hospital) the user is member of\n */\n groupId?: string\n /**\n * Id of the healthcare party if the user is a healthcare party.\n */\n healthcarePartyId?: string\n /**\n * Id of the patient if the user is a patient\n */\n patientId?: string\n /**\n * Id of the device if the user is a device\n */\n deviceId?: string\n /**\n * Delegations that are automatically generated client side when a new database object is created by this user\n */\n autoDelegations?: { [key in User.AutoDelegationTagEnum]?: Array<string> }\n /**\n * @deprecated use created instead\n * the timestamp (unix epoch in ms) of creation of the user, will be filled automatically if missing. Not enforced by the application server.\n */\n createdDate?: number\n /**\n * the timestamp (unix epoch in ms) of the latest validation of the terms of use of the application\n */\n termsOfUseDate?: number\n /**\n * email address of the user (used for token exchange or password recovery).\n */\n email?: string\n /**\n * mobile phone of the user (used for token exchange or password recovery).\n */\n mobilePhone?: string\n applicationTokens?: { [key: string]: string }\n /**\n * Encrypted and time-limited Authentication tokens used for inter-applications authentication\n */\n authenticationTokens?: { [key: string]: AuthenticationToken }\n /**\n * System metadata for the user: this configuration is read only, and defined only when using the cloud version of iCure.\n */\n systemMetadata?: User.SystemMetadata\n}\nexport namespace User {\n export type TypeEnum = 'database' | 'ldap' | 'token'\n export const TypeEnum = {\n Database: 'database' as TypeEnum,\n Ldap: 'ldap' as TypeEnum,\n Token: 'token' as TypeEnum,\n }\n export type StatusEnum = 'ACTIVE' | 'DISABLED' | 'REGISTERING'\n export const StatusEnum = {\n ACTIVE: 'ACTIVE' as StatusEnum,\n DISABLED: 'DISABLED' as StatusEnum,\n REGISTERING: 'REGISTERING' as StatusEnum,\n }\n export type AutoDelegationTagEnum =\n | 'all'\n | 'administrativeData'\n | 'generalInformation'\n | 'financialInformation'\n | 'medicalInformation'\n | 'sensitiveInformation'\n | 'confidentialInformation'\n | 'cdItemRisk'\n | 'cdItemFamilyRisk'\n | 'cdItemHealthcareelement'\n | 'cdItemHealthcareapproach'\n | 'cdItemAllergy'\n | 'cdItemDiagnosis'\n | 'cdItemLab'\n | 'cdItemResult'\n | 'cdItemParameter'\n | 'cdItemMedication'\n | 'cdItemTreatment'\n | 'cdItemVaccine'\n export const AutoDelegationTagEnum = {\n all: 'all' as AutoDelegationTagEnum,\n administrativeData: 'administrativeData' as AutoDelegationTagEnum,\n generalInformation: 'generalInformation' as AutoDelegationTagEnum,\n financialInformation: 'financialInformation' as AutoDelegationTagEnum,\n medicalInformation: 'medicalInformation' as AutoDelegationTagEnum,\n sensitiveInformation: 'sensitiveInformation' as AutoDelegationTagEnum,\n confidentialInformation: 'confidentialInformation' as AutoDelegationTagEnum,\n cdItemRisk: 'cdItemRisk' as AutoDelegationTagEnum,\n cdItemFamilyRisk: 'cdItemFamilyRisk' as AutoDelegationTagEnum,\n cdItemHealthcareelement: 'cdItemHealthcareelement' as AutoDelegationTagEnum,\n cdItemHealthcareapproach: 'cdItemHealthcareapproach' as AutoDelegationTagEnum,\n cdItemAllergy: 'cdItemAllergy' as AutoDelegationTagEnum,\n cdItemDiagnosis: 'cdItemDiagnosis' as AutoDelegationTagEnum,\n cdItemLab: 'cdItemLab' as AutoDelegationTagEnum,\n cdItemResult: 'cdItemResult' as AutoDelegationTagEnum,\n cdItemParameter: 'cdItemParameter' as AutoDelegationTagEnum,\n cdItemMedication: 'cdItemMedication' as AutoDelegationTagEnum,\n cdItemTreatment: 'cdItemTreatment' as AutoDelegationTagEnum,\n cdItemVaccine: 'cdItemVaccine' as AutoDelegationTagEnum,\n }\n\n export class SystemMetadata {\n constructor(json: JSON | any) {\n Object.assign(this as User, json)\n }\n\n /**\n * The roles of the user that the cloud environment recognizes\n */\n roles?: string[]\n /**\n * If the user is considered as an admin by the cloud environment\n */\n isAdmin?: boolean\n /**\n * True if the content of roles is inherited from the user's group configuration, false if the roles are defined specifically for the use\n */\n inheritsRoles?: boolean\n /**\n * Identifiers of the user available for login\n */\n loginIdentifiers?: Identifier[]\n }\n}\n"]}
|
package/icc-x-api/crypto/AES.js
CHANGED
|
@@ -91,7 +91,7 @@ class AESUtilsImpl {
|
|
|
91
91
|
*/
|
|
92
92
|
};
|
|
93
93
|
this._debug && console.log(`decrypt ${(0, utils_1.ua2hex)(encryptedData)} with ${rawKey}`);
|
|
94
|
-
this.crypto.subtle.decrypt(aesAlgorithmEncrypt, cryptoKey, encryptedDataUint8.subarray(this.ivLength, encryptedDataUint8.length)).then((decipheredData) => {
|
|
94
|
+
this.crypto.subtle.decrypt(aesAlgorithmEncrypt, cryptoKey, (0, utils_1.ua2ab)(encryptedDataUint8.subarray(this.ivLength, encryptedDataUint8.length))).then((decipheredData) => {
|
|
95
95
|
this._debug && console.log(`decipheredData: ${(0, utils_1.ua2hex)(decipheredData)}`);
|
|
96
96
|
resolve(decipheredData);
|
|
97
97
|
}, (err) => {
|
|
@@ -1 +1 @@
|
|
|
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,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ffer, 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"]}
|
|
1
|
+
{"version":3,"file":"AES.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/AES.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oCAA8D;AAmE9D,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,C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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,CAAC;oBACrF,OAAO,CAAC,IAAI,CAAC,iBAAiB,IAAA,cAAM,EAAC,MAAM,CAAC,SAAS,CAAC,CAAA;gBACxD,CAAC;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, ua2ab, 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, ua2ab(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"]}
|
|
@@ -150,7 +150,7 @@ class BaseExchangeDataManager {
|
|
|
150
150
|
*/
|
|
151
151
|
tryDecryptAccessControlSecret(exchangeData, decryptionKeys) {
|
|
152
152
|
return __awaiter(this, void 0, void 0, function* () {
|
|
153
|
-
return yield this.tryDecryptExchangeData(exchangeData, decryptionKeys, (ed) => ed.accessControlSecret, (d) => this.importAccessControlSecret(new Uint8Array(d)));
|
|
153
|
+
return yield this.tryDecryptExchangeData(exchangeData, decryptionKeys, (ed) => ed.accessControlSecret, (d) => this.importAccessControlSecret(new Uint8Array(d).buffer));
|
|
154
154
|
});
|
|
155
155
|
}
|
|
156
156
|
/**
|
|
@@ -163,7 +163,7 @@ class BaseExchangeDataManager {
|
|
|
163
163
|
*/
|
|
164
164
|
tryDecryptExchangeKeys(exchangeData, decryptionKeys) {
|
|
165
165
|
return __awaiter(this, void 0, void 0, function* () {
|
|
166
|
-
return yield this.tryDecryptExchangeData(exchangeData, decryptionKeys, (ed) => ed.exchangeKey, (d) => this.importExchangeKey(new Uint8Array(d)));
|
|
166
|
+
return yield this.tryDecryptExchangeData(exchangeData, decryptionKeys, (ed) => ed.exchangeKey, (d) => this.importExchangeKey(new Uint8Array(d).buffer));
|
|
167
167
|
});
|
|
168
168
|
}
|
|
169
169
|
/**
|
|
@@ -176,7 +176,7 @@ class BaseExchangeDataManager {
|
|
|
176
176
|
*/
|
|
177
177
|
tryDecryptSharedSignatureKeys(exchangeData, decryptionKeys) {
|
|
178
178
|
return __awaiter(this, void 0, void 0, function* () {
|
|
179
|
-
return yield this.tryDecryptExchangeData(exchangeData, decryptionKeys, (ed) => ed.sharedSignatureKey, (d) => this.importSharedSignatureKey(new Uint8Array(d)));
|
|
179
|
+
return yield this.tryDecryptExchangeData(exchangeData, decryptionKeys, (ed) => ed.sharedSignatureKey, (d) => this.importSharedSignatureKey(new Uint8Array(d).buffer));
|
|
180
180
|
});
|
|
181
181
|
}
|
|
182
182
|
tryDecryptExchangeData(exchangeData, decryptionKeys, encryptedDataSelector, unmarshalDecrypted) {
|
|
@@ -311,9 +311,9 @@ class BaseExchangeDataManager {
|
|
|
311
311
|
return __awaiter(this, arguments, void 0, function* ({ exchangeData, newEncryptionKeys, rawExchangeKey, rawAccessControlSecret, rawSharedSignatureKey, newDelegatorSignatureKeys, }) {
|
|
312
312
|
var _b;
|
|
313
313
|
const self = yield this.dataOwnerApi.getCurrentDataOwnerId();
|
|
314
|
-
const exchangeKey = yield this.importExchangeKey(new Uint8Array(rawExchangeKey));
|
|
315
|
-
const accessControlSecret = yield this.importAccessControlSecret(new Uint8Array(rawAccessControlSecret));
|
|
316
|
-
const sharedSignatureKey = yield this.importSharedSignatureKey(new Uint8Array(rawSharedSignatureKey));
|
|
314
|
+
const exchangeKey = yield this.importExchangeKey(new Uint8Array(rawExchangeKey).buffer);
|
|
315
|
+
const accessControlSecret = yield this.importAccessControlSecret(new Uint8Array(rawAccessControlSecret).buffer);
|
|
316
|
+
const sharedSignatureKey = yield this.importSharedSignatureKey(new Uint8Array(rawSharedSignatureKey).buffer);
|
|
317
317
|
const existingExchangeKeyEntries = new Set(Object.keys(exchangeData.exchangeKey));
|
|
318
318
|
const existingAcsEntries = new Set(Object.keys(exchangeData.accessControlSecret));
|
|
319
319
|
const existingSharedSignatureKeyEntries = new Set(Object.keys(exchangeData.sharedSignatureKey));
|
|
@@ -368,7 +368,7 @@ class BaseExchangeDataManager {
|
|
|
368
368
|
['publicKeysFingerprints', data.publicKeysFingerprintsV2.sort()],
|
|
369
369
|
];
|
|
370
370
|
const signJson = JSON.stringify(signObject);
|
|
371
|
-
return (0, utils_1.utf8_2ua)(signJson);
|
|
371
|
+
return (0, utils_1.ua2ab)((0, utils_1.utf8_2ua)(signJson));
|
|
372
372
|
});
|
|
373
373
|
}
|
|
374
374
|
bytesToSignForDelegatorSignature(data) {
|
|
@@ -379,7 +379,7 @@ class BaseExchangeDataManager {
|
|
|
379
379
|
// Generates a new exchange key
|
|
380
380
|
generateExchangeKey() {
|
|
381
381
|
return __awaiter(this, void 0, void 0, function* () {
|
|
382
|
-
const rawBytes =
|
|
382
|
+
const rawBytes = (0, utils_1.ua2ab)(this.primitives.randomBytes(32));
|
|
383
383
|
return {
|
|
384
384
|
key: yield this.importExchangeKey(rawBytes),
|
|
385
385
|
rawBytes,
|
|
@@ -415,7 +415,7 @@ class BaseExchangeDataManager {
|
|
|
415
415
|
// Generates a new access control secret
|
|
416
416
|
generateAccessControlSecret() {
|
|
417
417
|
return __awaiter(this, void 0, void 0, function* () {
|
|
418
|
-
const rawBytes = this.primitives.randomBytes(16);
|
|
418
|
+
const rawBytes = (0, utils_1.ua2ab)(this.primitives.randomBytes(16));
|
|
419
419
|
return {
|
|
420
420
|
secret: yield this.importAccessControlSecret(rawBytes),
|
|
421
421
|
rawBytes,
|
|
@@ -426,7 +426,7 @@ class BaseExchangeDataManager {
|
|
|
426
426
|
return Promise.resolve((0, utils_1.ua2hex)(decryptedBytes));
|
|
427
427
|
}
|
|
428
428
|
exportAccessControlSecret(secret) {
|
|
429
|
-
return Promise.resolve((0, utils_1.hex2ua)(secret));
|
|
429
|
+
return Promise.resolve((0, utils_1.ua2ab)((0, utils_1.hex2ua)(secret)));
|
|
430
430
|
}
|
|
431
431
|
encryptDataWithKeys(rawData, keys) {
|
|
432
432
|
return __awaiter(this, void 0, void 0, function* () {
|
|
@@ -451,7 +451,7 @@ class BaseExchangeDataManager {
|
|
|
451
451
|
return __awaiter(this, void 0, void 0, function* () {
|
|
452
452
|
const res = {};
|
|
453
453
|
for (const [fp, key] of Object.entries(keys)) {
|
|
454
|
-
res[(0, utils_2.fingerprintV1toV2)(fp)] = (0, utils_1.ua2b64)(yield this.primitives.HMAC.sign(yield this.extractHmacFromRsaPrivate(key), new Uint8Array(rawData)));
|
|
454
|
+
res[(0, utils_2.fingerprintV1toV2)(fp)] = (0, utils_1.ua2b64)(yield this.primitives.HMAC.sign(yield this.extractHmacFromRsaPrivate(key), new Uint8Array(rawData).buffer));
|
|
455
455
|
}
|
|
456
456
|
return res;
|
|
457
457
|
});
|
|
@@ -466,7 +466,7 @@ class BaseExchangeDataManager {
|
|
|
466
466
|
for (const [fp, signature] of Object.entries((_a = exchangeData.delegatorSignature) !== null && _a !== void 0 ? _a : {})) {
|
|
467
467
|
const verificationKey = keysByV2Fp[fp];
|
|
468
468
|
if (verificationKey &&
|
|
469
|
-
(yield this.primitives.HMAC.verify(yield this.extractHmacFromRsaPrivate(verificationKey), delegatorSignatureData, (0, utils_1.b64_2ua)(signature))))
|
|
469
|
+
(yield this.primitives.HMAC.verify(yield this.extractHmacFromRsaPrivate(verificationKey), delegatorSignatureData, (0, utils_1.ua2ab)((0, utils_1.b64_2ua)(signature)))))
|
|
470
470
|
return true;
|
|
471
471
|
}
|
|
472
472
|
return false;
|
|
@@ -474,12 +474,12 @@ class BaseExchangeDataManager {
|
|
|
474
474
|
}
|
|
475
475
|
signDataWithSharedKey(rawData, key) {
|
|
476
476
|
return __awaiter(this, void 0, void 0, function* () {
|
|
477
|
-
return (0, utils_1.ua2b64)(yield this.primitives.HMAC.sign(key, new Uint8Array(rawData)));
|
|
477
|
+
return (0, utils_1.ua2b64)(yield this.primitives.HMAC.sign(key, new Uint8Array(rawData).buffer));
|
|
478
478
|
});
|
|
479
479
|
}
|
|
480
480
|
verifyDataWithSharedKey(rawData, key, signature) {
|
|
481
481
|
return __awaiter(this, void 0, void 0, function* () {
|
|
482
|
-
return yield this.primitives.HMAC.verify(key, new Uint8Array(rawData), (0, utils_1.b64_2ua)(signature));
|
|
482
|
+
return yield this.primitives.HMAC.verify(key, new Uint8Array(rawData).buffer, (0, utils_1.ua2ab)((0, utils_1.b64_2ua)(signature)));
|
|
483
483
|
});
|
|
484
484
|
}
|
|
485
485
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseExchangeDataManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/BaseExchangeDataManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,4EAAwE;AAExE,+CAA2C;AAE3C,oCAAoE;AACpE,4BAA2B;AAC3B,mCAA4D;AAC5D,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAE9B;;;;GAIG;AACH,MAAa,uBAAuB;IAClC,YACW,GAAuB,EACf,YAA8B,EAC9B,UAA4B,EAC5B,gCAAyC,EACzC,eAAwB;QAJhC,QAAG,GAAH,GAAG,CAAoB;QACf,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,eAAU,GAAV,UAAU,CAAkB;QAC5B,qCAAgC,GAAhC,gCAAgC,CAAS;QACzC,oBAAe,GAAf,eAAe,CAAS;IACxC,CAAC;IAEJ;;;;;;OAMG;IACG,8CAA8C;;;YAClD,IAAI,CAAC,IAAI,CAAC,gCAAgC;gBAAE,OAAO,SAAS,CAAA;YAC5D,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAA;YACnE,IAAI,YAAY,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,4BAA4B,CAAC,WAAW,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;YAC5F,MAAM,YAAY,GAAG,MAAA,YAAY,CAAC,IAAI,mCAA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C,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,EAAuB,EAAE,CAAC,CAAC,IAAA,yBAAiB,EAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAA;YAC7I,KAAK,MAAM,CAAC,EAAE,EAAE,SAAS,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAA,YAAY,CAAC,kBAAkB,mCAAI,EAAE,CAAC,EAAE,CAAC;gBACpF,MAAM,eAAe,GAAG,UAAU,CAAC,EAAE,CAAC,CAAA;gBACtC,IACE,eAAe;oBACf,CAAC,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,yBAAyB,CAAC,eAAe,CAAC,EAAE,sBAAsB,EAAE,IAAA,eAAO,EAAC,SAAS,CAAC,CAAC,CAAC;oBAEtI,OAAO,IAAI,CAAA;YACf,CAAC;YACD,OAAO,KAAK,CAAA;QACd,CAAC;KAAA;IAEa,qBAAqB,CAAC,OAAoB,EAAE,GAAc;;YACtE,OAAO,IAAA,cAAM,EAAC,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;QAC9E,CAAC;KAAA;IAEa,uBAAuB,CAAC,OAAoB,EAAE,GAAc,EAAE,SAAiB;;YAC3F,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,UAAU,CAAC,OAAO,CAAC,EAAE,IAAA,eAAO,EAAC,SAAS,CAAC,CAAC,CAAA;QAC5F,CAAC;KAAA;CACF;AAlkBD,0DAkkBC","sourcesContent":["import { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair } from './RSA'\nimport { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { IccExchangeDataApi } from '../../icc-api/api/internal/IccExchangeDataApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { b64_2ua, hex2ua, ua2b64, ua2hex, utf8_2ua } from '../utils'\nimport * as _ from 'lodash'\nimport { fingerprintIsV1, fingerprintV1toV2 } from './utils'\nimport XHRError = XHR.XHRError\n\n/**\n * @internal this class is intended for internal use only and may be modified without notice\n * Functions to create and get exchange data.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeDataManager {\n constructor(\n readonly api: IccExchangeDataApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly primitives: CryptoPrimitives,\n private readonly selfRequiresAnonymousDelegations: boolean,\n private readonly doNotUseBulkGet: boolean\n ) {}\n\n /**\n * Get all the exchange data where the current data owner is the delegator or the delegate. However, some data owners, generally HCPs, may have a\n * prohibitively high amount of exchange data. If the crypto strategies specify that the current data owner requires anonymous delegation this\n * method returns all the exchange data found for the data owner, else the method returns undefined.\n * @return all the exchange data for the current data owner or undefined if the crypto strategies don't allow to retrieve all data for the current\n * data owner.\n */\n async getAllExchangeDataForCurrentDataOwnerIfAllowed(): Promise<ExchangeData[] | undefined> {\n if (!this.selfRequiresAnonymousDelegations) return undefined\n const dataOwnerId = await this.dataOwnerApi.getCurrentDataOwnerId()\n let latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, undefined, 1000)\n const allRetrieved = latestResult.rows ?? []\n while (latestResult.nextKeyPair?.startKeyDocId) {\n latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, latestResult.nextKeyPair.startKeyDocId, 1000)\n if (latestResult.rows) allRetrieved.push(...latestResult.rows)\n }\n return allRetrieved\n }\n\n /**\n * Get all exchange data for the provided delegator-delegate pair.\n * @param delegatorId id of a delegator data owner.\n * @param delegateId id of a delegate data owner.\n * @return all exchange data for the provided delegator-delegate pair.\n */\n async getExchangeDataByDelegatorDelegatePair(delegatorId: string, delegateId: string): Promise<ExchangeData[]> {\n return await this.api.getExchangeDataByDelegatorDelegate(delegatorId, delegateId)\n }\n\n /**\n * Get the exchange data with the provided id.\n * @param exchangeDataId id of the exchange data.\n * @return the exchange data with the provided id or undefined if no exchange data with such id could be found.\n */\n async getExchangeDataById(exchangeDataId: string): Promise<ExchangeData | undefined> {\n return await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && e.statusCode === 404) {\n return undefined\n } else throw e\n })\n }\n\n async getExchangeDataByIds(exchangeDataIds: string[]): Promise<ExchangeData[]> {\n if (this.doNotUseBulkGet) {\n const res: ExchangeData[] = []\n for (const exchangeDataId of exchangeDataIds) {\n const curr = await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && (e.statusCode === 404 || e.statusCode === 403)) {\n return undefined\n } else throw e\n })\n if (curr) res.push(curr)\n }\n return res\n } else {\n return await this.api.getExchangeDataByIds({ ids: exchangeDataIds })\n }\n }\n\n /**\n * Verifies the authenticity of the exchange data by checking the signature.\n * Note that all exchange data created by data owners other than the current data owner (including members of his hierarchy)\n * will always be unverified.\n * @param data collects the following information about the exchange data being verified:\n * - exchangeData the exchange data to verify.\n * - decryptedAccessControlSecret the access control secret decrypted from the exchange data.\n * - decryptedExchangeKey the exchange key decrypted from the exchange data.\n * - decryptedSharedSignatureKey the shared signature key decrypted from the exchange data.\n * @param verificationKeys verification keys for delegator signature by fingerprint.\n * @param verifyAsDelegator if true the method will also verify that the hmac key used for the signature was created by the delegator of the\n * exchange data. If true and the data was not created by the current data owner this method will return false.\n * @return the exchange data which could be verified given his signature and the available verification keys.\n * @throws if any of the provided exchange data has been created by a data owner other than the current data owner.\n */\n async verifyExchangeData(\n data: {\n exchangeData: ExchangeData\n decryptedAccessControlSecret: string\n decryptedExchangeKey: CryptoKey\n decryptedSharedSignatureKey: CryptoKey\n },\n verificationKeys: { [fp: string]: CryptoKey },\n verifyAsDelegator: boolean\n ): Promise<boolean> {\n if (verifyAsDelegator && data.exchangeData.delegator !== (await this.dataOwnerApi.getCurrentDataOwnerId())) return false\n if (verifyAsDelegator && !(await this.verifyDelegatorSignature(data.exchangeData, data.decryptedSharedSignatureKey, verificationKeys)))\n return false\n const sharedSignatureData = await this.bytesToSignForSharedSignature({\n decryptedAccessControlSecret: data.decryptedAccessControlSecret,\n decryptedExchangeKey: data.decryptedExchangeKey,\n delegator: data.exchangeData.delegator,\n delegate: data.exchangeData.delegate,\n publicKeysFingerprintsV2: [\n ...new Set([\n ...Object.keys(data.exchangeData.exchangeKey),\n ...Object.keys(data.exchangeData.accessControlSecret),\n ...Object.keys(data.exchangeData.sharedSignatureKey),\n ]),\n ],\n })\n return await this.verifyDataWithSharedKey(sharedSignatureData, data.decryptedSharedSignatureKey, data.exchangeData.sharedSignature)\n }\n\n /**\n * Extracts and decrypts the access control secret from the provided exchange data.\n * These need to be hashed together with the entity class and confidentiality level in order to get the actual access control key\n * which will be sent to the server.\n * @param exchangeData the exchange data from which to extract access control secrets.\n * @param decryptionKeys rsa key pairs to use for decryption of the access control secret.\n * @return an object composed of:\n * - successfulDecryptions: array of all successfully decrypted access control keys\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptAccessControlSecret(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: string[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.accessControlSecret,\n (d) => this.importAccessControlSecret(new Uint8Array(d))\n )\n }\n\n /**\n * Extract and decrypts the exchange keys from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptExchangeKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.exchangeKey,\n (d) => this.importExchangeKey(new Uint8Array(d))\n )\n }\n\n /**\n * Extract and decrypts the shared signature key from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptSharedSignatureKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.sharedSignatureKey,\n (d) => this.importSharedSignatureKey(new Uint8Array(d))\n )\n }\n\n private async tryDecryptExchangeData<T>(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n encryptedDataSelector: (data: ExchangeData) => { [keyPairFingerprint: string]: string },\n unmarshalDecrypted: (decrypted: ArrayBuffer) => Promise<T>\n ): Promise<{\n successfulDecryptions: T[]\n failedDecryptions: ExchangeData[]\n }> {\n const successfulDecryptions: T[] = []\n const failedDecryptions: ExchangeData[] = []\n for (const ed of exchangeData) {\n try {\n const decrypted = await this.tryDecrypt(encryptedDataSelector(ed), decryptionKeys)\n if (decrypted) {\n successfulDecryptions.push(await unmarshalDecrypted(decrypted))\n } else {\n failedDecryptions.push(ed)\n }\n } catch (e) {\n failedDecryptions.push(ed)\n }\n }\n return { successfulDecryptions, failedDecryptions }\n }\n\n private async tryDecrypt(\n encryptedData: { [keyPairFingerprintV2: string]: string },\n decryptionKeys: { [publicKeyFingerprintV1: string]: KeyPair<CryptoKey> }\n ): Promise<ArrayBuffer | undefined> {\n const decryptionKeysWithV2Fp = Object.keys(decryptionKeys).reduce((prev, fp) => {\n return {\n ...prev,\n [fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp]: decryptionKeys[fp],\n }\n }, {} as { [publicKeyFingerprint: string]: KeyPair<CryptoKey> })\n for (const [fp, encrypted] of Object.entries(encryptedData)) {\n try {\n const key = decryptionKeysWithV2Fp[fp]?.privateKey\n if (key) return await this.primitives.RSA.decrypt(key, b64_2ua(encrypted))\n } catch (e) {\n // Try with another key\n }\n }\n }\n\n /**\n * Creates exchange data from the current data owner to the provided delegate, uploading the newly created exchange data to the cloud.\n * This assumes that the keys have been verified.\n * @param delegateId id of the delegate for the new exchange data.\n * @param signatureKeys private keys to use for signing the created data.\n * @param encryptionKeys public keys to use for the encryption of the exchange data (from delegator and delegate).\n * @param optionalAttributes optional precalculated attributes for the creation of data\n * @return the newly created exchange data, and its decrypted exchange key and access control secret.\n */\n async createExchangeData(\n delegateId: string,\n signatureKeys: { [keyPairFingerprint: string]: CryptoKey },\n encryptionKeys: { [keyPairFingerprint: string]: CryptoKey },\n optionalAttributes: {\n id?: string\n } = {}\n ): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n sharedSignatureKey: CryptoKey\n }> {\n if (!Object.keys(encryptionKeys).length) {\n throw new Error('Must specify at least one encryption key ')\n }\n const exchangeKey = await this.generateExchangeKey()\n const accessControlSecret = await this.generateAccessControlSecret()\n const sharedSignatureKey = await this.generateSharedSignatureKey()\n const encryptedExchangeKey = await this.encryptDataWithKeys(exchangeKey.rawBytes, encryptionKeys)\n const encryptedAccessControlSecret = await this.encryptDataWithKeys(accessControlSecret.rawBytes, encryptionKeys)\n const encryptedSharedSignatureKey = await this.encryptDataWithKeys(sharedSignatureKey.rawBytes, encryptionKeys)\n const baseExchangeData = {\n id: optionalAttributes.id ?? this.primitives.randomUuid(),\n delegator: await this.dataOwnerApi.getCurrentDataOwnerId(),\n delegate: delegateId,\n exchangeKey: encryptedExchangeKey,\n accessControlSecret: encryptedAccessControlSecret,\n sharedSignatureKey: encryptedSharedSignatureKey,\n }\n const sharedSignature = await this.signDataWithSharedKey(\n await this.bytesToSignForSharedSignature({\n delegate: baseExchangeData.delegate,\n delegator: baseExchangeData.delegator,\n decryptedAccessControlSecret: accessControlSecret.secret,\n decryptedExchangeKey: exchangeKey.key,\n publicKeysFingerprintsV2: Object.keys(encryptionKeys).map(fingerprintV1toV2),\n }),\n sharedSignatureKey.key\n )\n const delegatorSignature = await this.signDataWithDelegatorKeys(\n await this.bytesToSignForDelegatorSignature({\n sharedSignatureKey: sharedSignatureKey.key,\n }),\n signatureKeys\n )\n const exchangeData = new ExchangeData({ ...baseExchangeData, delegatorSignature, sharedSignature })\n return {\n exchangeData: await this.api.createExchangeData(exchangeData),\n exchangeKey: exchangeKey.key,\n accessControlSecret: accessControlSecret.secret,\n sharedSignatureKey: sharedSignatureKey.key,\n }\n }\n\n async tryRawDecryptExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<\n | {\n rawExchangeKey: ArrayBuffer\n rawAccessControlSecret: ArrayBuffer\n rawSharedSignatureKey: ArrayBuffer\n }\n | undefined\n > {\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n const rawSharedSignatureKey = await this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey) return undefined\n return { rawExchangeKey, rawAccessControlSecret, rawSharedSignatureKey }\n }\n\n /**\n * Updates existing exchange data and uploads it to the cloud in order to share it also with additional public keys, useful for example in cases\n * where one of the data owners involved in the exchange data has lost one of his keys.\n * If the content of the exchange data could not be decrypted using the provided keys the method will not update anything and will return undefined.\n * This method assumes that the new encryption keys have been verified.\n * @param exchangeData exchange data to update.\n * @param decryptionKeys keys to use to extract the content of the exchange data which will be shared with the new keys.\n * @param newEncryptionKeys new keys to add to the exchange data.\n * @return the updated exchange data, and its decrypted exchange key and access control secret, or undefined if the exchange data content could not\n * be decrypted and the exchange data could not be updated.\n */\n async tryUpdateExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n newEncryptionKeys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<\n | {\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }\n | undefined\n > {\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n const rawSharedSignatureKey = await this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey) return undefined\n return await this.updateExchangeDataWithRawDecryptedContent({\n exchangeData: exchangeData,\n newEncryptionKeys: newEncryptionKeys,\n rawExchangeKey: rawExchangeKey,\n rawAccessControlSecret: rawAccessControlSecret,\n rawSharedSignatureKey: rawSharedSignatureKey,\n newDelegatorSignatureKeys: {},\n })\n }\n\n /**\n * Same as [tryUpdateExchangeData] but the decrypted content is already provided.\n */\n async updateExchangeDataWithRawDecryptedContent({\n exchangeData,\n newEncryptionKeys,\n rawExchangeKey,\n rawAccessControlSecret,\n rawSharedSignatureKey,\n newDelegatorSignatureKeys,\n }: {\n exchangeData: ExchangeData\n newEncryptionKeys: { [fp: string]: CryptoKey }\n newDelegatorSignatureKeys: { [keyPairFingerprint: string]: CryptoKey }\n rawExchangeKey: ArrayBuffer\n rawAccessControlSecret: ArrayBuffer\n rawSharedSignatureKey: ArrayBuffer\n }): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n const exchangeKey = await this.importExchangeKey(new Uint8Array(rawExchangeKey))\n const accessControlSecret = await this.importAccessControlSecret(new Uint8Array(rawAccessControlSecret))\n const sharedSignatureKey = await this.importSharedSignatureKey(new Uint8Array(rawSharedSignatureKey))\n const existingExchangeKeyEntries = new Set(Object.keys(exchangeData.exchangeKey))\n const existingAcsEntries = new Set(Object.keys(exchangeData.accessControlSecret))\n const existingSharedSignatureKeyEntries = new Set(Object.keys(exchangeData.sharedSignatureKey))\n const missingEntries = Object.keys(newEncryptionKeys).filter(\n (fp) => !existingAcsEntries.has(fp) || !existingExchangeKeyEntries.has(fp) || !existingSharedSignatureKeyEntries.has(fp)\n )\n const existingDelegatorSignatureEntries = new Set(Object.keys(exchangeData.delegatorSignature ?? {}))\n const missingDelegatorSignatureEntries =\n exchangeData.delegator == self ? Object.keys(newDelegatorSignatureKeys).filter((fp) => !existingDelegatorSignatureEntries.has(fp)) : []\n if (!missingEntries.length && !missingDelegatorSignatureEntries.length) return { exchangeData, exchangeKey, accessControlSecret }\n const encryptionKeysForMissingEntries = missingEntries.reduce((obj, fp) => {\n obj[fp] = newEncryptionKeys[fp]\n return obj\n }, {} as { [keyPairFingerprint: string]: CryptoKey })\n const updatedExchangeData = _.cloneDeep(exchangeData)\n updatedExchangeData.exchangeKey = {\n ...exchangeData.exchangeKey,\n ...(await this.encryptDataWithKeys(rawExchangeKey, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.accessControlSecret = {\n ...exchangeData.accessControlSecret,\n ...(await this.encryptDataWithKeys(rawAccessControlSecret, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.sharedSignatureKey = {\n ...exchangeData.sharedSignatureKey,\n ...(await this.encryptDataWithKeys(rawSharedSignatureKey, encryptionKeysForMissingEntries)),\n }\n const isVerified = await this.verifyExchangeData(\n {\n exchangeData,\n decryptedAccessControlSecret: accessControlSecret,\n decryptedExchangeKey: exchangeKey,\n decryptedSharedSignatureKey: sharedSignatureKey,\n },\n {},\n false\n )\n if (isVerified) {\n updatedExchangeData.sharedSignature = await this.signDataWithSharedKey(\n await this.bytesToSignForSharedSignature({\n delegate: updatedExchangeData.delegate,\n delegator: updatedExchangeData.delegator,\n decryptedAccessControlSecret: accessControlSecret,\n decryptedExchangeKey: exchangeKey,\n publicKeysFingerprintsV2: Object.keys(updatedExchangeData.exchangeKey),\n }),\n sharedSignatureKey\n )\n }\n if (missingDelegatorSignatureEntries.length > 0) {\n const bytesToSign = await this.bytesToSignForDelegatorSignature({ sharedSignatureKey })\n const newSigned = await this.signDataWithDelegatorKeys(\n bytesToSign,\n missingDelegatorSignatureEntries.reduce((obj, fp) => {\n obj[fp] = newDelegatorSignatureKeys[fp]\n return obj\n }, {} as { [keyPairFingerprint: string]: CryptoKey })\n )\n updatedExchangeData.delegatorSignature = {\n ...updatedExchangeData.delegatorSignature,\n ...newSigned,\n }\n }\n return { exchangeData: await this.api.modifyExchangeData(new ExchangeData(updatedExchangeData)), exchangeKey, accessControlSecret }\n }\n\n private async bytesToSignForSharedSignature(data: {\n delegator: string\n delegate: string\n decryptedAccessControlSecret: string\n decryptedExchangeKey: CryptoKey\n publicKeysFingerprintsV2: string[]\n }): Promise<ArrayBuffer> {\n // Use array of array to ensure that order is preserved regardless of how the specific js implementation orders\n // the keys of an object\n const signObject = [\n ['delegator', data.delegator],\n ['delegate', data.delegate],\n ['exchangeKey', ua2hex(await this.primitives.AES.exportKey(data.decryptedExchangeKey, 'raw'))],\n ['accessControlSecret', data.decryptedAccessControlSecret],\n ['publicKeysFingerprints', data.publicKeysFingerprintsV2.sort()],\n ]\n const signJson = JSON.stringify(signObject)\n return utf8_2ua(signJson)\n }\n\n private async bytesToSignForDelegatorSignature(data: { sharedSignatureKey: CryptoKey }): Promise<ArrayBuffer> {\n return this.primitives.sha256(await this.primitives.HMAC.exportKey(data.sharedSignatureKey))\n }\n\n // Generates a new exchange key\n private async generateExchangeKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = await this.primitives.randomBytes(32)\n return {\n key: await this.importExchangeKey(rawBytes),\n rawBytes,\n }\n }\n\n async importExchangeKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.AES.importKey('raw', decryptedBytes)\n }\n\n async exportExchangeKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.primitives.AES.exportKey(key, 'raw')\n }\n\n private async generateSharedSignatureKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const key = await this.primitives.HMAC.generateKey()\n return { key, rawBytes: await this.primitives.HMAC.exportKey(key) }\n }\n\n async importSharedSignatureKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.HMAC.importKey(decryptedBytes)\n }\n\n async exportSharedSignatureKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.primitives.HMAC.exportKey(key)\n }\n\n // Generates a new access control secret\n private async generateAccessControlSecret(): Promise<{\n secret: string // the imported secret\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = this.primitives.randomBytes(16)\n return {\n secret: await this.importAccessControlSecret(rawBytes),\n rawBytes,\n }\n }\n\n importAccessControlSecret(decryptedBytes: ArrayBuffer): Promise<string> {\n return Promise.resolve(ua2hex(decryptedBytes))\n }\n\n exportAccessControlSecret(secret: string): Promise<ArrayBuffer> {\n return Promise.resolve(hex2ua(secret))\n }\n\n private async encryptDataWithKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprintV1: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprintV2: string]: string }> {\n const res: { [keyPairFingerprintV2: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp] = ua2b64(await this.primitives.RSA.encrypt(key, new Uint8Array(rawData)))\n }\n return res\n }\n\n private async extractHmacFromRsaPrivate(privateRsaKey: CryptoKey): Promise<CryptoKey> {\n if (privateRsaKey.algorithm.name != 'RSA-OAEP' && !privateRsaKey.usages.includes('decrypt')) {\n throw new Error('Internal error: got unexpected key for signature/verification')\n }\n const keyBytes = await this.primitives.RSA.exportKey(privateRsaKey, 'pkcs8')\n const keyAsHmacBytes = await this.primitives.sha512(keyBytes)\n return await this.primitives.HMAC.importKey(keyAsHmacBytes, false)\n }\n\n private async signDataWithDelegatorKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprint: string]: string }> {\n const res: { [keyPairFingerprint: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintV1toV2(fp)] = ua2b64(await this.primitives.HMAC.sign(await this.extractHmacFromRsaPrivate(key), new Uint8Array(rawData)))\n }\n return res\n }\n\n private async verifyDelegatorSignature(\n exchangeData: ExchangeData,\n decryptedSharedSignatureKey: CryptoKey,\n verificationKeys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<Boolean> {\n const delegatorSignatureData = await this.bytesToSignForDelegatorSignature({\n sharedSignatureKey: decryptedSharedSignatureKey,\n })\n const keysByV2Fp = Object.fromEntries(Object.entries(verificationKeys).map(([fp, key]): [string, CryptoKey] => [fingerprintV1toV2(fp), key]))\n for (const [fp, signature] of Object.entries(exchangeData.delegatorSignature ?? {})) {\n const verificationKey = keysByV2Fp[fp]\n if (\n verificationKey &&\n (await this.primitives.HMAC.verify(await this.extractHmacFromRsaPrivate(verificationKey), delegatorSignatureData, b64_2ua(signature)))\n )\n return true\n }\n return false\n }\n\n private async signDataWithSharedKey(rawData: ArrayBuffer, key: CryptoKey): Promise<string> {\n return ua2b64(await this.primitives.HMAC.sign(key, new Uint8Array(rawData)))\n }\n\n private async verifyDataWithSharedKey(rawData: ArrayBuffer, key: CryptoKey, signature: string): Promise<boolean> {\n return await this.primitives.HMAC.verify(key, new Uint8Array(rawData), b64_2ua(signature))\n }\n}\n"]}
|
|
1
|
+
{"version":3,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OAAO,CAAC,MAAA,YAAY,CAAC,kBAAkB,mCAAI,EAAE,CAAC,EAAE,CAAC;gBACpF,MAAM,eAAe,GAAG,UAAU,CAAC,EAAE,CAAC,CAAA;gBACtC,IACE,eAAe;oBACf,CAAC,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,yBAAyB,CAAC,eAAe,CAAC,EAAE,sBAAsB,EAAE,IAAA,aAAK,EAAC,IAAA,eAAO,EAAC,SAAS,CAAC,CAAC,CAAC,CAAC;oBAE7I,OAAO,IAAI,CAAA;YACf,CAAC;YACD,OAAO,KAAK,CAAA;QACd,CAAC;KAAA;IAEa,qBAAqB,CAAC,OAAoB,EAAE,GAAc;;YACtE,OAAO,IAAA,cAAM,EAAC,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAA;QACrF,CAAC;KAAA;IAEa,uBAAuB,CAAC,OAAoB,EAAE,GAAc,EAAE,SAAiB;;YAC3F,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,IAAA,aAAK,EAAC,IAAA,eAAO,EAAC,SAAS,CAAC,CAAC,CAAC,CAAA;QAC1G,CAAC;KAAA;CACF;AAlkBD,0DAkkBC","sourcesContent":["import { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair } from './RSA'\nimport { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { IccExchangeDataApi } from '../../icc-api/api/internal/IccExchangeDataApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { b64_2ua, hex2ua, ua2ab, ua2b64, ua2hex, utf8_2ua } from '../utils'\nimport * as _ from 'lodash'\nimport { fingerprintIsV1, fingerprintV1toV2 } from './utils'\nimport XHRError = XHR.XHRError\n\n/**\n * @internal this class is intended for internal use only and may be modified without notice\n * Functions to create and get exchange data.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeDataManager {\n constructor(\n readonly api: IccExchangeDataApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly primitives: CryptoPrimitives,\n private readonly selfRequiresAnonymousDelegations: boolean,\n private readonly doNotUseBulkGet: boolean\n ) {}\n\n /**\n * Get all the exchange data where the current data owner is the delegator or the delegate. However, some data owners, generally HCPs, may have a\n * prohibitively high amount of exchange data. If the crypto strategies specify that the current data owner requires anonymous delegation this\n * method returns all the exchange data found for the data owner, else the method returns undefined.\n * @return all the exchange data for the current data owner or undefined if the crypto strategies don't allow to retrieve all data for the current\n * data owner.\n */\n async getAllExchangeDataForCurrentDataOwnerIfAllowed(): Promise<ExchangeData[] | undefined> {\n if (!this.selfRequiresAnonymousDelegations) return undefined\n const dataOwnerId = await this.dataOwnerApi.getCurrentDataOwnerId()\n let latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, undefined, 1000)\n const allRetrieved = latestResult.rows ?? []\n while (latestResult.nextKeyPair?.startKeyDocId) {\n latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, latestResult.nextKeyPair.startKeyDocId, 1000)\n if (latestResult.rows) allRetrieved.push(...latestResult.rows)\n }\n return allRetrieved\n }\n\n /**\n * Get all exchange data for the provided delegator-delegate pair.\n * @param delegatorId id of a delegator data owner.\n * @param delegateId id of a delegate data owner.\n * @return all exchange data for the provided delegator-delegate pair.\n */\n async getExchangeDataByDelegatorDelegatePair(delegatorId: string, delegateId: string): Promise<ExchangeData[]> {\n return await this.api.getExchangeDataByDelegatorDelegate(delegatorId, delegateId)\n }\n\n /**\n * Get the exchange data with the provided id.\n * @param exchangeDataId id of the exchange data.\n * @return the exchange data with the provided id or undefined if no exchange data with such id could be found.\n */\n async getExchangeDataById(exchangeDataId: string): Promise<ExchangeData | undefined> {\n return await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && e.statusCode === 404) {\n return undefined\n } else throw e\n })\n }\n\n async getExchangeDataByIds(exchangeDataIds: string[]): Promise<ExchangeData[]> {\n if (this.doNotUseBulkGet) {\n const res: ExchangeData[] = []\n for (const exchangeDataId of exchangeDataIds) {\n const curr = await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && (e.statusCode === 404 || e.statusCode === 403)) {\n return undefined\n } else throw e\n })\n if (curr) res.push(curr)\n }\n return res\n } else {\n return await this.api.getExchangeDataByIds({ ids: exchangeDataIds })\n }\n }\n\n /**\n * Verifies the authenticity of the exchange data by checking the signature.\n * Note that all exchange data created by data owners other than the current data owner (including members of his hierarchy)\n * will always be unverified.\n * @param data collects the following information about the exchange data being verified:\n * - exchangeData the exchange data to verify.\n * - decryptedAccessControlSecret the access control secret decrypted from the exchange data.\n * - decryptedExchangeKey the exchange key decrypted from the exchange data.\n * - decryptedSharedSignatureKey the shared signature key decrypted from the exchange data.\n * @param verificationKeys verification keys for delegator signature by fingerprint.\n * @param verifyAsDelegator if true the method will also verify that the hmac key used for the signature was created by the delegator of the\n * exchange data. If true and the data was not created by the current data owner this method will return false.\n * @return the exchange data which could be verified given his signature and the available verification keys.\n * @throws if any of the provided exchange data has been created by a data owner other than the current data owner.\n */\n async verifyExchangeData(\n data: {\n exchangeData: ExchangeData\n decryptedAccessControlSecret: string\n decryptedExchangeKey: CryptoKey\n decryptedSharedSignatureKey: CryptoKey\n },\n verificationKeys: { [fp: string]: CryptoKey },\n verifyAsDelegator: boolean\n ): Promise<boolean> {\n if (verifyAsDelegator && data.exchangeData.delegator !== (await this.dataOwnerApi.getCurrentDataOwnerId())) return false\n if (verifyAsDelegator && !(await this.verifyDelegatorSignature(data.exchangeData, data.decryptedSharedSignatureKey, verificationKeys)))\n return false\n const sharedSignatureData = await this.bytesToSignForSharedSignature({\n decryptedAccessControlSecret: data.decryptedAccessControlSecret,\n decryptedExchangeKey: data.decryptedExchangeKey,\n delegator: data.exchangeData.delegator,\n delegate: data.exchangeData.delegate,\n publicKeysFingerprintsV2: [\n ...new Set([\n ...Object.keys(data.exchangeData.exchangeKey),\n ...Object.keys(data.exchangeData.accessControlSecret),\n ...Object.keys(data.exchangeData.sharedSignatureKey),\n ]),\n ],\n })\n return await this.verifyDataWithSharedKey(sharedSignatureData, data.decryptedSharedSignatureKey, data.exchangeData.sharedSignature)\n }\n\n /**\n * Extracts and decrypts the access control secret from the provided exchange data.\n * These need to be hashed together with the entity class and confidentiality level in order to get the actual access control key\n * which will be sent to the server.\n * @param exchangeData the exchange data from which to extract access control secrets.\n * @param decryptionKeys rsa key pairs to use for decryption of the access control secret.\n * @return an object composed of:\n * - successfulDecryptions: array of all successfully decrypted access control keys\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptAccessControlSecret(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: string[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.accessControlSecret,\n (d) => this.importAccessControlSecret(new Uint8Array(d).buffer)\n )\n }\n\n /**\n * Extract and decrypts the exchange keys from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptExchangeKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.exchangeKey,\n (d) => this.importExchangeKey(new Uint8Array(d).buffer)\n )\n }\n\n /**\n * Extract and decrypts the shared signature key from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptSharedSignatureKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.sharedSignatureKey,\n (d) => this.importSharedSignatureKey(new Uint8Array(d).buffer)\n )\n }\n\n private async tryDecryptExchangeData<T>(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n encryptedDataSelector: (data: ExchangeData) => { [keyPairFingerprint: string]: string },\n unmarshalDecrypted: (decrypted: ArrayBuffer) => Promise<T>\n ): Promise<{\n successfulDecryptions: T[]\n failedDecryptions: ExchangeData[]\n }> {\n const successfulDecryptions: T[] = []\n const failedDecryptions: ExchangeData[] = []\n for (const ed of exchangeData) {\n try {\n const decrypted = await this.tryDecrypt(encryptedDataSelector(ed), decryptionKeys)\n if (decrypted) {\n successfulDecryptions.push(await unmarshalDecrypted(decrypted))\n } else {\n failedDecryptions.push(ed)\n }\n } catch (e) {\n failedDecryptions.push(ed)\n }\n }\n return { successfulDecryptions, failedDecryptions }\n }\n\n private async tryDecrypt(\n encryptedData: { [keyPairFingerprintV2: string]: string },\n decryptionKeys: { [publicKeyFingerprintV1: string]: KeyPair<CryptoKey> }\n ): Promise<ArrayBuffer | undefined> {\n const decryptionKeysWithV2Fp = Object.keys(decryptionKeys).reduce((prev, fp) => {\n return {\n ...prev,\n [fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp]: decryptionKeys[fp],\n }\n }, {} as { [publicKeyFingerprint: string]: KeyPair<CryptoKey> })\n for (const [fp, encrypted] of Object.entries(encryptedData)) {\n try {\n const key = decryptionKeysWithV2Fp[fp]?.privateKey\n if (key) return await this.primitives.RSA.decrypt(key, b64_2ua(encrypted))\n } catch (e) {\n // Try with another key\n }\n }\n }\n\n /**\n * Creates exchange data from the current data owner to the provided delegate, uploading the newly created exchange data to the cloud.\n * This assumes that the keys have been verified.\n * @param delegateId id of the delegate for the new exchange data.\n * @param signatureKeys private keys to use for signing the created data.\n * @param encryptionKeys public keys to use for the encryption of the exchange data (from delegator and delegate).\n * @param optionalAttributes optional precalculated attributes for the creation of data\n * @return the newly created exchange data, and its decrypted exchange key and access control secret.\n */\n async createExchangeData(\n delegateId: string,\n signatureKeys: { [keyPairFingerprint: string]: CryptoKey },\n encryptionKeys: { [keyPairFingerprint: string]: CryptoKey },\n optionalAttributes: {\n id?: string\n } = {}\n ): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n sharedSignatureKey: CryptoKey\n }> {\n if (!Object.keys(encryptionKeys).length) {\n throw new Error('Must specify at least one encryption key ')\n }\n const exchangeKey = await this.generateExchangeKey()\n const accessControlSecret = await this.generateAccessControlSecret()\n const sharedSignatureKey = await this.generateSharedSignatureKey()\n const encryptedExchangeKey = await this.encryptDataWithKeys(exchangeKey.rawBytes, encryptionKeys)\n const encryptedAccessControlSecret = await this.encryptDataWithKeys(accessControlSecret.rawBytes, encryptionKeys)\n const encryptedSharedSignatureKey = await this.encryptDataWithKeys(sharedSignatureKey.rawBytes, encryptionKeys)\n const baseExchangeData = {\n id: optionalAttributes.id ?? this.primitives.randomUuid(),\n delegator: await this.dataOwnerApi.getCurrentDataOwnerId(),\n delegate: delegateId,\n exchangeKey: encryptedExchangeKey,\n accessControlSecret: encryptedAccessControlSecret,\n sharedSignatureKey: encryptedSharedSignatureKey,\n }\n const sharedSignature = await this.signDataWithSharedKey(\n await this.bytesToSignForSharedSignature({\n delegate: baseExchangeData.delegate,\n delegator: baseExchangeData.delegator,\n decryptedAccessControlSecret: accessControlSecret.secret,\n decryptedExchangeKey: exchangeKey.key,\n publicKeysFingerprintsV2: Object.keys(encryptionKeys).map(fingerprintV1toV2),\n }),\n sharedSignatureKey.key\n )\n const delegatorSignature = await this.signDataWithDelegatorKeys(\n await this.bytesToSignForDelegatorSignature({\n sharedSignatureKey: sharedSignatureKey.key,\n }),\n signatureKeys\n )\n const exchangeData = new ExchangeData({ ...baseExchangeData, delegatorSignature, sharedSignature })\n return {\n exchangeData: await this.api.createExchangeData(exchangeData),\n exchangeKey: exchangeKey.key,\n accessControlSecret: accessControlSecret.secret,\n sharedSignatureKey: sharedSignatureKey.key,\n }\n }\n\n async tryRawDecryptExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<\n | {\n rawExchangeKey: ArrayBuffer\n rawAccessControlSecret: ArrayBuffer\n rawSharedSignatureKey: ArrayBuffer\n }\n | undefined\n > {\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n const rawSharedSignatureKey = await this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey) return undefined\n return { rawExchangeKey, rawAccessControlSecret, rawSharedSignatureKey }\n }\n\n /**\n * Updates existing exchange data and uploads it to the cloud in order to share it also with additional public keys, useful for example in cases\n * where one of the data owners involved in the exchange data has lost one of his keys.\n * If the content of the exchange data could not be decrypted using the provided keys the method will not update anything and will return undefined.\n * This method assumes that the new encryption keys have been verified.\n * @param exchangeData exchange data to update.\n * @param decryptionKeys keys to use to extract the content of the exchange data which will be shared with the new keys.\n * @param newEncryptionKeys new keys to add to the exchange data.\n * @return the updated exchange data, and its decrypted exchange key and access control secret, or undefined if the exchange data content could not\n * be decrypted and the exchange data could not be updated.\n */\n async tryUpdateExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n newEncryptionKeys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<\n | {\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }\n | undefined\n > {\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n const rawSharedSignatureKey = await this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey) return undefined\n return await this.updateExchangeDataWithRawDecryptedContent({\n exchangeData: exchangeData,\n newEncryptionKeys: newEncryptionKeys,\n rawExchangeKey: rawExchangeKey,\n rawAccessControlSecret: rawAccessControlSecret,\n rawSharedSignatureKey: rawSharedSignatureKey,\n newDelegatorSignatureKeys: {},\n })\n }\n\n /**\n * Same as [tryUpdateExchangeData] but the decrypted content is already provided.\n */\n async updateExchangeDataWithRawDecryptedContent({\n exchangeData,\n newEncryptionKeys,\n rawExchangeKey,\n rawAccessControlSecret,\n rawSharedSignatureKey,\n newDelegatorSignatureKeys,\n }: {\n exchangeData: ExchangeData\n newEncryptionKeys: { [fp: string]: CryptoKey }\n newDelegatorSignatureKeys: { [keyPairFingerprint: string]: CryptoKey }\n rawExchangeKey: ArrayBuffer\n rawAccessControlSecret: ArrayBuffer\n rawSharedSignatureKey: ArrayBuffer\n }): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n const exchangeKey = await this.importExchangeKey(new Uint8Array(rawExchangeKey).buffer)\n const accessControlSecret = await this.importAccessControlSecret(new Uint8Array(rawAccessControlSecret).buffer)\n const sharedSignatureKey = await this.importSharedSignatureKey(new Uint8Array(rawSharedSignatureKey).buffer)\n const existingExchangeKeyEntries = new Set(Object.keys(exchangeData.exchangeKey))\n const existingAcsEntries = new Set(Object.keys(exchangeData.accessControlSecret))\n const existingSharedSignatureKeyEntries = new Set(Object.keys(exchangeData.sharedSignatureKey))\n const missingEntries = Object.keys(newEncryptionKeys).filter(\n (fp) => !existingAcsEntries.has(fp) || !existingExchangeKeyEntries.has(fp) || !existingSharedSignatureKeyEntries.has(fp)\n )\n const existingDelegatorSignatureEntries = new Set(Object.keys(exchangeData.delegatorSignature ?? {}))\n const missingDelegatorSignatureEntries =\n exchangeData.delegator == self ? Object.keys(newDelegatorSignatureKeys).filter((fp) => !existingDelegatorSignatureEntries.has(fp)) : []\n if (!missingEntries.length && !missingDelegatorSignatureEntries.length) return { exchangeData, exchangeKey, accessControlSecret }\n const encryptionKeysForMissingEntries = missingEntries.reduce((obj, fp) => {\n obj[fp] = newEncryptionKeys[fp]\n return obj\n }, {} as { [keyPairFingerprint: string]: CryptoKey })\n const updatedExchangeData = _.cloneDeep(exchangeData)\n updatedExchangeData.exchangeKey = {\n ...exchangeData.exchangeKey,\n ...(await this.encryptDataWithKeys(rawExchangeKey, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.accessControlSecret = {\n ...exchangeData.accessControlSecret,\n ...(await this.encryptDataWithKeys(rawAccessControlSecret, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.sharedSignatureKey = {\n ...exchangeData.sharedSignatureKey,\n ...(await this.encryptDataWithKeys(rawSharedSignatureKey, encryptionKeysForMissingEntries)),\n }\n const isVerified = await this.verifyExchangeData(\n {\n exchangeData,\n decryptedAccessControlSecret: accessControlSecret,\n decryptedExchangeKey: exchangeKey,\n decryptedSharedSignatureKey: sharedSignatureKey,\n },\n {},\n false\n )\n if (isVerified) {\n updatedExchangeData.sharedSignature = await this.signDataWithSharedKey(\n await this.bytesToSignForSharedSignature({\n delegate: updatedExchangeData.delegate,\n delegator: updatedExchangeData.delegator,\n decryptedAccessControlSecret: accessControlSecret,\n decryptedExchangeKey: exchangeKey,\n publicKeysFingerprintsV2: Object.keys(updatedExchangeData.exchangeKey),\n }),\n sharedSignatureKey\n )\n }\n if (missingDelegatorSignatureEntries.length > 0) {\n const bytesToSign = await this.bytesToSignForDelegatorSignature({ sharedSignatureKey })\n const newSigned = await this.signDataWithDelegatorKeys(\n bytesToSign,\n missingDelegatorSignatureEntries.reduce((obj, fp) => {\n obj[fp] = newDelegatorSignatureKeys[fp]\n return obj\n }, {} as { [keyPairFingerprint: string]: CryptoKey })\n )\n updatedExchangeData.delegatorSignature = {\n ...updatedExchangeData.delegatorSignature,\n ...newSigned,\n }\n }\n return { exchangeData: await this.api.modifyExchangeData(new ExchangeData(updatedExchangeData)), exchangeKey, accessControlSecret }\n }\n\n private async bytesToSignForSharedSignature(data: {\n delegator: string\n delegate: string\n decryptedAccessControlSecret: string\n decryptedExchangeKey: CryptoKey\n publicKeysFingerprintsV2: string[]\n }): Promise<ArrayBuffer> {\n // Use array of array to ensure that order is preserved regardless of how the specific js implementation orders\n // the keys of an object\n const signObject = [\n ['delegator', data.delegator],\n ['delegate', data.delegate],\n ['exchangeKey', ua2hex(await this.primitives.AES.exportKey(data.decryptedExchangeKey, 'raw'))],\n ['accessControlSecret', data.decryptedAccessControlSecret],\n ['publicKeysFingerprints', data.publicKeysFingerprintsV2.sort()],\n ]\n const signJson = JSON.stringify(signObject)\n return ua2ab(utf8_2ua(signJson))\n }\n\n private async bytesToSignForDelegatorSignature(data: { sharedSignatureKey: CryptoKey }): Promise<ArrayBuffer> {\n return this.primitives.sha256(await this.primitives.HMAC.exportKey(data.sharedSignatureKey))\n }\n\n // Generates a new exchange key\n private async generateExchangeKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = ua2ab(this.primitives.randomBytes(32))\n return {\n key: await this.importExchangeKey(rawBytes),\n rawBytes,\n }\n }\n\n async importExchangeKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.AES.importKey('raw', decryptedBytes)\n }\n\n async exportExchangeKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.primitives.AES.exportKey(key, 'raw')\n }\n\n private async generateSharedSignatureKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const key = await this.primitives.HMAC.generateKey()\n return { key, rawBytes: await this.primitives.HMAC.exportKey(key) }\n }\n\n async importSharedSignatureKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.HMAC.importKey(decryptedBytes)\n }\n\n async exportSharedSignatureKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.primitives.HMAC.exportKey(key)\n }\n\n // Generates a new access control secret\n private async generateAccessControlSecret(): Promise<{\n secret: string // the imported secret\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = ua2ab(this.primitives.randomBytes(16))\n return {\n secret: await this.importAccessControlSecret(rawBytes),\n rawBytes,\n }\n }\n\n importAccessControlSecret(decryptedBytes: ArrayBuffer): Promise<string> {\n return Promise.resolve(ua2hex(decryptedBytes))\n }\n\n exportAccessControlSecret(secret: string): Promise<ArrayBuffer> {\n return Promise.resolve(ua2ab(hex2ua(secret)))\n }\n\n private async encryptDataWithKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprintV1: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprintV2: string]: string }> {\n const res: { [keyPairFingerprintV2: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp] = ua2b64(await this.primitives.RSA.encrypt(key, new Uint8Array(rawData)))\n }\n return res\n }\n\n private async extractHmacFromRsaPrivate(privateRsaKey: CryptoKey): Promise<CryptoKey> {\n if (privateRsaKey.algorithm.name != 'RSA-OAEP' && !privateRsaKey.usages.includes('decrypt')) {\n throw new Error('Internal error: got unexpected key for signature/verification')\n }\n const keyBytes = await this.primitives.RSA.exportKey(privateRsaKey, 'pkcs8')\n const keyAsHmacBytes = await this.primitives.sha512(keyBytes)\n return await this.primitives.HMAC.importKey(keyAsHmacBytes, false)\n }\n\n private async signDataWithDelegatorKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprint: string]: string }> {\n const res: { [keyPairFingerprint: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintV1toV2(fp)] = ua2b64(await this.primitives.HMAC.sign(await this.extractHmacFromRsaPrivate(key), new Uint8Array(rawData).buffer))\n }\n return res\n }\n\n private async verifyDelegatorSignature(\n exchangeData: ExchangeData,\n decryptedSharedSignatureKey: CryptoKey,\n verificationKeys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<Boolean> {\n const delegatorSignatureData = await this.bytesToSignForDelegatorSignature({\n sharedSignatureKey: decryptedSharedSignatureKey,\n })\n const keysByV2Fp = Object.fromEntries(Object.entries(verificationKeys).map(([fp, key]): [string, CryptoKey] => [fingerprintV1toV2(fp), key]))\n for (const [fp, signature] of Object.entries(exchangeData.delegatorSignature ?? {})) {\n const verificationKey = keysByV2Fp[fp]\n if (\n verificationKey &&\n (await this.primitives.HMAC.verify(await this.extractHmacFromRsaPrivate(verificationKey), delegatorSignatureData, ua2ab(b64_2ua(signature))))\n )\n return true\n }\n return false\n }\n\n private async signDataWithSharedKey(rawData: ArrayBuffer, key: CryptoKey): Promise<string> {\n return ua2b64(await this.primitives.HMAC.sign(key, new Uint8Array(rawData).buffer))\n }\n\n private async verifyDataWithSharedKey(rawData: ArrayBuffer, key: CryptoKey, signature: string): Promise<boolean> {\n return await this.primitives.HMAC.verify(key, new Uint8Array(rawData).buffer, ua2ab(b64_2ua(signature)))\n }\n}\n"]}
|
|
@@ -41,7 +41,7 @@ class BaseExchangeKeysManager {
|
|
|
41
41
|
const newKeyHashVersion = (0, utils_2.getShaVersionForKey)(other.stub, newDataOwnerPublicKey);
|
|
42
42
|
if (!newKeyHashVersion)
|
|
43
43
|
throw new Error(`Public key not found for data owner ${otherDataOwner}`);
|
|
44
|
-
const newPublicKey = yield this.primitives.RSA.importKey('spki', (0, utils_1.hex2ua)(newDataOwnerPublicKey), ['encrypt'], newKeyHashVersion);
|
|
44
|
+
const newPublicKey = yield this.primitives.RSA.importKey('spki', (0, utils_1.ua2ab)((0, utils_1.hex2ua)(newDataOwnerPublicKey)), ['encrypt'], newKeyHashVersion);
|
|
45
45
|
yield this.extendForGiveAccessBackTo(selfId, otherDataOwner, (0, utils_2.fingerprintV1)(newDataOwnerPublicKey), newPublicKey, keyPairsByFingerprint);
|
|
46
46
|
yield this.extendForGiveAccessBackTo(otherDataOwner, selfId, (0, utils_2.fingerprintV1)(newDataOwnerPublicKey), newPublicKey, keyPairsByFingerprint);
|
|
47
47
|
});
|