@icure/api 8.0.23 → 8.0.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/icc-x-api/auth/JwtAuthService.js +11 -0
- package/icc-x-api/auth/JwtAuthService.js.map +1 -1
- package/icc-x-api/auth/JwtBridgedAuthService.js +17 -0
- package/icc-x-api/auth/JwtBridgedAuthService.js.map +1 -1
- package/icc-x-api/auth/JwtError.d.ts +7 -0
- package/icc-x-api/auth/JwtError.js +14 -0
- package/icc-x-api/auth/JwtError.js.map +1 -0
- package/icc-x-api/crypto/AES.d.ts +54 -2
- package/icc-x-api/crypto/AES.js +5 -5
- package/icc-x-api/crypto/AES.js.map +1 -1
- package/icc-x-api/crypto/CryptoPrimitives.d.ts +21 -12
- package/icc-x-api/crypto/CryptoPrimitives.js +8 -19
- package/icc-x-api/crypto/CryptoPrimitives.js.map +1 -1
- package/icc-x-api/crypto/DelegationsDeAnonymization.js +1 -1
- package/icc-x-api/crypto/DelegationsDeAnonymization.js.map +1 -1
- package/icc-x-api/crypto/HMACUtils.d.ts +8 -1
- package/icc-x-api/crypto/HMACUtils.js +3 -3
- package/icc-x-api/crypto/HMACUtils.js.map +1 -1
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.d.ts +113 -0
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.js +477 -0
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.js.map +1 -0
- package/icc-x-api/crypto/RSA.d.ts +107 -4
- package/icc-x-api/crypto/RSA.js +4 -4
- package/icc-x-api/crypto/RSA.js.map +1 -1
- package/icc-x-api/crypto/TransferKeysManager.js +6 -1
- package/icc-x-api/crypto/TransferKeysManager.js.map +1 -1
- package/icc-x-api/crypto/shamir.d.ts +7 -3
- package/icc-x-api/crypto/shamir.js +14 -5
- package/icc-x-api/crypto/shamir.js.map +1 -1
- package/icc-x-api/index.d.ts +1 -0
- package/icc-x-api/index.js +5 -3
- package/icc-x-api/index.js.map +1 -1
- package/package.json +1 -1
- package/test/icc-api/api/IccMedicalLocationApi.js +6 -6
- package/test/icc-api/api/IccMedicalLocationApi.js.map +1 -1
- package/test/icc-x-api/auth/jwt-provider-test.d.ts +1 -0
- package/test/icc-x-api/auth/jwt-provider-test.js +138 -0
- package/test/icc-x-api/auth/jwt-provider-test.js.map +1 -0
- package/test/icc-x-api/crud/comprehensive-crud-test.js +1 -1
- package/test/icc-x-api/crud/comprehensive-crud-test.js.map +1 -1
- package/test/icc-x-api/crud/entities-crud-test-interface.js +1 -0
- package/test/icc-x-api/crud/entities-crud-test-interface.js.map +1 -1
- package/test/icc-x-api/crypto/anonymous-delegations-test.js +1 -2
- package/test/icc-x-api/crypto/anonymous-delegations-test.js.map +1 -1
- package/test/icc-x-api/crypto/crypto-utils.js +1 -2
- package/test/icc-x-api/crypto/crypto-utils.js.map +1 -1
- package/test/icc-x-api/crypto/exchange-data-manager-test.js +1 -1
- package/test/icc-x-api/crypto/exchange-data-manager-test.js.map +1 -1
- package/test/icc-x-api/crypto/full-crypto-test.js +1 -2
- package/test/icc-x-api/crypto/full-crypto-test.js.map +1 -1
- package/test/icc-x-api/crypto/secure-delegations-manager-test.js +1 -1
- package/test/icc-x-api/crypto/secure-delegations-manager-test.js.map +1 -1
- package/test/icc-x-api/crypto/secure-delegations-metadata-decryptor-test.js +2 -2
- package/test/icc-x-api/crypto/secure-delegations-metadata-decryptor-test.js.map +1 -1
- package/test/icc-x-api/crypto/shamir.js +6 -7
- package/test/icc-x-api/crypto/shamir.js.map +1 -1
- package/test/icc-x-api/crypto/signature-keys-manager-test.js +1 -1
- package/test/icc-x-api/crypto/signature-keys-manager-test.js.map +1 -1
- package/test/icc-x-api/icc-maintenance-task-x-api-test.js +3 -2
- package/test/icc-x-api/icc-maintenance-task-x-api-test.js.map +1 -1
- package/test/icc-x-api/icc-user-x-api-test.js +1 -1
- package/test/icc-x-api/icc-user-x-api-test.js.map +1 -1
- package/test/icc-x-api/patient-user.js +1 -2
- package/test/icc-x-api/patient-user.js.map +1 -1
- package/test/icc-x-api/test-legacy-data-support.js +2 -3
- package/test/icc-x-api/test-legacy-data-support.js.map +1 -1
- package/test/utils/FakeDataOwnerApi.js +1 -1
- package/test/utils/FakeDataOwnerApi.js.map +1 -1
- package/test/utils/FakeGenericApi.js +1 -1
- package/test/utils/FakeGenericApi.js.map +1 -1
- package/test/utils/TestApi.js +1 -1
- package/test/utils/TestApi.js.map +1 -1
- package/test/utils/TestCryptoStrategies.js +1 -1
- package/test/utils/TestCryptoStrategies.js.map +1 -1
- package/test/utils/test_utils.js +6 -6
- package/test/utils/test_utils.js.map +1 -1
- package/test/icc-api/api/IccArticleApi.d.ts +0 -1
- package/test/icc-api/api/IccArticleApi.js +0 -64
- package/test/icc-api/api/IccArticleApi.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NativeCryptoPrimitivesBridge.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/NativeCryptoPrimitivesBridge.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,qCAAsC;AAGtC,oCAA6E;AAC7E,mCAAoC;AAEpC;;GAEG;AACH,MAAa,4BAA4B;IACvC,YAAY,iBAAoI;QAC9I,IAAI,CAAC,YAAY,GAAG,iBAAiB,CAAC,YAAY,CAAA;QAClD,IAAI,CAAC,MAAM,GAAG,iBAAiB,CAAC,MAAM,CAAA;QACtC,IAAI,CAAC,MAAM,GAAG,IAAI,kBAAkB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAA;QACvD,IAAI,CAAC,GAAG,GAAG,IAAI,eAAe,CAAC,iBAAiB,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,CAAA;QACxE,IAAI,CAAC,IAAI,GAAG,IAAI,gBAAgB,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAA;QACxD,IAAI,CAAC,GAAG,GAAG,IAAI,eAAe,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAA;IACvD,CAAC;IASD,W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QACN,OAAO,QAAQ,CAAA;IACjB,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAA;IACpE,CAAC;IAED,MAAM;QACJ,OAAO,EAAE,CAAA;IACX,CAAC;CACF;AAED,IAAK,YAEJ;AAFD,WAAK,YAAY;IACf,2CAA2B,CAAA;AAC7B,CAAC,EAFI,YAAY,KAAZ,YAAY,QAEhB;AACD,IAAK,sBAGJ;AAHD,WAAK,sBAAsB;IACzB,uDAA6B,CAAA;IAC7B,2DAAiC,CAAA;AACnC,CAAC,EAHI,sBAAsB,KAAtB,sBAAsB,QAG1B;AACD,IAAK,qBAEJ;AAFD,WAAK,qBAAqB;IACxB,wDAA+B,CAAA;AACjC,CAAC,EAFI,qBAAqB,KAArB,qBAAqB,QAEzB;AAED,IAAK,aAEJ;AAFD,WAAK,aAAa;IAChB,0CAAyB,CAAA;AAC3B,CAAC,EAFI,aAAa,KAAb,aAAa,QAEjB","sourcesContent":["import { CryptoPrimitives } from './CryptoPrimitives'\nimport { HMACUtils } from './HMACUtils'\nimport { ShamirClass } from './shamir'\nimport { AESUtils } from './AES'\nimport { KeyPair, RSAUtils, ShaVersion } from './RSA'\nimport { b64_2ua, hex2ua, ua2b64, ua2hex, ua2utf8, utf8_2ua } from '../utils'\nimport { randomBytes } from 'crypto'\n\n/**\n * Allows to use the expo-kryptom module as crypto primitives. This is necessary when building expo (react native) apps.\n */\nexport class NativeCryptoPrimitivesBridge implements CryptoPrimitives {\n constructor(expoKryptomModule: { Aes: AesService; Rsa: RsaService; Hmac: HmacService; StrongRandom: StrongRandomService; Digest: DigestService }) {\n this.strongRandom = expoKryptomModule.StrongRandom\n this.digest = expoKryptomModule.Digest\n this.shamir = new StrongRandomShamir(this.strongRandom)\n this.AES = new NativeAesBridge(expoKryptomModule.Aes, this.strongRandom)\n this.HMAC = new NativeHmacBridge(expoKryptomModule.Hmac)\n this.RSA = new NativeRsaBridge(expoKryptomModule.Rsa)\n }\n\n readonly AES: AESUtils\n readonly HMAC: HMACUtils\n readonly RSA: RSAUtils\n readonly shamir: ShamirClass\n private readonly strongRandom: StrongRandomService\n private readonly digest: DigestService\n\n randomBytes(n: number): Uint8Array {\n return this.strongRandom.randomBytes(n)\n }\n\n randomUuid(): string {\n return this.strongRandom.randomUUID()\n }\n\n async sha256(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return await this.digest.sha256(data instanceof ArrayBuffer ? new Uint8Array(data) : data)\n }\n}\n\nclass StrongRandomShamir extends ShamirClass {\n constructor(private readonly strongRandom: StrongRandomService) {\n super()\n }\n\n protected fillRandom(arr: Uint32Array): void {\n const random = this.strongRandom.randomBytes(arr.byteLength)\n // Note that the new Uint32Array does not copy the random array\n arr.set(new Uint32Array(random.buffer))\n }\n}\n\nclass NativeAesBridge implements AESUtils {\n constructor(private readonly aes: AesService, private readonly random: StrongRandomService) {}\n\n async decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return await this.aes.decrypt(new Uint8Array(encryptedData), getKryptomKey(cryptoKey))\n }\n\n 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 async decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n const imported = await this.importKey('raw', hex2ua(rawKey))\n return this.decrypt(imported, plainData)\n }\n\n async encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return await this.aes.encrypt(new Uint8Array(plainData), getKryptomKey(cryptoKey), null)\n }\n\n async encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n const imported = await this.importKey('raw', hex2ua(rawKey))\n return this.encrypt(imported, plainData)\n }\n\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n async exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey> {\n const rawKey = await this.aes.exportRawKey(getKryptomKey(cryptoKey))\n if (format == 'raw') return rawKey\n return {\n kty: 'oct',\n alg: rawKey.byteLength == 32 ? 'A256CBC' : 'A128CBC',\n ext: true,\n key_ops: ['encrypt', 'decrypt'],\n k: ua2b64(rawKey).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_'),\n }\n }\n\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n generateCryptoKey(toHex: true): Promise<string>\n async generateCryptoKey(toHex: boolean): Promise<string | CryptoKey> {\n if (toHex) {\n return Promise.resolve(ua2hex(this.random.randomBytes(32)))\n } else {\n const aesKey = await this.aes.generateKey(AesAlgorithm.AesCbcPkcs7, 256)\n return new AesCryptoKey(aesKey, 256)\n }\n }\n\n generateIV(ivByteLength: number): Uint8Array {\n return randomBytes(ivByteLength)\n }\n\n async importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey> {\n let keyBytes: Uint8Array\n if (format === 'jwk') {\n if (\n (aesKey as JsonWebKey).kty !== 'oct' ||\n ((aesKey as JsonWebKey).alg !== 'A256CBC' && (aesKey as JsonWebKey).alg !== 'A128CBC') ||\n !(aesKey as JsonWebKey).ext ||\n !(aesKey as JsonWebKey).key_ops?.includes('encrypt') ||\n !(aesKey as JsonWebKey).key_ops?.includes('decrypt') ||\n !(aesKey as JsonWebKey).k\n ) {\n throw new Error(\n 'Invalid JWK - must have kty=oct, alg=(A256CBC||A128CBC), ext=true, key_ops=[encrypt, decrypt], and must have non-empty k field'\n )\n }\n // b64_2ua works also with url-safe base64\n keyBytes = new Uint8Array(b64_2ua((aesKey as JsonWebKey).k!))\n } else if (format === 'raw') {\n if (aesKey! instanceof ArrayBuffer && !ArrayBuffer.isView(aesKey))\n throw new Error(\"aesKey must be an ArrayBuffer or an ArrayBufferView when format is 'raw'\")\n keyBytes = new Uint8Array(aesKey as ArrayBufferLike)\n } else throw new Error(`Invalid format ${format}`)\n const imported = await this.aes.importRawKey(keyBytes, AesAlgorithm.AesCbcPkcs7)\n return new AesCryptoKey(imported, keyBytes.length)\n }\n}\n\nfunction getKryptomKey<T>(cryptoKey: CryptoKey) {\n if ('kryptomKey' in cryptoKey) {\n return cryptoKey.kryptomKey as T\n } else throw new Error('Invalid crypto key: only crypto keys generated or loaded with this implementation of crypto primitives are supported')\n}\n\nclass AesCryptoKey implements CryptoKey {\n constructor(readonly kryptomKey: AesKey, readonly size: number) {}\n\n get algorithm(): AesKeyAlgorithm {\n return { name: 'AES-CBC', length: this.size }\n }\n get extractable(): boolean {\n return true\n }\n get type(): KeyType {\n return 'secret'\n }\n get usages(): KeyUsage[] {\n return ['encrypt', 'decrypt']\n }\n\n toJSON() {\n return {}\n }\n}\n\nclass NativeHmacBridge implements HMACUtils {\n constructor(private readonly hmac: HmacService) {}\n\n async exportKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.hmac.exportRawKey(getKryptomKey(key))\n }\n\n async generateKey(): Promise<CryptoKey> {\n const kryptomKey = await this.hmac.generateKey(HmacAlgorithm.HmacSha512)\n return new HmacCryptoKey(kryptomKey)\n }\n\n async importKey(key: ArrayBuffer): Promise<CryptoKey> {\n const kryptomKey = await this.hmac.importRawKey(new Uint8Array(key), HmacAlgorithm.HmacSha512)\n return new HmacCryptoKey(kryptomKey)\n }\n\n async sign(key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer> {\n return await this.hmac.sign(new Uint8Array(data), getKryptomKey(key))\n }\n\n async verify(key: CryptoKey, data: ArrayBuffer, signature: ArrayBuffer): Promise<boolean> {\n return await this.hmac.verify(new Uint8Array(signature), new Uint8Array(data), getKryptomKey(key))\n }\n}\n\nclass HmacCryptoKey implements CryptoKey {\n constructor(readonly kryptomKey: HmacKey) {}\n\n get algorithm(): HmacKeyAlgorithm {\n return { name: 'HMAC', hash: { name: 'SHA-512' }, length: 1024 }\n }\n get extractable(): boolean {\n return true\n }\n get type(): KeyType {\n return 'secret'\n }\n get usages(): KeyUsage[] {\n return ['sign', 'verify']\n }\n\n toJSON() {\n return {}\n }\n}\n\nclass NativeRsaBridge implements RSAUtils {\n constructor(private readonly rsa: RsaService) {}\n\n async checkKeyPairValidity(keyPair: KeyPair<CryptoKey>): Promise<boolean> {\n try {\n const text = 'shibboleth'\n const encryptedText = await this.encrypt(keyPair.publicKey, utf8_2ua(text))\n const decryptedText = ua2utf8(await this.decrypt(keyPair.privateKey, new Uint8Array(encryptedText)))\n return decryptedText === text\n } catch (e) {\n return false\n }\n }\n\n async decrypt(privateKey: CryptoKey, encryptedData: Uint8Array): Promise<ArrayBuffer> {\n return await this.rsa.decrypt(encryptedData, getKryptomKey(privateKey))\n }\n\n async encrypt(publicKey: CryptoKey, plainData: Uint8Array): Promise<ArrayBuffer> {\n return await this.rsa.encrypt(plainData, getKryptomKey(publicKey))\n }\n\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'spki'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'pkcs8'): Promise<ArrayBuffer>\n async exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'spki' | 'pkcs8'): Promise<JsonWebKey | ArrayBuffer> {\n if (format === 'jwk') {\n if (cryptoKey.type === 'private') {\n return await this.rsa.exportPrivateKeyJwk(getKryptomKey(cryptoKey))\n } else {\n return await this.rsa.exportPublicKeyJwk(getKryptomKey(cryptoKey))\n }\n } else if (format === 'spki') {\n return await this.rsa.exportPrivateKeyPkcs8(getKryptomKey(cryptoKey))\n } else if (format === 'pkcs8') {\n return await this.rsa.exportPublicKeySpki(getKryptomKey(cryptoKey))\n } else throw new Error(`Invalid format ${format}`)\n }\n\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'jwk', pubKeyFormat: 'jwk'): Promise<KeyPair<JsonWebKey>>\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'pkcs8', pubKeyFormat: 'spki'): Promise<KeyPair<ArrayBuffer>>\n async exportKeys(\n keyPair: KeyPair<CryptoKey>,\n privKeyFormat: 'jwk' | 'pkcs8',\n pubKeyFormat: 'jwk' | 'spki'\n ): Promise<KeyPair<JsonWebKey | ArrayBuffer>> {\n let privateKey: JsonWebKey | ArrayBuffer\n if (privKeyFormat === 'jwk') {\n privateKey = await this.rsa.exportPrivateKeyJwk(getKryptomKey(keyPair.privateKey))\n } else {\n privateKey = await this.rsa.exportPrivateKeyPkcs8(getKryptomKey(keyPair.privateKey))\n }\n let publicKey: JsonWebKey | ArrayBuffer\n if (pubKeyFormat === 'jwk') {\n publicKey = await this.rsa.exportPublicKeyJwk(getKryptomKey(keyPair.publicKey))\n } else {\n publicKey = await this.rsa.exportPublicKeySpki(getKryptomKey(keyPair.publicKey))\n }\n return { privateKey, publicKey }\n }\n\n async generateKeyPair(shaVersion: ShaVersion): Promise<KeyPair<CryptoKey>> {\n const generated = await this.rsa.generateKey(this.kryptomAlgorithm(shaVersion), 2048)\n // In expo-kryptom a private keys and public keys are supertypes of keypair.\n return {\n privateKey: new PrivateRsaCryptoKey(generated, this.encryptionKeysAlgorithm(shaVersion)),\n publicKey: new PublicRsaCryptoKey(generated, this.encryptionKeysAlgorithm(shaVersion)),\n }\n }\n\n async generateSignatureKeyPair(): Promise<KeyPair<CryptoKey>> {\n const generated = await this.rsa.generateKey(RsaSignatureAlgorithm.PssWithSha256, 2048)\n return {\n privateKey: new PrivateRsaCryptoKey(generated, this.signatureKeysAlgorithm()),\n publicKey: new PublicRsaCryptoKey(generated, this.signatureKeysAlgorithm()),\n }\n }\n\n importKey(\n format: 'jwk' | 'spki' | 'pkcs8',\n keydata: JsonWebKey | ArrayBuffer,\n keyUsages: KeyUsage[],\n hashAlgorithm: ShaVersion\n ): Promise<CryptoKey> {\n if (keyUsages[0] == 'encrypt' && (format == 'jwk' || format == 'spki')) {\n return this.importPublicKey(format, keydata, hashAlgorithm)\n } else if (keyUsages[0] == 'decrypt' && (format == 'jwk' || format == 'pkcs8')) {\n return this.importPrivateKey(format, keydata, hashAlgorithm)\n } else throw new Error(`Combination of key usages and key format not supported: ${keyUsages} ${format}`)\n }\n\n async importKeyPair(\n privateKeyFormat: string,\n privateKeydata: JsonWebKey | ArrayBuffer,\n publicKeyFormat: string,\n publicKeyData: JsonWebKey | ArrayBuffer,\n hashAlgorithm: ShaVersion\n ): Promise<KeyPair<CryptoKey>> {\n let importedPrivate: RsaPrivateKey\n let importedPublic: RsaPublicKey\n const algorithm = this.kryptomAlgorithm(hashAlgorithm)\n if (privateKeyFormat == 'jwk') {\n importedPrivate = await this.rsa.importPrivateKeyJwk(privateKeydata as PrivateRsaKeyJwk, algorithm)\n } else {\n importedPrivate = await this.rsa.importPrivateKeyPkcs8(new Uint8Array(privateKeydata as ArrayBuffer), algorithm)\n }\n if (publicKeyFormat == 'jwk') {\n importedPublic = await this.rsa.importPublicKeyJwk(publicKeyData as PublicRsaKeyJwk, algorithm)\n } else {\n importedPublic = await this.rsa.importPublicKeySpki(new Uint8Array(publicKeyData as ArrayBuffer), algorithm)\n }\n return {\n privateKey: new PrivateRsaCryptoKey(importedPrivate, this.encryptionKeysAlgorithm(hashAlgorithm)),\n publicKey: new PublicRsaCryptoKey(importedPublic, this.encryptionKeysAlgorithm(hashAlgorithm)),\n }\n }\n\n async importPrivateKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer, hashAlgorithm: ShaVersion): Promise<CryptoKey> {\n let imported: RsaPrivateKey\n if (format == 'jwk') {\n imported = await this.rsa.importPrivateKeyJwk(keydata as PrivateRsaKeyJwk, this.kryptomAlgorithm(hashAlgorithm))\n } else {\n imported = await this.rsa.importPrivateKeyPkcs8(new Uint8Array(keydata as ArrayBuffer), this.kryptomAlgorithm(hashAlgorithm))\n }\n return new PrivateRsaCryptoKey(imported, this.encryptionKeysAlgorithm(hashAlgorithm))\n }\n\n async importPublicKey(format: 'jwk' | 'spki', keydata: JsonWebKey | ArrayBuffer, hashAlgorithm: ShaVersion): Promise<CryptoKey> {\n let imported: RsaPublicKey\n if (format == 'jwk') {\n imported = await this.rsa.importPublicKeyJwk(keydata as PublicRsaKeyJwk, this.kryptomAlgorithm(hashAlgorithm))\n } else {\n imported = await this.rsa.importPublicKeySpki(new Uint8Array(keydata as ArrayBuffer), this.kryptomAlgorithm(hashAlgorithm))\n }\n return new PublicRsaCryptoKey(imported, this.encryptionKeysAlgorithm(hashAlgorithm))\n }\n\n async importSignatureKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey> {\n let importedKey: RsaPrivateKey\n if (format == 'jwk') {\n importedKey = await this.rsa.importPrivateKeyJwk(keydata as PrivateRsaKeyJwk, RsaSignatureAlgorithm.PssWithSha256)\n } else {\n importedKey = await this.rsa.importPrivateKeyPkcs8(new Uint8Array(keydata as ArrayBuffer), RsaSignatureAlgorithm.PssWithSha256)\n }\n return new PrivateRsaCryptoKey(importedKey, this.signatureKeysAlgorithm())\n }\n\n async importVerificationKey(format: 'jwk' | 'spki', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey> {\n let importedKey: RsaPublicKey\n if (format == 'jwk') {\n importedKey = await this.rsa.importPublicKeyJwk(keydata as PublicRsaKeyJwk, RsaSignatureAlgorithm.PssWithSha256)\n } else {\n importedKey = await this.rsa.importPublicKeySpki(new Uint8Array(keydata as ArrayBuffer), RsaSignatureAlgorithm.PssWithSha256)\n }\n return new PublicRsaCryptoKey(importedKey, this.signatureKeysAlgorithm())\n }\n\n async sign(privateKey: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer> {\n return await this.rsa.signature(new Uint8Array(data), getKryptomKey(privateKey))\n }\n\n async verifySignature(publicKey: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer): Promise<boolean> {\n return await this.rsa.verify(new Uint8Array(signature), new Uint8Array(data), getKryptomKey(publicKey))\n }\n\n private kryptomAlgorithm(shaVersion: ShaVersion): RsaEncryptionAlgorithm {\n return shaVersion == 'sha-256' ? RsaEncryptionAlgorithm.OaepWithSha256 : RsaEncryptionAlgorithm.OaepWithSha1\n }\n\n private encryptionKeysAlgorithm(shaVersion: ShaVersion): RsaHashedKeyAlgorithm {\n return {\n name: 'RSA-OAEP',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: shaVersion == 'sha-256' ? 'SHA-256' : 'SHA-1' },\n }\n }\n\n private signatureKeysAlgorithm(): RsaHashedKeyAlgorithm {\n return {\n name: 'RSA-PSS',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'SHA-256' },\n }\n }\n}\n\nclass PrivateRsaCryptoKey implements CryptoKey {\n constructor(readonly kryptomKey: RsaPrivateKey, readonly algorithm: RsaKeyAlgorithm) {}\n\n get extractable(): boolean {\n return true\n }\n\n get type(): KeyType {\n return 'private'\n }\n\n get usages(): KeyUsage[] {\n return this.algorithm.name != 'RSA-PSS' ? ['decrypt'] : ['sign']\n }\n\n toJSON() {\n return {}\n }\n}\n\nclass PublicRsaCryptoKey implements CryptoKey {\n constructor(readonly kryptomKey: RsaPublicKey, readonly algorithm: RsaKeyAlgorithm) {}\n\n get extractable(): boolean {\n return true\n }\n\n get type(): KeyType {\n return 'public'\n }\n\n get usages(): KeyUsage[] {\n return this.algorithm.name != 'RSA-PSS' ? ['encrypt'] : ['verify']\n }\n\n toJSON() {\n return {}\n }\n}\n\nenum AesAlgorithm {\n AesCbcPkcs7 = 'AesCbcPkcs7',\n}\nenum RsaEncryptionAlgorithm {\n OaepWithSha1 = 'OaepWithSha1',\n OaepWithSha256 = 'OaepWithSha256',\n}\nenum RsaSignatureAlgorithm {\n PssWithSha256 = 'PssWithSha256',\n}\ntype RsaAlgorithm = RsaEncryptionAlgorithm | RsaSignatureAlgorithm\nenum HmacAlgorithm {\n HmacSha512 = 'HmacSha512',\n}\n\ninterface HmacKey {\n algorithmIdentifier: HmacAlgorithm\n}\n\ninterface AesKey {\n algorithmIdentifier: AesAlgorithm\n}\n\ninterface RsaKeyPair {\n algorithmIdentifier: RsaAlgorithm\n}\n\ninterface RsaPrivateKey {\n algorithmIdentifier: RsaAlgorithm\n}\n\ninterface RsaPublicKey {\n algorithmIdentifier: RsaAlgorithm\n}\n\ntype PrivateRsaKeyJwk = {\n alg: string\n d: string\n dp: string\n dq: string\n e: string\n ext: boolean\n key_ops: string[]\n n: string\n p: string\n q: string\n qi: string\n}\n\ntype PublicRsaKeyJwk = {\n alg: string\n e: string\n ext: boolean\n key_ops: string[]\n n: string\n}\n\ninterface AesService {\n generateKey(algorithmIdentifier: AesAlgorithm, size: number): Promise<AesKey>\n encrypt(data: Uint8Array, key: AesKey, iv: Uint8Array | null): Promise<Uint8Array>\n decrypt(ivAndEncryptedData: Uint8Array, key: AesKey): Promise<Uint8Array>\n exportRawKey(key: AesKey): Promise<Uint8Array>\n importRawKey(rawKey: Uint8Array, algorithmIdentifier: AesAlgorithm): Promise<AesKey>\n}\n\ninterface RsaService {\n generateKey(algorithmIdentifier: RsaAlgorithm, size: number): Promise<RsaKeyPair>\n encrypt(data: Uint8Array, key: RsaPublicKey): Promise<Uint8Array>\n decrypt(data: Uint8Array, key: RsaPrivateKey): Promise<Uint8Array>\n signature(data: Uint8Array, key: RsaPrivateKey): Promise<Uint8Array>\n verify(signature: Uint8Array, data: Uint8Array, key: RsaPublicKey): Promise<boolean>\n exportPrivateKeyPkcs8(key: RsaPrivateKey): Promise<Uint8Array>\n exportPrivateKeyJwk(key: RsaPrivateKey): Promise<PrivateRsaKeyJwk>\n exportPublicKeySpki(key: RsaPublicKey): Promise<Uint8Array>\n exportPublicKeyJwk(key: RsaPublicKey): Promise<PublicRsaKeyJwk>\n importPrivateKeyPkcs8(privateKeyPkcs8: Uint8Array, algorithmIdentifier: RsaAlgorithm): Promise<RsaPrivateKey>\n importPrivateKeyJwk(privateKey: PrivateRsaKeyJwk, algorithmIdentifier: RsaAlgorithm): Promise<RsaPrivateKey>\n importPublicKeySpki(publicKeySpki: Uint8Array, algorithmIdentifier: RsaAlgorithm): Promise<RsaPublicKey>\n importPublicKeyJwk(publicKey: PublicRsaKeyJwk, algorithmIdentifier: RsaAlgorithm): Promise<RsaPublicKey>\n importKeyPair(privateKeyPkcs8: Uint8Array, algorithmIdentifier: RsaAlgorithm): Promise<RsaKeyPair>\n}\n\ninterface HmacService {\n generateKey(algorithmIdentifier: HmacAlgorithm): Promise<HmacKey>\n sign(data: Uint8Array, key: HmacKey): Promise<Uint8Array>\n verify(signature: Uint8Array, data: Uint8Array, key: HmacKey): Promise<boolean>\n exportRawKey(key: HmacKey): Promise<Uint8Array>\n importRawKey(rawKey: Uint8Array, algorithmIdentifier: HmacAlgorithm): Promise<HmacKey>\n}\n\ninterface StrongRandomService {\n randomBytes(length: number): Uint8Array\n randomUUID(): string\n}\n\ninterface DigestService {\n sha256(data: Uint8Array): Promise<Uint8Array>\n}\n"]}
|
|
@@ -9,7 +9,110 @@ export declare enum ShaVersion {
|
|
|
9
9
|
Sha1 = "sha-1",
|
|
10
10
|
Sha256 = "sha-256"
|
|
11
11
|
}
|
|
12
|
-
export
|
|
12
|
+
export interface RSAUtils {
|
|
13
|
+
/**
|
|
14
|
+
* Generates a key pair for encryption/decryption of data.
|
|
15
|
+
* @param shaVersion the version of the SHA algorithm to use.
|
|
16
|
+
*/
|
|
17
|
+
generateKeyPair(shaVersion: ShaVersion): Promise<KeyPair<CryptoKey>>;
|
|
18
|
+
/**
|
|
19
|
+
* Generates a key pair for signing data and signature verification.
|
|
20
|
+
*/
|
|
21
|
+
generateSignatureKeyPair(): Promise<KeyPair<CryptoKey>>;
|
|
22
|
+
/**
|
|
23
|
+
*
|
|
24
|
+
* 'JWK': Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)
|
|
25
|
+
* 'spki': for private key
|
|
26
|
+
* 'pkcs8': for private Key
|
|
27
|
+
*
|
|
28
|
+
* @param keyPair is {publicKey: CryptoKey, privateKey: CryptoKey}
|
|
29
|
+
* @param privKeyFormat will be 'pkcs8' or 'jwk'
|
|
30
|
+
* @param pubKeyFormat will be 'spki' or 'jwk'
|
|
31
|
+
* @returns {Promise} will the AES Key
|
|
32
|
+
*/
|
|
33
|
+
exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'jwk', pubKeyFormat: 'jwk'): Promise<KeyPair<JsonWebKey>>;
|
|
34
|
+
exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'pkcs8', pubKeyFormat: 'spki'): Promise<KeyPair<ArrayBuffer>>;
|
|
35
|
+
exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: string, pubKeyFormat: string): Promise<KeyPair<JsonWebKey | ArrayBuffer>>;
|
|
36
|
+
/**
|
|
37
|
+
* Format:
|
|
38
|
+
*
|
|
39
|
+
* 'JWK': Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)
|
|
40
|
+
* 'spki': for private key
|
|
41
|
+
* 'pkcs8': for private Key
|
|
42
|
+
*
|
|
43
|
+
* @param cryptoKey public or private
|
|
44
|
+
* @param format either 'jwk' or 'spki' or 'pkcs8'
|
|
45
|
+
* @returns {Promise|*} will be RSA key (public or private)
|
|
46
|
+
*/
|
|
47
|
+
exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>;
|
|
48
|
+
exportKey(cryptoKey: CryptoKey, format: 'spki'): Promise<ArrayBuffer>;
|
|
49
|
+
exportKey(cryptoKey: CryptoKey, format: 'pkcs8'): Promise<ArrayBuffer>;
|
|
50
|
+
exportKey(cryptoKey: CryptoKey, format: string): Promise<JsonWebKey | ArrayBuffer>;
|
|
51
|
+
/**
|
|
52
|
+
*
|
|
53
|
+
* @param publicKey (CryptoKey)
|
|
54
|
+
* @param plainData (Uint8Array)
|
|
55
|
+
*/
|
|
56
|
+
encrypt(publicKey: CryptoKey, plainData: Uint8Array): Promise<ArrayBuffer>;
|
|
57
|
+
/**
|
|
58
|
+
*
|
|
59
|
+
* @param privateKey (CryptoKey)
|
|
60
|
+
* @param encryptedData (Uint8Array)
|
|
61
|
+
*/
|
|
62
|
+
decrypt(privateKey: CryptoKey, encryptedData: Uint8Array): Promise<ArrayBuffer>;
|
|
63
|
+
/**
|
|
64
|
+
*
|
|
65
|
+
* @param format 'jwk', 'spki', or 'pkcs8'
|
|
66
|
+
* @param keydata should be the key data based on the format.
|
|
67
|
+
* @param keyUsages Array of usages. For example, ['encrypt'] for public key.
|
|
68
|
+
* @param hashAlgorithm 'sha-1' or 'sha-256'
|
|
69
|
+
* @returns {*}
|
|
70
|
+
*/
|
|
71
|
+
importKey(format: 'jwk' | 'spki' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer, keyUsages: KeyUsage[], hashAlgorithm: ShaVersion): Promise<CryptoKey>;
|
|
72
|
+
importSignatureKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey>;
|
|
73
|
+
importVerificationKey(format: 'jwk' | 'spki', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey>;
|
|
74
|
+
/**
|
|
75
|
+
*
|
|
76
|
+
* @param format 'jwk' or 'pkcs8'
|
|
77
|
+
* @param keydata should be the key data based on the format.
|
|
78
|
+
* @param hashAlgorithm 'sha-1' or 'sha-256'
|
|
79
|
+
* @returns {*}
|
|
80
|
+
*/
|
|
81
|
+
importPrivateKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer, hashAlgorithm: ShaVersion): Promise<CryptoKey>;
|
|
82
|
+
/**
|
|
83
|
+
*
|
|
84
|
+
* @param privateKeyFormat 'jwk' or 'pkcs8'
|
|
85
|
+
* @param privateKeydata should be the key data based on the format.
|
|
86
|
+
* @param publicKeyFormat 'jwk' or 'spki'
|
|
87
|
+
* @param publicKeyData should be the key data based on the format.
|
|
88
|
+
* @param hashAlgorithm 'sha-1' or 'sha-256'
|
|
89
|
+
* @returns {Promise|*}
|
|
90
|
+
*/
|
|
91
|
+
importKeyPair(privateKeyFormat: 'jwk' | 'pkcs8', privateKeydata: JsonWebKey | ArrayBuffer, publicKeyFormat: 'jwk' | 'spki', publicKeyData: JsonWebKey | ArrayBuffer, hashAlgorithm: ShaVersion): Promise<KeyPair<CryptoKey>>;
|
|
92
|
+
/**
|
|
93
|
+
* Tries to encrypt then decrypt data using a keypair. If both operations succeed without throwing an error and the decrypted data matches the
|
|
94
|
+
* original data returns true, else false.
|
|
95
|
+
* @param keyPair a key pair.
|
|
96
|
+
* @return if the key pair could be successfully used to encrypt then decrypt data.
|
|
97
|
+
*/
|
|
98
|
+
checkKeyPairValidity(keyPair: KeyPair<CryptoKey>): Promise<boolean>;
|
|
99
|
+
/**
|
|
100
|
+
* Generates a signature for some data. The signature algorithm used is RSA-PSS with SHA-256.
|
|
101
|
+
* @param privateKey private key to use for signature
|
|
102
|
+
* @param data the data to sign
|
|
103
|
+
* @return the signature.
|
|
104
|
+
*/
|
|
105
|
+
sign(privateKey: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
|
|
106
|
+
/**
|
|
107
|
+
* Verifies if a signature matches the data. The signature algorithm used is RSA-PSS with sha-256.
|
|
108
|
+
* @param publicKey public key to use for signature verification.
|
|
109
|
+
* @param signature the signature to verify
|
|
110
|
+
* @param data the data that was signed
|
|
111
|
+
* @return if the signature matches the data and key.
|
|
112
|
+
*/
|
|
113
|
+
verifySignature(publicKey: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer): Promise<boolean>;
|
|
114
|
+
}
|
|
115
|
+
export declare class RSAUtilsImpl implements RSAUtils {
|
|
13
116
|
/********* RSA Config **********/
|
|
14
117
|
rsaParams: any;
|
|
15
118
|
rsaHashedParams: any;
|
|
@@ -73,10 +176,10 @@ export declare class RSAUtils {
|
|
|
73
176
|
* @param hashAlgorithm 'sha-1' or 'sha-256'
|
|
74
177
|
* @returns {*}
|
|
75
178
|
*/
|
|
76
|
-
importKey(format:
|
|
179
|
+
importKey(format: 'jwk' | 'spki' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer, keyUsages: KeyUsage[], hashAlgorithm: ShaVersion): Promise<CryptoKey>;
|
|
77
180
|
importSignatureKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey>;
|
|
78
181
|
importVerificationKey(format: 'jwk' | 'spki', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey>;
|
|
79
|
-
|
|
182
|
+
paramsForCreationOrImport(shaVersion: ShaVersion): any;
|
|
80
183
|
/**
|
|
81
184
|
*
|
|
82
185
|
* @param format 'jwk' or 'pkcs8'
|
|
@@ -84,7 +187,7 @@ export declare class RSAUtils {
|
|
|
84
187
|
* @param hashAlgorithm 'sha-1' or 'sha-256'
|
|
85
188
|
* @returns {*}
|
|
86
189
|
*/
|
|
87
|
-
importPrivateKey(format:
|
|
190
|
+
importPrivateKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer, hashAlgorithm: ShaVersion): Promise<CryptoKey>;
|
|
88
191
|
/**
|
|
89
192
|
*
|
|
90
193
|
* @param privateKeyFormat 'jwk' or 'pkcs8'
|
package/icc-x-api/crypto/RSA.js
CHANGED
|
@@ -9,14 +9,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.RSA = exports.
|
|
12
|
+
exports.RSA = exports.RSAUtilsImpl = exports.ShaVersion = void 0;
|
|
13
13
|
const utils_1 = require("../utils");
|
|
14
14
|
var ShaVersion;
|
|
15
15
|
(function (ShaVersion) {
|
|
16
16
|
ShaVersion["Sha1"] = "sha-1";
|
|
17
17
|
ShaVersion["Sha256"] = "sha-256";
|
|
18
18
|
})(ShaVersion = exports.ShaVersion || (exports.ShaVersion = {}));
|
|
19
|
-
class
|
|
19
|
+
class RSAUtilsImpl {
|
|
20
20
|
constructor(crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : {}) {
|
|
21
21
|
/********* RSA Config **********/
|
|
22
22
|
//TODO bigger modulus
|
|
@@ -210,6 +210,6 @@ class RSAUtils {
|
|
|
210
210
|
});
|
|
211
211
|
}
|
|
212
212
|
}
|
|
213
|
-
exports.
|
|
214
|
-
exports.RSA = new
|
|
213
|
+
exports.RSAUtilsImpl = RSAUtilsImpl;
|
|
214
|
+
exports.RSA = new RSAUtilsImpl();
|
|
215
215
|
//# sourceMappingURL=RSA.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RSA.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/RSA.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oCAA4C;AAO5C,IAAY,UAGX;AAHD,WAAY,UAAU;IACpB,4BAAc,CAAA;IACd,gCAAkB,CAAA;AACpB,CAAC,EAHW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAGrB;AAED,MAAa,QAAQ;IA2BnB,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;QA1BvI,iCAAiC;QACjC,qBAAqB;QACrB,sBAAsB;QACtB,cAAS,GAAQ,EAAE,IAAI,EAAE,UAAU,EA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AE,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;QACzG,CAAC;KAAA;CACF;AA5OD,4BA4OC;AAEY,QAAA,GAAG,GAAG,IAAI,QAAQ,EAAE,CAAA","sourcesContent":["import { ua2utf8, utf8_2ua } from '../utils'\n\n/**\n * Represents an RSA KeyPair in a generic format.\n */\nexport type KeyPair<T> = { publicKey: T; privateKey: T }\n\nexport enum ShaVersion {\n Sha1 = 'sha-1',\n Sha256 = 'sha-256',\n}\n\nexport class RSAUtils {\n /********* RSA Config **********/\n //TODO bigger modulus\n //TODO PSS for signing\n rsaParams: any = { name: 'RSA-OAEP' }\n // RSA params for 'import' and 'generate' function.\n rsaHashedParams: any = {\n name: 'RSA-OAEP',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'sha-1' },\n }\n rsaWithSha256HashedParams: any = {\n name: 'RSA-OAEP',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'SHA-256' },\n }\n private readonly signatureKeysGenerationParams = {\n name: 'RSA-PSS',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'SHA-256' },\n }\n\n private crypto: Crypto\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this.crypto = crypto\n }\n\n /**\n * Generates a key pair for encryption/decryption of data.\n * @param shaVersion the version of the SHA algorithm to use.\n */\n generateKeyPair(shaVersion: ShaVersion): Promise<KeyPair<CryptoKey>> {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n const rsaParams = this.paramsForCreationOrImport(shaVersion)\n\n return new Promise<KeyPair<CryptoKey>>((resolve, reject) => {\n this.crypto.subtle.generateKey(rsaParams, extractable, keyUsages).then(resolve, reject)\n })\n }\n\n /**\n * Generates a key pair for signing data and signature verification.\n */\n async generateSignatureKeyPair(): Promise<KeyPair<CryptoKey>> {\n return await this.crypto.subtle.generateKey(this.signatureKeysGenerationParams, true, ['sign', 'verify'])\n }\n\n /**\n *\n * 'JWK': Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n * 'spki': for private key\n * 'pkcs8': for private Key\n *\n * @param keyPair is {publicKey: CryptoKey, privateKey: CryptoKey}\n * @param privKeyFormat will be 'pkcs8' or 'jwk'\n * @param pubKeyFormat will be 'spki' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'jwk', pubKeyFormat: 'jwk'): Promise<KeyPair<JsonWebKey>>\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'pkcs8', pubKeyFormat: 'spki'): Promise<KeyPair<ArrayBuffer>>\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: string, pubKeyFormat: string): Promise<KeyPair<JsonWebKey | ArrayBuffer>> {\n const pubPromise = this.crypto.subtle.exportKey(pubKeyFormat as any, keyPair.publicKey)\n const privPromise = this.crypto.subtle.exportKey(privKeyFormat as any, keyPair.privateKey)\n\n return Promise.all([pubPromise, privPromise]).then(function (results) {\n return {\n publicKey: results[0],\n privateKey: results[1],\n }\n })\n }\n\n /**\n * Format:\n *\n * 'JWK': Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n * 'spki': for private key\n * 'pkcs8': for private Key\n *\n * @param cryptoKey public or private\n * @param format either 'jwk' or 'spki' or 'pkcs8'\n * @returns {Promise|*} will be RSA key (public or private)\n */\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'spki'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'pkcs8'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: string): Promise<JsonWebKey | ArrayBuffer> {\n return new Promise((resolve: (value: JsonWebKey | ArrayBuffer) => any, reject) => {\n this.crypto.subtle.exportKey(format as any, cryptoKey).then(resolve, reject)\n })\n }\n\n /**\n *\n * @param publicKey (CryptoKey)\n * @param plainData (Uint8Array)\n */\n encrypt(publicKey: CryptoKey, plainData: Uint8Array): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject) => {\n this.crypto.subtle.encrypt(this.rsaParams, publicKey, plainData.buffer ? plainData.buffer : plainData).then(resolve, reject) //Node prefers arrayBuffer\n })\n }\n\n /**\n *\n * @param privateKey (CryptoKey)\n * @param encryptedData (Uint8Array)\n */\n decrypt(privateKey: CryptoKey, encryptedData: Uint8Array): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject) => {\n this.crypto.subtle.decrypt(this.rsaParams, privateKey, encryptedData).then(resolve, reject)\n })\n }\n\n /**\n *\n * @param format 'jwk', 'spki', or 'pkcs8'\n * @param keydata should be the key data based on the format.\n * @param keyUsages Array of usages. For example, ['encrypt'] for public key.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {*}\n */\n importKey(format: string, keydata: JsonWebKey | ArrayBuffer, keyUsages: KeyUsage[], hashAlgorithm: ShaVersion): Promise<CryptoKey> {\n const extractable = true\n return new Promise((resolve: (value: CryptoKey) => any, reject) => {\n const rsaParams = this.paramsForCreationOrImport(hashAlgorithm)\n this.crypto.subtle.importKey(format as any, keydata as any, rsaParams, extractable, keyUsages).then(resolve, reject)\n })\n }\n\n importSignatureKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey> {\n const extractable = true\n return this.crypto.subtle.importKey(format as any, keydata as any, this.signatureKeysGenerationParams, extractable, ['sign'])\n }\n\n importVerificationKey(format: 'jwk' | 'spki', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey> {\n const extractable = true\n return this.crypto.subtle.importKey(format as any, keydata as any, this.signatureKeysGenerationParams, extractable, ['verify'])\n }\n\n private paramsForCreationOrImport(shaVersion: ShaVersion) {\n if (shaVersion === 'sha-1') {\n return this.rsaHashedParams\n } else if (shaVersion === 'sha-256') {\n return this.rsaWithSha256HashedParams\n } else {\n throw new Error('Unexpected error, invalid SHA version')\n }\n }\n\n /**\n *\n * @param format 'jwk' or 'pkcs8'\n * @param keydata should be the key data based on the format.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {*}\n */\n importPrivateKey(format: string, keydata: JsonWebKey | ArrayBuffer, hashAlgorithm: ShaVersion): Promise<CryptoKey> {\n const extractable = true\n return new Promise((resolve: (value: CryptoKey) => any, reject) => {\n const rsaParams = this.paramsForCreationOrImport(hashAlgorithm)\n this.crypto.subtle.importKey(format as any, keydata as any, rsaParams, extractable, ['decrypt']).then(resolve, reject)\n })\n }\n\n /**\n *\n * @param privateKeyFormat 'jwk' or 'pkcs8'\n * @param privateKeydata should be the key data based on the format.\n * @param publicKeyFormat 'jwk' or 'spki'\n * @param publicKeyData should be the key data based on the format.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {Promise|*}\n */\n importKeyPair(\n privateKeyFormat: string,\n privateKeydata: JsonWebKey | ArrayBuffer,\n publicKeyFormat: string,\n publicKeyData: JsonWebKey | ArrayBuffer,\n hashAlgorithm: ShaVersion\n ): Promise<KeyPair<CryptoKey>> {\n const extractable = true\n const rsaParams = this.paramsForCreationOrImport(hashAlgorithm)\n const privPromise = this.crypto.subtle.importKey(privateKeyFormat as any, privateKeydata as any, rsaParams, extractable, ['decrypt'])\n const pubPromise = this.crypto.subtle.importKey(publicKeyFormat as any, publicKeyData as any, rsaParams, extractable, ['encrypt'])\n\n return Promise.all([pubPromise, privPromise]).then(function (results) {\n return {\n publicKey: results[0],\n privateKey: results[1],\n }\n })\n }\n\n /**\n * Tries to encrypt then decrypt data using a keypair. If both operations succeed without throwing an error and the decrypted data matches the\n * original data returns true, else false.\n * @param keyPair a key pair.\n * @return if the key pair could be successfully used to encrypt then decrypt data.\n */\n async checkKeyPairValidity(keyPair: KeyPair<CryptoKey>): Promise<boolean> {\n try {\n const text = 'shibboleth'\n const encryptedText = await this.encrypt(keyPair.publicKey, utf8_2ua(text))\n const decryptedText = ua2utf8(await this.decrypt(keyPair.privateKey, new Uint8Array(encryptedText)))\n return decryptedText === text\n } catch (e) {\n return false\n }\n }\n\n /**\n * Generates a signature for some data. The signature algorithm used is RSA-PSS with SHA-256.\n * @param privateKey private key to use for signature\n * @param data the data to sign\n * @return the signature.\n */\n async sign(privateKey: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer> {\n return await this.crypto.subtle.sign({ name: 'RSA-PSS', saltLength: 32 }, privateKey, data)\n }\n\n /**\n * Verifies if a signature matches the data. The signature algorithm used is RSA-PSS with sha-256.\n * @param publicKey public key to use for signature verification.\n * @param signature the signature to verify\n * @param data the data that was signed\n * @return if the signature matches the data and key.\n */\n async verifySignature(publicKey: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer): Promise<boolean> {\n return await this.crypto.subtle.verify({ name: 'RSA-PSS', saltLength: 32 }, publicKey, signature, data)\n }\n}\n\nexport const RSA = new RSAUtils()\n"]}
|
|
1
|
+
{"version":3,"file":"RSA.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/RSA.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oCAA4C;AAO5C,IAAY,UAGX;AAHD,WAAY,UAAU;IACpB,4BAAc,CAAA;IACd,gCAAkB,CAAA;AACpB,CAAC,EAHW,UAAU,GAAV,kBAAU,KAAV,kBAAU,QAGrB;AAkID,MAAa,YAAY;IA2BvB,YAAY,SAAiB,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,C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EAAE,SAAsB,EAAE,IAAiB;;YACnF,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,CAAA;QACzG,CAAC;KAAA;CACF;AAjPD,oCAiPC;AAEY,QAAA,GAAG,GAAa,IAAI,YAAY,EAAE,CAAA","sourcesContent":["import { ua2utf8, utf8_2ua } from '../utils'\n\n/**\n * Represents an RSA KeyPair in a generic format.\n */\nexport type KeyPair<T> = { publicKey: T; privateKey: T }\n\nexport enum ShaVersion {\n Sha1 = 'sha-1',\n Sha256 = 'sha-256',\n}\n\nexport interface RSAUtils {\n /**\n * Generates a key pair for encryption/decryption of data.\n * @param shaVersion the version of the SHA algorithm to use.\n */\n generateKeyPair(shaVersion: ShaVersion): Promise<KeyPair<CryptoKey>>\n\n /**\n * Generates a key pair for signing data and signature verification.\n */\n generateSignatureKeyPair(): Promise<KeyPair<CryptoKey>>\n\n /**\n *\n * 'JWK': Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n * 'spki': for private key\n * 'pkcs8': for private Key\n *\n * @param keyPair is {publicKey: CryptoKey, privateKey: CryptoKey}\n * @param privKeyFormat will be 'pkcs8' or 'jwk'\n * @param pubKeyFormat will be 'spki' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'jwk', pubKeyFormat: 'jwk'): Promise<KeyPair<JsonWebKey>>\n\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'pkcs8', pubKeyFormat: 'spki'): Promise<KeyPair<ArrayBuffer>>\n\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: string, pubKeyFormat: string): Promise<KeyPair<JsonWebKey | ArrayBuffer>>\n\n /**\n * Format:\n *\n * 'JWK': Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n * 'spki': for private key\n * 'pkcs8': for private Key\n *\n * @param cryptoKey public or private\n * @param format either 'jwk' or 'spki' or 'pkcs8'\n * @returns {Promise|*} will be RSA key (public or private)\n */\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n\n exportKey(cryptoKey: CryptoKey, format: 'spki'): Promise<ArrayBuffer>\n\n exportKey(cryptoKey: CryptoKey, format: 'pkcs8'): Promise<ArrayBuffer>\n\n exportKey(cryptoKey: CryptoKey, format: string): Promise<JsonWebKey | ArrayBuffer>\n\n /**\n *\n * @param publicKey (CryptoKey)\n * @param plainData (Uint8Array)\n */\n encrypt(publicKey: CryptoKey, plainData: Uint8Array): Promise<ArrayBuffer>\n\n /**\n *\n * @param privateKey (CryptoKey)\n * @param encryptedData (Uint8Array)\n */\n decrypt(privateKey: CryptoKey, encryptedData: Uint8Array): Promise<ArrayBuffer>\n\n /**\n *\n * @param format 'jwk', 'spki', or 'pkcs8'\n * @param keydata should be the key data based on the format.\n * @param keyUsages Array of usages. For example, ['encrypt'] for public key.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {*}\n */\n importKey(format: 'jwk' | 'spki' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer, keyUsages: KeyUsage[], hashAlgorithm: ShaVersion): Promise<CryptoKey>\n\n importSignatureKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey>\n\n importVerificationKey(format: 'jwk' | 'spki', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey>\n\n /**\n *\n * @param format 'jwk' or 'pkcs8'\n * @param keydata should be the key data based on the format.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {*}\n */\n importPrivateKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer, hashAlgorithm: ShaVersion): Promise<CryptoKey>\n\n /**\n *\n * @param privateKeyFormat 'jwk' or 'pkcs8'\n * @param privateKeydata should be the key data based on the format.\n * @param publicKeyFormat 'jwk' or 'spki'\n * @param publicKeyData should be the key data based on the format.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {Promise|*}\n */\n importKeyPair(\n privateKeyFormat: 'jwk' | 'pkcs8',\n privateKeydata: JsonWebKey | ArrayBuffer,\n publicKeyFormat: 'jwk' | 'spki',\n publicKeyData: JsonWebKey | ArrayBuffer,\n hashAlgorithm: ShaVersion\n ): Promise<KeyPair<CryptoKey>>\n\n /**\n * Tries to encrypt then decrypt data using a keypair. If both operations succeed without throwing an error and the decrypted data matches the\n * original data returns true, else false.\n * @param keyPair a key pair.\n * @return if the key pair could be successfully used to encrypt then decrypt data.\n */\n checkKeyPairValidity(keyPair: KeyPair<CryptoKey>): Promise<boolean>\n\n /**\n * Generates a signature for some data. The signature algorithm used is RSA-PSS with SHA-256.\n * @param privateKey private key to use for signature\n * @param data the data to sign\n * @return the signature.\n */\n sign(privateKey: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>\n\n /**\n * Verifies if a signature matches the data. The signature algorithm used is RSA-PSS with sha-256.\n * @param publicKey public key to use for signature verification.\n * @param signature the signature to verify\n * @param data the data that was signed\n * @return if the signature matches the data and key.\n */\n verifySignature(publicKey: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer): Promise<boolean>\n}\n\nexport class RSAUtilsImpl implements RSAUtils {\n /********* RSA Config **********/\n //TODO bigger modulus\n //TODO PSS for signing\n rsaParams: any = { name: 'RSA-OAEP' }\n // RSA params for 'import' and 'generate' function.\n rsaHashedParams: any = {\n name: 'RSA-OAEP',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'sha-1' },\n }\n rsaWithSha256HashedParams: any = {\n name: 'RSA-OAEP',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'SHA-256' },\n }\n private readonly signatureKeysGenerationParams = {\n name: 'RSA-PSS',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // Equivalent to 65537 (Fermat F4), read http://en.wikipedia.org/wiki/65537_(number)\n hash: { name: 'SHA-256' },\n }\n\n private crypto: Crypto\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this.crypto = crypto\n }\n\n /**\n * Generates a key pair for encryption/decryption of data.\n * @param shaVersion the version of the SHA algorithm to use.\n */\n generateKeyPair(shaVersion: ShaVersion): Promise<KeyPair<CryptoKey>> {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n const rsaParams = this.paramsForCreationOrImport(shaVersion)\n\n return new Promise<KeyPair<CryptoKey>>((resolve, reject) => {\n this.crypto.subtle.generateKey(rsaParams, extractable, keyUsages).then(resolve, reject)\n })\n }\n\n /**\n * Generates a key pair for signing data and signature verification.\n */\n async generateSignatureKeyPair(): Promise<KeyPair<CryptoKey>> {\n return await this.crypto.subtle.generateKey(this.signatureKeysGenerationParams, true, ['sign', 'verify'])\n }\n\n /**\n *\n * 'JWK': Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n * 'spki': for private key\n * 'pkcs8': for private Key\n *\n * @param keyPair is {publicKey: CryptoKey, privateKey: CryptoKey}\n * @param privKeyFormat will be 'pkcs8' or 'jwk'\n * @param pubKeyFormat will be 'spki' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'jwk', pubKeyFormat: 'jwk'): Promise<KeyPair<JsonWebKey>>\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: 'pkcs8', pubKeyFormat: 'spki'): Promise<KeyPair<ArrayBuffer>>\n exportKeys(keyPair: KeyPair<CryptoKey>, privKeyFormat: string, pubKeyFormat: string): Promise<KeyPair<JsonWebKey | ArrayBuffer>> {\n const pubPromise = this.crypto.subtle.exportKey(pubKeyFormat as any, keyPair.publicKey)\n const privPromise = this.crypto.subtle.exportKey(privKeyFormat as any, keyPair.privateKey)\n\n return Promise.all([pubPromise, privPromise]).then(function (results) {\n return {\n publicKey: results[0],\n privateKey: results[1],\n }\n })\n }\n\n /**\n * Format:\n *\n * 'JWK': Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n * 'spki': for private key\n * 'pkcs8': for private Key\n *\n * @param cryptoKey public or private\n * @param format either 'jwk' or 'spki' or 'pkcs8'\n * @returns {Promise|*} will be RSA key (public or private)\n */\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'spki'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'pkcs8'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: string): Promise<JsonWebKey | ArrayBuffer> {\n return new Promise((resolve: (value: JsonWebKey | ArrayBuffer) => any, reject) => {\n this.crypto.subtle.exportKey(format as any, cryptoKey).then(resolve, reject)\n })\n }\n\n /**\n *\n * @param publicKey (CryptoKey)\n * @param plainData (Uint8Array)\n */\n encrypt(publicKey: CryptoKey, plainData: Uint8Array): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject) => {\n this.crypto.subtle.encrypt(this.rsaParams, publicKey, plainData.buffer ? plainData.buffer : plainData).then(resolve, reject) //Node prefers arrayBuffer\n })\n }\n\n /**\n *\n * @param privateKey (CryptoKey)\n * @param encryptedData (Uint8Array)\n */\n decrypt(privateKey: CryptoKey, encryptedData: Uint8Array): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject) => {\n this.crypto.subtle.decrypt(this.rsaParams, privateKey, encryptedData).then(resolve, reject)\n })\n }\n\n /**\n *\n * @param format 'jwk', 'spki', or 'pkcs8'\n * @param keydata should be the key data based on the format.\n * @param keyUsages Array of usages. For example, ['encrypt'] for public key.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {*}\n */\n importKey(\n format: 'jwk' | 'spki' | 'pkcs8',\n keydata: JsonWebKey | ArrayBuffer,\n keyUsages: KeyUsage[],\n hashAlgorithm: ShaVersion\n ): Promise<CryptoKey> {\n const extractable = true\n return new Promise((resolve: (value: CryptoKey) => any, reject) => {\n const rsaParams = this.paramsForCreationOrImport(hashAlgorithm)\n this.crypto.subtle.importKey(format as any, keydata as any, rsaParams, extractable, keyUsages).then(resolve, reject)\n })\n }\n\n importSignatureKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey> {\n const extractable = true\n return this.crypto.subtle.importKey(format as any, keydata as any, this.signatureKeysGenerationParams, extractable, ['sign'])\n }\n\n importVerificationKey(format: 'jwk' | 'spki', keydata: JsonWebKey | ArrayBuffer): Promise<CryptoKey> {\n const extractable = true\n return this.crypto.subtle.importKey(format as any, keydata as any, this.signatureKeysGenerationParams, extractable, ['verify'])\n }\n\n paramsForCreationOrImport(shaVersion: ShaVersion) {\n if (shaVersion === 'sha-1') {\n return this.rsaHashedParams\n } else if (shaVersion === 'sha-256') {\n return this.rsaWithSha256HashedParams\n } else {\n throw new Error('Unexpected error, invalid SHA version')\n }\n }\n\n /**\n *\n * @param format 'jwk' or 'pkcs8'\n * @param keydata should be the key data based on the format.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {*}\n */\n importPrivateKey(format: 'jwk' | 'pkcs8', keydata: JsonWebKey | ArrayBuffer, hashAlgorithm: ShaVersion): Promise<CryptoKey> {\n const extractable = true\n return new Promise((resolve: (value: CryptoKey) => any, reject) => {\n const rsaParams = this.paramsForCreationOrImport(hashAlgorithm)\n this.crypto.subtle.importKey(format as any, keydata as any, rsaParams, extractable, ['decrypt']).then(resolve, reject)\n })\n }\n\n /**\n *\n * @param privateKeyFormat 'jwk' or 'pkcs8'\n * @param privateKeydata should be the key data based on the format.\n * @param publicKeyFormat 'jwk' or 'spki'\n * @param publicKeyData should be the key data based on the format.\n * @param hashAlgorithm 'sha-1' or 'sha-256'\n * @returns {Promise|*}\n */\n importKeyPair(\n privateKeyFormat: string,\n privateKeydata: JsonWebKey | ArrayBuffer,\n publicKeyFormat: string,\n publicKeyData: JsonWebKey | ArrayBuffer,\n hashAlgorithm: ShaVersion\n ): Promise<KeyPair<CryptoKey>> {\n const extractable = true\n const rsaParams = this.paramsForCreationOrImport(hashAlgorithm)\n const privPromise = this.crypto.subtle.importKey(privateKeyFormat as any, privateKeydata as any, rsaParams, extractable, ['decrypt'])\n const pubPromise = this.crypto.subtle.importKey(publicKeyFormat as any, publicKeyData as any, rsaParams, extractable, ['encrypt'])\n\n return Promise.all([pubPromise, privPromise]).then(function (results) {\n return {\n publicKey: results[0],\n privateKey: results[1],\n }\n })\n }\n\n /**\n * Tries to encrypt then decrypt data using a keypair. If both operations succeed without throwing an error and the decrypted data matches the\n * original data returns true, else false.\n * @param keyPair a key pair.\n * @return if the key pair could be successfully used to encrypt then decrypt data.\n */\n async checkKeyPairValidity(keyPair: KeyPair<CryptoKey>): Promise<boolean> {\n try {\n const text = 'shibboleth'\n const encryptedText = await this.encrypt(keyPair.publicKey, utf8_2ua(text))\n const decryptedText = ua2utf8(await this.decrypt(keyPair.privateKey, new Uint8Array(encryptedText)))\n return decryptedText === text\n } catch (e) {\n return false\n }\n }\n\n /**\n * Generates a signature for some data. The signature algorithm used is RSA-PSS with SHA-256.\n * @param privateKey private key to use for signature\n * @param data the data to sign\n * @return the signature.\n */\n async sign(privateKey: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer> {\n return await this.crypto.subtle.sign({ name: 'RSA-PSS', saltLength: 32 }, privateKey, data)\n }\n\n /**\n * Verifies if a signature matches the data. The signature algorithm used is RSA-PSS with sha-256.\n * @param publicKey public key to use for signature verification.\n * @param signature the signature to verify\n * @param data the data that was signed\n * @return if the signature matches the data and key.\n */\n async verifySignature(publicKey: CryptoKey, signature: ArrayBuffer, data: ArrayBuffer): Promise<boolean> {\n return await this.crypto.subtle.verify({ name: 'RSA-PSS', saltLength: 32 }, publicKey, signature, data)\n }\n}\n\nexport const RSA: RSAUtils = new RSAUtilsImpl()\n"]}
|
|
@@ -79,7 +79,12 @@ class TransferKeysManager {
|
|
|
79
79
|
// Result only includes the acyclic label, not the full group
|
|
80
80
|
transferKeysCandidatesFp(keyToFp, graph) {
|
|
81
81
|
return Object.entries((0, graph_utils_1.reachSetsAcyclic)(graph.acyclicGraph))
|
|
82
|
-
.filter(([from, reachable]) =>
|
|
82
|
+
.filter(([from, reachable]) => {
|
|
83
|
+
var _a;
|
|
84
|
+
const currGroup = (_a = graph.acyclicLabelToGroup[from]) !== null && _a !== void 0 ? _a : [from];
|
|
85
|
+
const reachableOriginal = new Set(Array.from(reachable).flatMap((x) => { var _a; return (_a = graph.acyclicLabelToGroup[x]) !== null && _a !== void 0 ? _a : [x]; }));
|
|
86
|
+
return !currGroup.includes(keyToFp) && !reachableOriginal.has(keyToFp);
|
|
87
|
+
})
|
|
83
88
|
.map((x) => x[0]);
|
|
84
89
|
}
|
|
85
90
|
transferTargetKeys(keyManager, graph) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TransferKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/TransferKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,+BAA2C;AAE3C,oCAAiC;AAEjC,sDAA+E;AAC/E,mCAAgJ;AAOhJ;;;GAGG;AACH,MAAa,mBAAmB;IAC9B,YACmB,UAA4B,EAC5B,uBAAgD,EAChD,YAA8B,EAC9B,qBAAgD,EAChD,wBAAkD,EAClD,YAAgC;QALhC,eAAU,GAAV,UAAU,CAAkB;QAC5B,4BAAuB,GAAvB,uBAAuB,CAAyB;QAChD,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,0BAAqB,GAArB,qBAAqB,CAA2B;QAChD,6BA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,CAAC,IAAI,IAAI,CAAC;oBAAE,SAAQ;gBAC7C,qIAAqI;gBACrI,MAAM,SAAS,GAAG,IAAA,8BAAgB,EAAC,KAAK,CAAC,YAAY,CAAC,CAAA;gBACtD,MAAM,mBAAmB,GAAG,uBAAuB,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CACvE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC,qBAAqB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CACrG,CAAA;gBACD,IAAI,mBAAmB,CAAC,MAAM,IAAI,CAAC;oBAAE,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAA;gBACxH,kJAAkJ;gBAClJ,OAAO;gBACP,MAAM,2BAA2B,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE;oBACxE,MAAM,GAAG,GAAG,KAAK,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAA;oBAC9G,IAAI,CAAC,GAAG;wBAAE,MAAM,IAAI,KAAK,CAAC,kFAAkF,CAAC,CAAA;oBAC7G,OAAO,GAAG,CAAA;gBACZ,CAAC,CAAC,CAAA;gBACF,GAAG,CAAC,IAAI,CAAC;oBACP,OAAO,EAAE,2BAA2B;oBACpC,MAAM,EAAE,SAAS;oBACjB,QAAQ,EAAE,WAAW;iBACtB,CAAC,CAAA;aACH;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;KAAA;CACF;AA5ID,kDA4IC","sourcesContent":["import { KeyPair, ShaVersion } from './RSA'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ua2hex } from '../utils'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { reachSetsAcyclic, StronglyConnectedGraph } from '../utils/graph-utils'\nimport { fingerprintToPublicKeysMapOf, fingerprintV1, loadPublicKeys, transferKeysFpGraphOf, fingerprintIsV1, fingerprintV1toV2 } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { BaseExchangeDataManager } from './BaseExchangeDataManager'\nimport { UserSignatureKeysManager } from './UserSignatureKeysManager'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is intended only for internal use and may be changed without notice.\n * Allows to create new transfer keys.\n */\nexport class TransferKeysManager {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly baseExchangeDataManager: BaseExchangeDataManager,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly encryptionKeysManager: UserEncryptionKeysManager,\n private readonly userSignatureKeysManager: UserSignatureKeysManager,\n private readonly icureStorage: IcureStorageFacade\n ) {}\n\n /**\n * Analyses the transfer keys graph and creates new transfer keys which allow to improve data accessibility from other devices.\n * For security reasons transfer keys will only be created between keys verified by the user, but this will be done ignoring any existing edges from\n * unverified keys to verified keys.\n * @param self the current data owner.\n * @return the updated data owner.\n */\n async updateTransferKeys(self: CryptoActorStubWithType): Promise<void> {\n const newEdgesByTarget = await this.getNewVerifiedTransferKeysEdges(self)\n if (!newEdgesByTarget.length) return\n const selfId = self.stub.id!\n const fpToPublicKey = fingerprintToPublicKeysMapOf(self.stub, ShaVersion.Sha1)\n const fpToPublicKeyWithSha256 = fingerprintToPublicKeysMapOf(self.stub, ShaVersion.Sha256)\n const signatureKeyPair = await this.userSignatureKeysManager.getOrCreateSignatureKeyPair()\n const verifiedFps = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n const allVerifiedSourcesAndTarget = Array.from(\n new Set(\n newEdgesByTarget.flatMap((x) =>\n // Sources are guaranteed to be verified, but target may not be\n verifiedFps.has(x.targetFp) ? [x.targetFp, ...x.sources] : x.sources\n )\n )\n )\n const newExchangeKeyPublicKeys = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKey[fp]).filter((key) => !!key)\n const newExchangeKeyPublicKeysWithSha256 = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKeyWithSha256[fp]).filter((key) => !!key)\n const createdExchangeData = await this.baseExchangeDataManager.createExchangeData(\n selfId,\n { [signatureKeyPair.fingerprint]: signatureKeyPair.keyPair.privateKey },\n {\n ...(await loadPublicKeys(this.primitives.RSA, newExchangeKeyPublicKeys, ShaVersion.Sha1)),\n ...(await loadPublicKeys(this.primitives.RSA, newExchangeKeyPublicKeysWithSha256, ShaVersion.Sha256)),\n }\n )\n let updatedTransferKeys = self.stub.transferKeys ?? {}\n for (const newEdges of newEdgesByTarget) {\n const encryptedTransferKey = await this.encryptTransferKey(newEdges.target, createdExchangeData.exchangeKey)\n updatedTransferKeys = newEdges.sources.reduce((acc, candidateFp) => {\n const existingKeys = { ...(acc[candidateFp] ?? {}) }\n existingKeys[newEdges.targetFp] = encryptedTransferKey\n acc[candidateFp] = existingKeys\n return acc\n }, updatedTransferKeys)\n }\n await this.dataOwnerApi.modifyCryptoActorStub({\n stub: {\n ...self.stub,\n transferKeys: updatedTransferKeys,\n },\n type: self.type,\n })\n }\n\n // encrypts a transfer key in pkcs8 format using an exchange key, returns the hex representation\n private async encryptTransferKey(transferKey: KeyPair<CryptoKey>, exchangeKey: CryptoKey): Promise<string> {\n const exportedKey = await this.primitives.RSA.exportKey(transferKey.privateKey, 'pkcs8')\n return ua2hex(await this.primitives.AES.encrypt(exchangeKey, exportedKey))\n }\n\n // all public keys would go to the stored keys -> no need for specifying the key.\n // Result only includes the acyclic label, not the full group\n private transferKeysCandidatesFp(keyToFp: string, graph: StronglyConnectedGraph): string[] {\n return Object.entries(reachSetsAcyclic(graph.acyclicGraph))\n .filter(([from, reachable]) => from != keyToFp && !reachable.has(keyToFp))\n .map((x) => x[0])\n }\n\n private async transferTargetKeys(\n keyManager: UserEncryptionKeysManager,\n graph: StronglyConnectedGraph\n ): Promise<{ fingerprint: string; pair: KeyPair<CryptoKey> }[]> {\n const availableGroups = new Set(Object.keys(keyManager.getDecryptionKeys()).map((x) => graph.originalLabelToAcyclicLabel[x] ?? x))\n const groupsReachableFromAvailable = new Set(\n Object.entries(graph.acyclicGraph).flatMap(([source, reachables]) => (availableGroups.has(source) ? Array.from(reachables) : []))\n )\n const targetCandidates = Array.from(availableGroups).filter((x) => !groupsReachableFromAvailable.has(x))\n const verifiedFps = new Set(keyManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n return targetCandidates.map((candidateFp) => {\n const candidateGroup = graph.acyclicLabelToGroup[candidateFp] ?? [candidateFp] // May not be part of transfer keys graph yet\n const bestCandidateOfGroup = candidateGroup.find((x) => verifiedFps.has(x)) ?? candidateFp\n return { fingerprint: bestCandidateOfGroup, pair: keyManager.getKeyPairForFingerprint(bestCandidateOfGroup)!.pair }\n })\n }\n\n // Decides the best edges considering the verified public keys.\n private async getNewVerifiedTransferKeysEdges(self: CryptoActorStubWithType): Promise<\n {\n sources: string[]\n target: KeyPair<CryptoKey>\n targetFp: string\n }[]\n > {\n const verifiedKeysFpSet = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(self.stub.id!)).forEach(([key, verified]) => {\n if (verified) verifiedKeysFpSet.add(fingerprintV1(key))\n })\n if (verifiedKeysFpSet.size == 0) return []\n const graph = transferKeysFpGraphOf(self.stub)\n // 1. Choose keys available in this device which should be reachable from all other verified keys\n const targetKeys = await this.transferTargetKeys(this.encryptionKeysManager, graph)\n const res = []\n for (const { fingerprint: targetKeyFp, pair: targetKey } of targetKeys) {\n // 2. Find groups which can't reach the existing target keys\n const candidatesFp = this.transferKeysCandidatesFp(targetKeyFp, graph)\n // 3. Keep only groups which contain at least a verified candidate\n const verifiedGroupCandidates = candidatesFp.filter((candidate) =>\n graph.acyclicLabelToGroup[candidate].some((candidateGroupMember) => verifiedKeysFpSet.has(candidateGroupMember))\n )\n const verifiedCandidatesSet = new Set(verifiedGroupCandidates)\n if (verifiedCandidatesSet.size == 0) continue\n // 4. Drop all candidates which can already reach another candidate group: it is sufficient to create a transfer key from that group.\n const reachSets = reachSetsAcyclic(graph.acyclicGraph)\n const optimizedCandidates = verifiedGroupCandidates.filter((candidate) =>\n Array.from(reachSets[candidate]).every((reachableNode) => !verifiedCandidatesSet.has(reachableNode))\n )\n if (optimizedCandidates.length == 0) throw new Error('Check failed: at least one candidate should survive optimization')\n // 5. Transfer keys could also be faked: to make sure we are not giving access to unauthorised people we remap the candidates to a verified public\n // keys\n const verifiedOptimizedCandidates = optimizedCandidates.map((candidate) => {\n const res = graph.acyclicLabelToGroup[candidate].find((groupMemberFp) => verifiedKeysFpSet.has(groupMemberFp))\n if (!res) throw new Error('Check failed: optimized candidates groups should have at least a verified member')\n return res\n })\n res.push({\n sources: verifiedOptimizedCandidates,\n target: targetKey,\n targetFp: targetKeyFp,\n })\n }\n return res\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"TransferKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/TransferKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,+BAA2C;AAE3C,oCAAiC;AAEjC,sDAA+E;AAC/E,mCAAgJ;AAOhJ;;;GAGG;AACH,MAAa,mBAAmB;IAC9B,YACmB,UAA4B,EAC5B,uBAAgD,EAChD,YAA8B,EAC9B,qBAAgD,EAChD,wBAAkD,EAClD,YAAgC;QALhC,eAAU,GAAV,UAAU,CAAkB;QAC5B,4BAAuB,GAAvB,uBAAuB,CAAyB;QAChD,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,0BAAqB,GAArB,qBAAqB,CAA2B;QAChD,6BAAwB,GAAxB,wBAAwB,CAA0B;QAClD,iBAAY,GAAZ,YAAY,CAAoB;IAChD,CAAC;IAEJ;;;;;;OAMG;IACG,kBAAkB,CAAC,IAA6B;;;YACpD,MAAM,gBAA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WAAW;iBACtB,CAAC,CAAA;aACH;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;KAAA;CACF;AAhJD,kDAgJC","sourcesContent":["import { KeyPair, ShaVersion } from './RSA'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ua2hex } from '../utils'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { reachSetsAcyclic, StronglyConnectedGraph } from '../utils/graph-utils'\nimport { fingerprintToPublicKeysMapOf, fingerprintV1, loadPublicKeys, transferKeysFpGraphOf, fingerprintIsV1, fingerprintV1toV2 } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { BaseExchangeDataManager } from './BaseExchangeDataManager'\nimport { UserSignatureKeysManager } from './UserSignatureKeysManager'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is intended only for internal use and may be changed without notice.\n * Allows to create new transfer keys.\n */\nexport class TransferKeysManager {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly baseExchangeDataManager: BaseExchangeDataManager,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly encryptionKeysManager: UserEncryptionKeysManager,\n private readonly userSignatureKeysManager: UserSignatureKeysManager,\n private readonly icureStorage: IcureStorageFacade\n ) {}\n\n /**\n * Analyses the transfer keys graph and creates new transfer keys which allow to improve data accessibility from other devices.\n * For security reasons transfer keys will only be created between keys verified by the user, but this will be done ignoring any existing edges from\n * unverified keys to verified keys.\n * @param self the current data owner.\n * @return the updated data owner.\n */\n async updateTransferKeys(self: CryptoActorStubWithType): Promise<void> {\n const newEdgesByTarget = await this.getNewVerifiedTransferKeysEdges(self)\n if (!newEdgesByTarget.length) return\n const selfId = self.stub.id!\n const fpToPublicKey = fingerprintToPublicKeysMapOf(self.stub, ShaVersion.Sha1)\n const fpToPublicKeyWithSha256 = fingerprintToPublicKeysMapOf(self.stub, ShaVersion.Sha256)\n const signatureKeyPair = await this.userSignatureKeysManager.getOrCreateSignatureKeyPair()\n const verifiedFps = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n const allVerifiedSourcesAndTarget = Array.from(\n new Set(\n newEdgesByTarget.flatMap((x) =>\n // Sources are guaranteed to be verified, but target may not be\n verifiedFps.has(x.targetFp) ? [x.targetFp, ...x.sources] : x.sources\n )\n )\n )\n const newExchangeKeyPublicKeys = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKey[fp]).filter((key) => !!key)\n const newExchangeKeyPublicKeysWithSha256 = allVerifiedSourcesAndTarget.map((fp) => fpToPublicKeyWithSha256[fp]).filter((key) => !!key)\n const createdExchangeData = await this.baseExchangeDataManager.createExchangeData(\n selfId,\n { [signatureKeyPair.fingerprint]: signatureKeyPair.keyPair.privateKey },\n {\n ...(await loadPublicKeys(this.primitives.RSA, newExchangeKeyPublicKeys, ShaVersion.Sha1)),\n ...(await loadPublicKeys(this.primitives.RSA, newExchangeKeyPublicKeysWithSha256, ShaVersion.Sha256)),\n }\n )\n let updatedTransferKeys = self.stub.transferKeys ?? {}\n for (const newEdges of newEdgesByTarget) {\n const encryptedTransferKey = await this.encryptTransferKey(newEdges.target, createdExchangeData.exchangeKey)\n updatedTransferKeys = newEdges.sources.reduce((acc, candidateFp) => {\n const existingKeys = { ...(acc[candidateFp] ?? {}) }\n existingKeys[newEdges.targetFp] = encryptedTransferKey\n acc[candidateFp] = existingKeys\n return acc\n }, updatedTransferKeys)\n }\n await this.dataOwnerApi.modifyCryptoActorStub({\n stub: {\n ...self.stub,\n transferKeys: updatedTransferKeys,\n },\n type: self.type,\n })\n }\n\n // encrypts a transfer key in pkcs8 format using an exchange key, returns the hex representation\n private async encryptTransferKey(transferKey: KeyPair<CryptoKey>, exchangeKey: CryptoKey): Promise<string> {\n const exportedKey = await this.primitives.RSA.exportKey(transferKey.privateKey, 'pkcs8')\n return ua2hex(await this.primitives.AES.encrypt(exchangeKey, exportedKey))\n }\n\n // all public keys would go to the stored keys -> no need for specifying the key.\n // Result only includes the acyclic label, not the full group\n private transferKeysCandidatesFp(keyToFp: string, graph: StronglyConnectedGraph): string[] {\n return Object.entries(reachSetsAcyclic(graph.acyclicGraph))\n .filter(([from, reachable]) => {\n const currGroup = graph.acyclicLabelToGroup[from] ?? [from]\n const reachableOriginal = new Set(Array.from(reachable).flatMap((x) => graph.acyclicLabelToGroup[x] ?? [x]))\n return !currGroup.includes(keyToFp) && !reachableOriginal.has(keyToFp)\n })\n .map((x) => x[0])\n }\n\n private async transferTargetKeys(\n keyManager: UserEncryptionKeysManager,\n graph: StronglyConnectedGraph\n ): Promise<{ fingerprint: string; pair: KeyPair<CryptoKey> }[]> {\n const availableGroups = new Set(Object.keys(keyManager.getDecryptionKeys()).map((x) => graph.originalLabelToAcyclicLabel[x] ?? x))\n const groupsReachableFromAvailable = new Set(\n Object.entries(graph.acyclicGraph).flatMap(([source, reachables]) => (availableGroups.has(source) ? Array.from(reachables) : []))\n )\n const targetCandidates = Array.from(availableGroups).filter((x) => !groupsReachableFromAvailable.has(x))\n const verifiedFps = new Set(keyManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n return targetCandidates.map((candidateFp) => {\n const candidateGroup = graph.acyclicLabelToGroup[candidateFp] ?? [candidateFp] // May not be part of transfer keys graph yet\n const bestCandidateOfGroup = candidateGroup.find((x) => verifiedFps.has(x)) ?? candidateFp\n return { fingerprint: bestCandidateOfGroup, pair: keyManager.getKeyPairForFingerprint(bestCandidateOfGroup)!.pair }\n })\n }\n\n // Decides the best edges considering the verified public keys.\n private async getNewVerifiedTransferKeysEdges(self: CryptoActorStubWithType): Promise<\n {\n sources: string[]\n target: KeyPair<CryptoKey>\n targetFp: string\n }[]\n > {\n const verifiedKeysFpSet = new Set(this.encryptionKeysManager.getSelfVerifiedKeys().map((x) => x.fingerprint))\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(self.stub.id!)).forEach(([key, verified]) => {\n if (verified) verifiedKeysFpSet.add(fingerprintV1(key))\n })\n if (verifiedKeysFpSet.size == 0) return []\n const graph = transferKeysFpGraphOf(self.stub)\n // 1. Choose keys available in this device which should be reachable from all other verified keys\n const targetKeys = await this.transferTargetKeys(this.encryptionKeysManager, graph)\n const res = []\n for (const { fingerprint: targetKeyFp, pair: targetKey } of targetKeys) {\n // 2. Find groups which can't reach the existing target keys\n const candidatesFp = this.transferKeysCandidatesFp(targetKeyFp, graph)\n // 3. Keep only groups which contain at least a verified candidate\n const verifiedGroupCandidates = candidatesFp.filter((candidate) =>\n graph.acyclicLabelToGroup[candidate].some((candidateGroupMember) => verifiedKeysFpSet.has(candidateGroupMember))\n )\n const verifiedCandidatesSet = new Set(verifiedGroupCandidates)\n if (verifiedCandidatesSet.size == 0) continue\n // 4. Drop all candidates which can already reach another candidate group: it is sufficient to create a transfer key from that group.\n const reachSets = reachSetsAcyclic(graph.acyclicGraph)\n const optimizedCandidates = verifiedGroupCandidates.filter((candidate) =>\n Array.from(reachSets[candidate]).every((reachableNode) => !verifiedCandidatesSet.has(reachableNode))\n )\n if (optimizedCandidates.length == 0) throw new Error('Check failed: at least one candidate should survive optimization')\n // 5. Transfer keys could also be faked: to make sure we are not giving access to unauthorised people we remap the candidates to a verified public\n // keys\n const verifiedOptimizedCandidates = optimizedCandidates.map((candidate) => {\n const res = graph.acyclicLabelToGroup[candidate].find((groupMemberFp) => verifiedKeysFpSet.has(groupMemberFp))\n if (!res) throw new Error('Check failed: optimized candidates groups should have at least a verified member')\n return res\n })\n res.push({\n sources: verifiedOptimizedCandidates,\n target: targetKey,\n targetFp: targetKeyFp,\n })\n }\n return res\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export declare class ShamirClass {
|
|
1
|
+
export declare abstract class ShamirClass {
|
|
2
2
|
config: {
|
|
3
3
|
bits: number;
|
|
4
4
|
radix: number;
|
|
@@ -13,8 +13,7 @@ export declare class ShamirClass {
|
|
|
13
13
|
logs: number[];
|
|
14
14
|
exps: number[];
|
|
15
15
|
};
|
|
16
|
-
|
|
17
|
-
constructor(crypto?: Crypto);
|
|
16
|
+
protected abstract fillRandom(arr: Uint32Array): void;
|
|
18
17
|
init(): void;
|
|
19
18
|
split(str: string, padLength?: number): number[];
|
|
20
19
|
bin2hex(str: string): string;
|
|
@@ -37,4 +36,9 @@ export declare class ShamirClass {
|
|
|
37
36
|
newShare(id: number | string, shares: Array<string>): string;
|
|
38
37
|
lagrange(at: number, x: Array<number>, y: Array<number>): number;
|
|
39
38
|
}
|
|
39
|
+
export declare class WebcryptoShamir extends ShamirClass {
|
|
40
|
+
private crypto;
|
|
41
|
+
constructor(crypto?: Crypto);
|
|
42
|
+
protected fillRandom(arr: Uint32Array): void;
|
|
43
|
+
}
|
|
40
44
|
export declare const shamir: ShamirClass;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.shamir = exports.ShamirClass = void 0;
|
|
3
|
+
exports.shamir = exports.WebcryptoShamir = exports.ShamirClass = void 0;
|
|
4
4
|
class ShamirClass {
|
|
5
|
-
constructor(
|
|
5
|
+
constructor() {
|
|
6
6
|
// Protected settings object
|
|
7
7
|
this.config = {
|
|
8
8
|
bits: 8,
|
|
@@ -22,7 +22,6 @@ class ShamirClass {
|
|
|
22
22
|
logs: [],
|
|
23
23
|
exps: [],
|
|
24
24
|
};
|
|
25
|
-
this.crypto = crypto;
|
|
26
25
|
}
|
|
27
26
|
init() {
|
|
28
27
|
const primitive = this.config.primitivePolynomials[this.config.bits];
|
|
@@ -93,7 +92,7 @@ class ShamirClass {
|
|
|
93
92
|
};
|
|
94
93
|
let elems = Math.ceil(bits / 32), str = null, arr = new Uint32Array(elems);
|
|
95
94
|
while (str === null) {
|
|
96
|
-
this.
|
|
95
|
+
this.fillRandom(arr);
|
|
97
96
|
str = construct(bits, arr, 8);
|
|
98
97
|
}
|
|
99
98
|
return str;
|
|
@@ -276,5 +275,15 @@ class ShamirClass {
|
|
|
276
275
|
}
|
|
277
276
|
}
|
|
278
277
|
exports.ShamirClass = ShamirClass;
|
|
279
|
-
|
|
278
|
+
class WebcryptoShamir extends ShamirClass {
|
|
279
|
+
constructor(crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : {}) {
|
|
280
|
+
super();
|
|
281
|
+
this.crypto = crypto;
|
|
282
|
+
}
|
|
283
|
+
fillRandom(arr) {
|
|
284
|
+
this.crypto.getRandomValues(arr);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
exports.WebcryptoShamir = WebcryptoShamir;
|
|
288
|
+
exports.shamir = new WebcryptoShamir();
|
|
280
289
|
//# sourceMappingURL=shamir.js.map
|