@nmshd/crypto 2.1.1 → 2.2.0-alpha.1

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.
Files changed (66) hide show
  1. package/dist/CoreBuffer.js +1 -2
  2. package/dist/CoreBuffer.js.map +1 -1
  3. package/dist/CryptoDerivation.js +6 -0
  4. package/dist/CryptoDerivation.js.map +1 -1
  5. package/dist/CryptoErrorCode.d.ts +12 -1
  6. package/dist/CryptoErrorCode.js +11 -0
  7. package/dist/CryptoErrorCode.js.map +1 -1
  8. package/dist/CryptoSerializable.d.ts +5 -1
  9. package/dist/CryptoSerializable.js +10 -1
  10. package/dist/CryptoSerializable.js.map +1 -1
  11. package/dist/CryptoValidation.js +20 -0
  12. package/dist/CryptoValidation.js.map +1 -1
  13. package/dist/SodiumWrapper.js +17 -7
  14. package/dist/SodiumWrapper.js.map +1 -1
  15. package/dist/buildInformation.js +5 -5
  16. package/dist/crypto-layer/CryptoDerivationHandle.d.ts +40 -0
  17. package/dist/crypto-layer/CryptoDerivationHandle.js +75 -0
  18. package/dist/crypto-layer/CryptoDerivationHandle.js.map +1 -0
  19. package/dist/crypto-layer/CryptoLayerConfig.d.ts +18 -0
  20. package/dist/crypto-layer/CryptoLayerConfig.js +3 -0
  21. package/dist/crypto-layer/CryptoLayerConfig.js.map +1 -0
  22. package/dist/crypto-layer/CryptoLayerProviders.d.ts +18 -0
  23. package/dist/crypto-layer/CryptoLayerProviders.js +105 -0
  24. package/dist/crypto-layer/CryptoLayerProviders.js.map +1 -0
  25. package/dist/crypto-layer/CryptoLayerUtils.d.ts +14 -0
  26. package/dist/crypto-layer/CryptoLayerUtils.js +106 -0
  27. package/dist/crypto-layer/CryptoLayerUtils.js.map +1 -0
  28. package/dist/crypto-layer/encryption/BaseKeyHandle.d.ts +59 -0
  29. package/dist/crypto-layer/encryption/BaseKeyHandle.js +119 -0
  30. package/dist/crypto-layer/encryption/BaseKeyHandle.js.map +1 -0
  31. package/dist/crypto-layer/encryption/CryptoEncryptionHandle.d.ts +27 -0
  32. package/dist/crypto-layer/encryption/CryptoEncryptionHandle.js +181 -0
  33. package/dist/crypto-layer/encryption/CryptoEncryptionHandle.js.map +1 -0
  34. package/dist/crypto-layer/encryption/DeviceBoundDerivedKeyHandle.d.ts +7 -0
  35. package/dist/crypto-layer/encryption/DeviceBoundDerivedKeyHandle.js +36 -0
  36. package/dist/crypto-layer/encryption/DeviceBoundDerivedKeyHandle.js.map +1 -0
  37. package/dist/crypto-layer/encryption/DeviceBoundKeyHandle.d.ts +7 -0
  38. package/dist/crypto-layer/encryption/DeviceBoundKeyHandle.js +36 -0
  39. package/dist/crypto-layer/encryption/DeviceBoundKeyHandle.js.map +1 -0
  40. package/dist/crypto-layer/encryption/PortableDerivedKeyHandle.d.ts +6 -0
  41. package/dist/crypto-layer/encryption/PortableDerivedKeyHandle.js +35 -0
  42. package/dist/crypto-layer/encryption/PortableDerivedKeyHandle.js.map +1 -0
  43. package/dist/crypto-layer/encryption/PortableKeyHandle.d.ts +7 -0
  44. package/dist/crypto-layer/encryption/PortableKeyHandle.js +36 -0
  45. package/dist/crypto-layer/encryption/PortableKeyHandle.js.map +1 -0
  46. package/dist/crypto-layer/index.d.ts +10 -0
  47. package/dist/crypto-layer/index.js +27 -0
  48. package/dist/crypto-layer/index.js.map +1 -0
  49. package/dist/encryption/CryptoEncryption.d.ts +4 -1
  50. package/dist/encryption/CryptoEncryption.js +23 -0
  51. package/dist/encryption/CryptoEncryption.js.map +1 -1
  52. package/dist/exchange/CryptoExchangePrivateKey.js +2 -0
  53. package/dist/exchange/CryptoExchangePrivateKey.js.map +1 -1
  54. package/dist/hash/CryptoHash.js +1 -0
  55. package/dist/hash/CryptoHash.js.map +1 -1
  56. package/dist/index.d.ts +1 -0
  57. package/dist/index.js +1 -0
  58. package/dist/index.js.map +1 -1
  59. package/dist/signature/CryptoSignatures.js +4 -0
  60. package/dist/signature/CryptoSignatures.js.map +1 -1
  61. package/package.json +23 -32
  62. package/lib-web/nmshd.crypto.js +0 -5787
  63. package/lib-web/nmshd.crypto.js.map +0 -1
  64. package/lib-web/nmshd.crypto.min.js +0 -2
  65. package/lib-web/nmshd.crypto.min.js.map +0 -1
  66. package/ui5.yaml +0 -9
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.initCryptoLayerProviders = initCryptoLayerProviders;
4
+ exports.getProvider = getProvider;
5
+ exports.hasProviderForSecurityLevel = hasProviderForSecurityLevel;
6
+ const CryptoError_1 = require("../CryptoError");
7
+ const CryptoErrorCode_1 = require("../CryptoErrorCode");
8
+ let PROVIDERS_BY_SECURITY = undefined;
9
+ let PROVIDERS_BY_NAME = undefined;
10
+ const DEFAULT_PROVIDER_CONFIG = {
11
+ max_security_level: "Hardware",
12
+ min_security_level: "Software",
13
+ supported_asym_spec: ["P256", "Curve25519"],
14
+ supported_ciphers: ["AesCbc256", "AesGcm256"],
15
+ supported_hashes: ["Sha2_256", "Sha2_512"]
16
+ };
17
+ async function providerBySecurityMapFromProviderByNameMap(providersByName) {
18
+ const providersBySecurity = new Map();
19
+ for (const [providerName, provider] of providersByName) {
20
+ const capabilities = await provider.getCapabilities();
21
+ if (!capabilities) {
22
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.CalLoadingProvider, `Failed fetching capabilities or security levels of provider ${providerName}`).setContext(providerBySecurityMapFromProviderByNameMap);
23
+ }
24
+ if (capabilities.max_security_level !== capabilities.min_security_level) {
25
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.CalLoadingProvider, `Minimum and maximum security levels of provider ${providerName} must be the same.`).setContext(providerBySecurityMapFromProviderByNameMap);
26
+ }
27
+ const securityLevel = capabilities.min_security_level;
28
+ if (!providersBySecurity.has(securityLevel)) {
29
+ providersBySecurity.set(securityLevel, []);
30
+ }
31
+ providersBySecurity.get(securityLevel).push(provider);
32
+ }
33
+ return providersBySecurity;
34
+ }
35
+ /**
36
+ * Creates a provider if possible with the given provider filter. This means, that the provider created must adhere to the filter.
37
+ *
38
+ * If a `SecurityLevel` is given, the default provider config {@link DEFAULT_PROVIDER_CONFIG} will be used to fill in the rest for the selection.
39
+ */
40
+ async function createProviderFromProviderFilter(providerToBeInitialized, factoryFunctions, providerImplConfig) {
41
+ if ("providerName" in providerToBeInitialized) {
42
+ return await factoryFunctions.createProviderFromName(providerToBeInitialized.providerName, providerImplConfig);
43
+ }
44
+ if ("securityLevel" in providerToBeInitialized) {
45
+ const providerConfig = Object.assign(Object.assign({}, DEFAULT_PROVIDER_CONFIG), { max_security_level: providerToBeInitialized.securityLevel, min_security_level: providerToBeInitialized.securityLevel });
46
+ return await factoryFunctions.createProvider(providerConfig, providerImplConfig);
47
+ }
48
+ if ("providerConfig" in providerToBeInitialized) {
49
+ return await factoryFunctions.createProvider(providerToBeInitialized.providerConfig, providerImplConfig);
50
+ }
51
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.WrongParameters, `No available provider matches the given requirements: ${JSON.stringify(providerToBeInitialized)}`).setContext(createProviderFromProviderFilter);
52
+ }
53
+ /**
54
+ * Initializes a list of global providers with the given configuration.
55
+ */
56
+ async function initCryptoLayerProviders(config) {
57
+ if (PROVIDERS_BY_NAME !== undefined && PROVIDERS_BY_SECURITY !== undefined) {
58
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.CalProvidersAlreadyInitialized, "Providers cannot be initialized again.").setContext(initCryptoLayerProviders);
59
+ }
60
+ const providers = new Map();
61
+ for (const [providerToBeInitialized, providerImplConfig] of config.providersToBeInitialized) {
62
+ const provider = await createProviderFromProviderFilter(providerToBeInitialized, config.factoryFunctions, providerImplConfig);
63
+ if (provider === undefined) {
64
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.CalLoadingProvider, `Failed loading provider with given requirements: ${JSON.stringify(providerToBeInitialized)}`).setContext(initCryptoLayerProviders);
65
+ }
66
+ providers.set(await provider.providerName(), provider);
67
+ }
68
+ PROVIDERS_BY_NAME = providers;
69
+ PROVIDERS_BY_SECURITY = await providerBySecurityMapFromProviderByNameMap(PROVIDERS_BY_NAME);
70
+ }
71
+ /**
72
+ * Returns an initialized provider with the given name or security level if possible,
73
+ * otherwise throws {@link CryptoError} with {@link CryptoErrorCode.CalThisProviderNotInitialized}.
74
+ *
75
+ * Providers need to be initialized via the {@link initCryptoLayerProviders} function,
76
+ * else throws {@link CryptoError} with {@link CryptoErrorCode.CalProvidersNotInitialized}.
77
+ */
78
+ function getProvider(identifier) {
79
+ var _a;
80
+ if (PROVIDERS_BY_NAME === undefined || PROVIDERS_BY_SECURITY === undefined) {
81
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.CalProvidersNotInitialized, "Failed to get providers as providers are not initialized.").setContext(getProvider);
82
+ }
83
+ let provider;
84
+ if ("providerName" in identifier) {
85
+ provider = PROVIDERS_BY_NAME.get(identifier.providerName);
86
+ }
87
+ else if ("securityLevel" in identifier) {
88
+ provider = (_a = PROVIDERS_BY_SECURITY.get(identifier.securityLevel)) === null || _a === void 0 ? void 0 : _a[0];
89
+ }
90
+ else {
91
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.WrongParameters, "Provider identifier was not able to be parsed while trying to get a provider.").setContext(getProvider);
92
+ }
93
+ if (provider === undefined) {
94
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.CalThisProviderNotInitialized, `Failed finding provider with name or security level ${identifier}`).setContext(getProvider);
95
+ }
96
+ return provider;
97
+ }
98
+ function hasProviderForSecurityLevel(securityLevel) {
99
+ if (PROVIDERS_BY_SECURITY === undefined) {
100
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.CalProvidersNotInitialized, "Failed to get providers as providers are not initialized.").setContext(hasProviderForSecurityLevel);
101
+ }
102
+ const providers = PROVIDERS_BY_SECURITY.get(securityLevel);
103
+ return providers !== undefined && providers.length > 0;
104
+ }
105
+ //# sourceMappingURL=CryptoLayerProviders.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CryptoLayerProviders.js","sourceRoot":"","sources":["../../src/crypto-layer/CryptoLayerProviders.ts"],"names":[],"mappings":";;AAuFA,4DA6BC;AAWD,kCA4BC;AAED,kEAUC;AA9JD,gDAA6C;AAC7C,wDAAqD;AAGrD,IAAI,qBAAqB,GAA+C,SAAS,CAAC;AAClF,IAAI,iBAAiB,GAAsC,SAAS,CAAC;AAErE,MAAM,uBAAuB,GAAmB;IAC5C,kBAAkB,EAAE,UAAU;IAC9B,kBAAkB,EAAE,UAAU;IAC9B,mBAAmB,EAAE,CAAC,MAAM,EAAE,YAAY,CAAC;IAC3C,iBAAiB,EAAE,CAAC,WAAW,EAAE,WAAW,CAAC;IAC7C,gBAAgB,EAAE,CAAC,UAAU,EAAE,UAAU,CAAC;CAC7C,CAAC;AAEF,KAAK,UAAU,0CAA0C,CACrD,eAAsC;IAEtC,MAAM,mBAAmB,GAAG,IAAI,GAAG,EAA6B,CAAC;IACjE,KAAK,MAAM,CAAC,YAAY,EAAE,QAAQ,CAAC,IAAI,eAAe,EAAE,CAAC;QACrD,MAAM,YAAY,GAAG,MAAM,QAAQ,CAAC,eAAe,EAAE,CAAC;QACtD,IAAI,CAAC,YAAY,EAAE,CAAC;YAChB,MAAM,IAAI,yBAAW,CACjB,iCAAe,CAAC,kBAAkB,EAClC,+DAA+D,YAAY,EAAE,CAChF,CAAC,UAAU,CAAC,0CAA0C,CAAC,CAAC;QAC7D,CAAC;QACD,IAAI,YAAY,CAAC,kBAAkB,KAAK,YAAY,CAAC,kBAAkB,EAAE,CAAC;YACtE,MAAM,IAAI,yBAAW,CACjB,iCAAe,CAAC,kBAAkB,EAClC,mDAAmD,YAAY,oBAAoB,CACtF,CAAC,UAAU,CAAC,0CAA0C,CAAC,CAAC;QAC7D,CAAC;QACD,MAAM,aAAa,GAAG,YAAY,CAAC,k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,CAAC;QACvC,QAAQ,GAAG,MAAA,qBAAqB,CAAC,GAAG,CAAC,UAAU,CAAC,aAAa,CAAC,0CAAG,CAAC,CAAC,CAAC;IACxE,CAAC;SAAM,CAAC;QACJ,MAAM,IAAI,yBAAW,CACjB,iCAAe,CAAC,eAAe,EAC/B,+EAA+E,CAClF,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;IAC9B,CAAC;IAED,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QACzB,MAAM,IAAI,yBAAW,CACjB,iCAAe,CAAC,6BAA6B,EAC7C,uDAAuD,UAAU,EAAE,CACtE,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,QAAQ,CAAC;AACpB,CAAC;AAED,SAAgB,2BAA2B,CAAC,aAA4B;IACpE,IAAI,qBAAqB,KAAK,SAAS,EAAE,CAAC;QACtC,MAAM,IAAI,yBAAW,CACjB,iCAAe,CAAC,0BAA0B,EAC1C,2DAA2D,CAC9D,CAAC,UAAU,CAAC,2BAA2B,CAAC,CAAC;IAC9C,CAAC;IAED,MAAM,SAAS,GAAG,qBAAqB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC3D,OAAO,SAAS,KAAK,SAAS,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;AAC3D,CAAC"}
@@ -0,0 +1,14 @@
1
+ import { Argon2Options, AsymmetricKeySpec, Cipher, CryptoHash, KDF } from "@nmshd/rs-crypto-types";
2
+ import { CryptoDerivationAlgorithm, CryptoEncryptionAlgorithm } from "..";
3
+ import { CryptoExchangeAlgorithm } from "../exchange/CryptoExchange";
4
+ import { CryptoHashAlgorithm } from "../hash/CryptoHash";
5
+ import { CryptoSignatureAlgorithm } from "../signature/CryptoSignatureAlgorithm";
6
+ export declare class CryptoLayerUtils {
7
+ static asymSpecFromCryptoExchangeOrSignatureAlgorithm(algorithm: CryptoExchangeAlgorithm | CryptoSignatureAlgorithm): AsymmetricKeySpec;
8
+ static cryptoHashAlgorithmFromCryptoHash(cryptoHash: CryptoHash): CryptoHashAlgorithm;
9
+ static cryptoHashFromCryptoHashAlgorithm(algorithm: CryptoHashAlgorithm): CryptoHash;
10
+ static cipherFromCryptoEncryptionAlgorithm(alg: CryptoEncryptionAlgorithm): Cipher;
11
+ static cryptoEncryptionAlgorithmFromCipher(cipher: Cipher): CryptoEncryptionAlgorithm;
12
+ static argon2OptionsFromIterationsMemLimitAndParallelism(iterations: number, memlimit: number, parallelism: number): Argon2Options;
13
+ static kdfFromCryptoDerivation(derivationAlgorithm: CryptoDerivationAlgorithm, iterations: number, memlimit: number, parallelism: number): KDF;
14
+ }
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CryptoLayerUtils = void 0;
4
+ const CryptoError_1 = require("../CryptoError");
5
+ const CryptoErrorCode_1 = require("../CryptoErrorCode");
6
+ class CryptoLayerUtils {
7
+ static asymSpecFromCryptoExchangeOrSignatureAlgorithm(algorithm) {
8
+ switch (algorithm) {
9
+ case 1 /* CryptoExchangeAlgorithm.ECDH_P256 */:
10
+ return "P256";
11
+ case 2 /* CryptoExchangeAlgorithm.ECDH_P521 */:
12
+ return "P521";
13
+ case 3 /* CryptoExchangeAlgorithm.ECDH_X25519 */:
14
+ return "Curve25519";
15
+ case 1 /* CryptoSignatureAlgorithm.ECDSA_P256 */:
16
+ return "P256";
17
+ case 2 /* CryptoSignatureAlgorithm.ECDSA_P521 */:
18
+ return "P521";
19
+ case 3 /* CryptoSignatureAlgorithm.ECDSA_ED25519 */:
20
+ return "Curve25519";
21
+ }
22
+ }
23
+ static cryptoHashAlgorithmFromCryptoHash(cryptoHash) {
24
+ // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
25
+ switch (cryptoHash) {
26
+ case "Sha2_256":
27
+ return 1 /* CryptoHashAlgorithm.SHA256 */;
28
+ case "Sha2_512":
29
+ return 2 /* CryptoHashAlgorithm.SHA512 */;
30
+ case "Blake2b":
31
+ return 3 /* CryptoHashAlgorithm.BLAKE2B */;
32
+ default:
33
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.CalUnsupportedAlgorithm, `Hash function ${cryptoHash} is not supported by ts crypto.`);
34
+ }
35
+ }
36
+ static cryptoHashFromCryptoHashAlgorithm(algorithm) {
37
+ switch (algorithm) {
38
+ case 1 /* CryptoHashAlgorithm.SHA256 */:
39
+ return "Sha2_256";
40
+ case 2 /* CryptoHashAlgorithm.SHA512 */:
41
+ return "Sha2_512";
42
+ case 3 /* CryptoHashAlgorithm.BLAKE2B */:
43
+ return "Blake2b";
44
+ }
45
+ }
46
+ static cipherFromCryptoEncryptionAlgorithm(alg) {
47
+ switch (alg) {
48
+ case 1 /* CryptoEncryptionAlgorithm.AES128_GCM */:
49
+ return "AesGcm128";
50
+ case 2 /* CryptoEncryptionAlgorithm.AES256_GCM */:
51
+ return "AesGcm256";
52
+ case 3 /* CryptoEncryptionAlgorithm.XCHACHA20_POLY1305 */:
53
+ return "XChaCha20Poly1305";
54
+ case 4 /* CryptoEncryptionAlgorithm.AES128_CBC */:
55
+ return "AesCbc128";
56
+ case 5 /* CryptoEncryptionAlgorithm.AES256_CBC */:
57
+ return "AesCbc256";
58
+ case 6 /* CryptoEncryptionAlgorithm.CHACHA20_POLY1305 */:
59
+ return "ChaCha20Poly1305";
60
+ }
61
+ }
62
+ static cryptoEncryptionAlgorithmFromCipher(cipher) {
63
+ switch (cipher) {
64
+ case "AesGcm128":
65
+ return 1 /* CryptoEncryptionAlgorithm.AES128_GCM */;
66
+ case "AesGcm256":
67
+ return 2 /* CryptoEncryptionAlgorithm.AES256_GCM */;
68
+ case "AesCbc128":
69
+ return 4 /* CryptoEncryptionAlgorithm.AES128_CBC */;
70
+ case "AesCbc256":
71
+ return 5 /* CryptoEncryptionAlgorithm.AES256_CBC */;
72
+ case "XChaCha20Poly1305":
73
+ return 3 /* CryptoEncryptionAlgorithm.XCHACHA20_POLY1305 */;
74
+ case "ChaCha20Poly1305":
75
+ return 6 /* CryptoEncryptionAlgorithm.CHACHA20_POLY1305 */;
76
+ }
77
+ }
78
+ static argon2OptionsFromIterationsMemLimitAndParallelism(iterations, memlimit, parallelism) {
79
+ const kibiByteBase = 2 ^ 10;
80
+ if (memlimit % kibiByteBase !== 0) {
81
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.WrongParameters, "rust-crypto uses kibibytes for Argon2. The `memlimit` parameter (in bytes) is not a multiple of `2^10` and thus not convertible without loss.").setContext(CryptoLayerUtils.argon2OptionsFromIterationsMemLimitAndParallelism);
82
+ }
83
+ const memory = memlimit / kibiByteBase;
84
+ const options = {
85
+ memory: memory,
86
+ iterations: iterations,
87
+ parallelism: parallelism
88
+ };
89
+ return options;
90
+ }
91
+ static kdfFromCryptoDerivation(derivationAlgorithm, iterations, memlimit, parallelism) {
92
+ const options = CryptoLayerUtils.argon2OptionsFromIterationsMemLimitAndParallelism(iterations, memlimit, parallelism);
93
+ switch (derivationAlgorithm) {
94
+ case "argon2id" /* CryptoDerivationAlgorithm.ARGON2ID */:
95
+ // eslint-disable-next-line @typescript-eslint/naming-convention
96
+ return { Argon2id: options };
97
+ case "argon2i" /* CryptoDerivationAlgorithm.ARGON2I */:
98
+ // eslint-disable-next-line @typescript-eslint/naming-convention
99
+ return { Argon2i: options };
100
+ default:
101
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.WrongParameters, `Crypto derivation algorithm '${derivationAlgorithm}' not supported.`).setContext(CryptoLayerUtils.kdfFromCryptoDerivation);
102
+ }
103
+ }
104
+ }
105
+ exports.CryptoLayerUtils = CryptoLayerUtils;
106
+ //# sourceMappingURL=CryptoLayerUtils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CryptoLayerUtils.js","sourceRoot":"","sources":["../../src/crypto-layer/CryptoLayerUtils.ts"],"names":[],"mappings":";;;AAEA,gDAA6C;AAC7C,wDAAqD;AAKrD,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ializableAsync } from "@js-soft/ts-serval";
2
+ import { KeyHandle, KeySpec, Provider } from "@nmshd/rs-crypto-types";
3
+ import { CoreBuffer, ICoreBuffer } from "../../CoreBuffer";
4
+ import { CryptoSerializableAsync } from "../../CryptoSerializable";
5
+ import { ProviderIdentifier } from "../CryptoLayerProviders";
6
+ export interface IBaseKeyHandleSerialized extends ISerialized {
7
+ kid: string;
8
+ pnm: string;
9
+ spc: KeySpec;
10
+ }
11
+ export interface IBaseKeyHandle extends ISerializable {
12
+ id: string;
13
+ providerName: string;
14
+ spec: KeySpec;
15
+ }
16
+ export interface BaseKeyHandleConstructor<T extends BaseKeyHandle> {
17
+ new (): T;
18
+ deserialize(value: string): Promise<T>;
19
+ fromProviderAndKeyHandle(provider: Provider, keyHandle: KeyHandle, other?: {
20
+ providerName?: string;
21
+ keyId?: string;
22
+ keySpec?: KeySpec;
23
+ }): Promise<T>;
24
+ fromAny(value: any): Promise<T>;
25
+ }
26
+ /**
27
+ * Represents a handle to a secret key used for symmetric encryption/decryption within the crypto layer.
28
+ * This handle encapsulates a reference to the key material, managed by the underlying crypto provider,
29
+ * without exposing the raw key material directly.
30
+ */
31
+ export declare abstract class BaseKeyHandle extends CryptoSerializableAsync implements IBaseKeyHandle {
32
+ id: string;
33
+ providerName: string;
34
+ spec: KeySpec;
35
+ provider: Provider;
36
+ keyHandle: KeyHandle;
37
+ /**
38
+ * Deserializes an object representation of a {@link BaseKeyHandle}.
39
+ *
40
+ * This method is not able to import raw keys or {@link KeyHandle}.
41
+ */
42
+ static from<T extends BaseKeyHandle>(this: BaseKeyHandleConstructor<T>, value: BaseKeyHandleConstructor<T> | IBaseKeyHandle | CoreBuffer): Promise<T>;
43
+ /** @see from */
44
+ static fromJSON<T extends BaseKeyHandle>(this: BaseKeyHandleConstructor<T>, value: IBaseKeyHandleSerialized): Promise<T>;
45
+ /** @see from */
46
+ static fromBase64<T extends BaseKeyHandle>(this: BaseKeyHandleConstructor<T>, value: string): Promise<T>;
47
+ /**
48
+ * Creates a new {@link BaseKeyHandle} or its child from an existing {@link KeyHandle}.
49
+ */
50
+ static fromProviderAndKeyHandle<T extends BaseKeyHandle>(this: new () => T, provider: Provider, keyHandle: KeyHandle): Promise<T>;
51
+ protected static preFrom(value: any): any;
52
+ static postFrom<T extends SerializableAsync>(value: T): Promise<T>;
53
+ }
54
+ export declare abstract class ImportableBaseKeyHandle extends BaseKeyHandle {
55
+ /**
56
+ * Creates a new {@link BaseKeyHandle} or its child by importing a raw key into a provider.
57
+ */
58
+ static fromRawKey<T extends ImportableBaseKeyHandle>(this: BaseKeyHandleConstructor<T>, providerIdent: ProviderIdentifier, rawKey: ICoreBuffer, spec: KeySpec): Promise<T>;
59
+ }
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ImportableBaseKeyHandle = exports.BaseKeyHandle = void 0;
13
+ const ts_serval_1 = require("@js-soft/ts-serval");
14
+ const checks_1 = require("@nmshd/rs-crypto-types/checks");
15
+ const CoreBuffer_1 = require("../../CoreBuffer");
16
+ const CryptoError_1 = require("../../CryptoError");
17
+ const CryptoErrorCode_1 = require("../../CryptoErrorCode");
18
+ const CryptoSerializable_1 = require("../../CryptoSerializable");
19
+ const CryptoLayerProviders_1 = require("../CryptoLayerProviders");
20
+ /**
21
+ * Represents a handle to a secret key used for symmetric encryption/decryption within the crypto layer.
22
+ * This handle encapsulates a reference to the key material, managed by the underlying crypto provider,
23
+ * without exposing the raw key material directly.
24
+ */
25
+ let BaseKeyHandle = class BaseKeyHandle extends CryptoSerializable_1.CryptoSerializableAsync {
26
+ /**
27
+ * Deserializes an object representation of a {@link BaseKeyHandle}.
28
+ *
29
+ * This method is not able to import raw keys or {@link KeyHandle}.
30
+ */
31
+ static async from(value) {
32
+ return await this.fromAny(value);
33
+ }
34
+ /** @see from */
35
+ static async fromJSON(value) {
36
+ return await this.fromAny(value);
37
+ }
38
+ /** @see from */
39
+ static async fromBase64(value) {
40
+ return await this.deserialize(CoreBuffer_1.CoreBuffer.base64_utf8(value));
41
+ }
42
+ /**
43
+ * Creates a new {@link BaseKeyHandle} or its child from an existing {@link KeyHandle}.
44
+ */
45
+ static async fromProviderAndKeyHandle(provider, keyHandle) {
46
+ const result = new this();
47
+ [result.providerName, result.id, result.spec] = await Promise.all([
48
+ provider.providerName(),
49
+ keyHandle.id(),
50
+ keyHandle.spec()
51
+ ]);
52
+ result.provider = provider;
53
+ result.keyHandle = keyHandle;
54
+ return result;
55
+ }
56
+ static preFrom(value) {
57
+ if (value.kid) {
58
+ value = {
59
+ id: value.kid,
60
+ providerName: value.pnm,
61
+ spec: value.spc
62
+ };
63
+ }
64
+ return value;
65
+ }
66
+ static async postFrom(value) {
67
+ if (!(value instanceof this)) {
68
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.DeserializeValidation, "Expected 'BaseKeyHandle' in postFrom.");
69
+ }
70
+ const provider = (0, CryptoLayerProviders_1.getProvider)({ providerName: value.providerName });
71
+ const keyHandle = await provider.loadKey(value.id);
72
+ value.keyHandle = keyHandle;
73
+ value.provider = provider;
74
+ return value;
75
+ }
76
+ };
77
+ exports.BaseKeyHandle = BaseKeyHandle;
78
+ __decorate([
79
+ (0, ts_serval_1.validate)(),
80
+ (0, ts_serval_1.serialize)(),
81
+ __metadata("design:type", String)
82
+ ], BaseKeyHandle.prototype, "id", void 0);
83
+ __decorate([
84
+ (0, ts_serval_1.validate)(),
85
+ (0, ts_serval_1.serialize)(),
86
+ __metadata("design:type", String)
87
+ ], BaseKeyHandle.prototype, "providerName", void 0);
88
+ __decorate([
89
+ (0, ts_serval_1.validate)({
90
+ customValidator: (value) => {
91
+ if ((0, checks_1.isKeySpec)(value))
92
+ return undefined;
93
+ return "Is not of type KeySpec.";
94
+ }
95
+ }),
96
+ (0, ts_serval_1.serialize)(),
97
+ __metadata("design:type", Object)
98
+ ], BaseKeyHandle.prototype, "spec", void 0);
99
+ exports.BaseKeyHandle = BaseKeyHandle = __decorate([
100
+ (0, ts_serval_1.type)("BaseKeyHandle")
101
+ ], BaseKeyHandle);
102
+ class ImportableBaseKeyHandle extends BaseKeyHandle {
103
+ /**
104
+ * Creates a new {@link BaseKeyHandle} or its child by importing a raw key into a provider.
105
+ */
106
+ static async fromRawKey(providerIdent, rawKey, spec) {
107
+ const provider = (0, CryptoLayerProviders_1.getProvider)(providerIdent);
108
+ let keyHandle;
109
+ try {
110
+ keyHandle = await provider.importKey(spec, rawKey.buffer);
111
+ }
112
+ catch (e) {
113
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.CalImportOfKey, "Failed to import raw symmetric key.", undefined, e, ImportableBaseKeyHandle.fromRawKey);
114
+ }
115
+ return await this.fromProviderAndKeyHandle(provider, keyHandle);
116
+ }
117
+ }
118
+ exports.ImportableBaseKeyHandle = ImportableBaseKeyHandle;
119
+ //# sourceMappingURL=BaseKeyHandle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseKeyHandle.js","sourceRoot":"","sources":["../../../src/crypto-layer/encryption/BaseKeyHandle.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,kDAA8G;AAE9G,0DAA0D;AAC1D,iDAA2D;AAC3D,mDAAgD;AAChD,2DAAwD;AACxD,iEAAmE;AACnE,kEAA0E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GAAG,MAAM,QAAQ,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;QAC9D,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACT,MAAM,IAAI,yBAAW,CACjB,iCAAe,CAAC,cAAc,EAC9B,qCAAqC,EACrC,SAAS,EACT,CAAU,EACV,uBAAuB,CAAC,UAAU,CACrC,CAAC;QACN,CAAC;QACD,OAAO,MAAM,IAAI,CAAC,wBAAwB,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;IACpE,CAAC;CACJ;AAzBD,0DAyBC"}
@@ -0,0 +1,27 @@
1
+ import { Provider } from "@nmshd/rs-crypto-types";
2
+ import { CoreBuffer } from "../../CoreBuffer";
3
+ import { CryptoCipher } from "../../encryption/CryptoCipher";
4
+ import { CryptoEncryptionAlgorithm } from "../../encryption/CryptoEncryption";
5
+ import { CryptoSecretKey } from "../../encryption/CryptoSecretKey";
6
+ import { CryptoHashAlgorithm } from "../../hash/CryptoHash";
7
+ import { ProviderIdentifier } from "../CryptoLayerProviders";
8
+ import { BaseKeyHandle } from "./BaseKeyHandle";
9
+ import { DeviceBoundKeyHandle } from "./DeviceBoundKeyHandle";
10
+ import { PortableDerivedKeyHandle } from "./PortableDerivedKeyHandle";
11
+ import { PortableKeyHandle } from "./PortableKeyHandle";
12
+ export declare class CryptoEncryptionHandle {
13
+ private static generateKeyHandle;
14
+ static generateDeviceBoundKeyHandle(providerIdent: ProviderIdentifier, encryptionAlgorithm: CryptoEncryptionAlgorithm, hashAlgorithm: CryptoHashAlgorithm): Promise<DeviceBoundKeyHandle>;
15
+ static generatePortableKeyHandle(providerIdent: ProviderIdentifier, encryptionAlgorithm: CryptoEncryptionAlgorithm, hashAlgorithm: CryptoHashAlgorithm): Promise<PortableKeyHandle>;
16
+ static encrypt<T extends BaseKeyHandle>(plaintext: CoreBuffer, secretKeyHandle: T, nonce?: CoreBuffer): Promise<CryptoCipher>;
17
+ static encryptWithCounter<T extends BaseKeyHandle>(plaintext: CoreBuffer, secretKeyHandle: T, nonce: CoreBuffer, counter: number): Promise<CryptoCipher>;
18
+ static decrypt<T extends BaseKeyHandle>(cipher: CryptoCipher, secretKeyHandle: T, nonce?: CoreBuffer): Promise<CoreBuffer>;
19
+ static decryptWithCounter<T extends BaseKeyHandle>(cipher: CryptoCipher, secretKeyHandle: T, nonce: CoreBuffer, counter: number): Promise<CoreBuffer>;
20
+ static createNonce(algorithm: CryptoEncryptionAlgorithm, provider: Provider): Promise<CoreBuffer>;
21
+ static extractRawKey(portableKeyHandle: PortableKeyHandle | PortableDerivedKeyHandle): Promise<CoreBuffer>;
22
+ static cryptoSecretKeyFromPortableKeyHandle(portableKeyHandle: PortableKeyHandle | PortableDerivedKeyHandle): Promise<CryptoSecretKey>;
23
+ private static keyHandleFromCryptoSecretKey;
24
+ static portableKeyHandleFromCryptoSecretKey(providerIdent: ProviderIdentifier, cryptoSecretKey: CryptoSecretKey, signingHash?: CryptoHashAlgorithm): Promise<PortableKeyHandle>;
25
+ static portableDerivedKeyHandleFromCryptoSecretKey(providerIdent: ProviderIdentifier, cryptoSecretKey: CryptoSecretKey, signingHash?: CryptoHashAlgorithm): Promise<PortableDerivedKeyHandle>;
26
+ private static _addCounter;
27
+ }
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CryptoEncryptionHandle = void 0;
4
+ const CoreBuffer_1 = require("../../CoreBuffer");
5
+ const CryptoError_1 = require("../../CryptoError");
6
+ const CryptoErrorCode_1 = require("../../CryptoErrorCode");
7
+ const CryptoValidation_1 = require("../../CryptoValidation");
8
+ const CryptoCipher_1 = require("../../encryption/CryptoCipher");
9
+ const CryptoSecretKey_1 = require("../../encryption/CryptoSecretKey");
10
+ const CryptoLayerProviders_1 = require("../CryptoLayerProviders");
11
+ const CryptoLayerUtils_1 = require("../CryptoLayerUtils");
12
+ const DeviceBoundKeyHandle_1 = require("./DeviceBoundKeyHandle");
13
+ const PortableDerivedKeyHandle_1 = require("./PortableDerivedKeyHandle");
14
+ const PortableKeyHandle_1 = require("./PortableKeyHandle");
15
+ class CryptoEncryptionHandle {
16
+ static async generateKeyHandle(constructor, providerIdent, spec) {
17
+ const provider = (0, CryptoLayerProviders_1.getProvider)(providerIdent);
18
+ const keyHandle = await provider.createKey(spec);
19
+ const secretKeyHandle = await constructor.fromProviderAndKeyHandle(provider, keyHandle, {
20
+ keySpec: spec
21
+ });
22
+ return secretKeyHandle;
23
+ }
24
+ static async generateDeviceBoundKeyHandle(providerIdent, encryptionAlgorithm, hashAlgorithm) {
25
+ const deviceBoundSpec = {
26
+ cipher: CryptoLayerUtils_1.CryptoLayerUtils.cipherFromCryptoEncryptionAlgorithm(encryptionAlgorithm),
27
+ signing_hash: CryptoLayerUtils_1.CryptoLayerUtils.cryptoHashFromCryptoHashAlgorithm(hashAlgorithm),
28
+ ephemeral: false,
29
+ non_exportable: true
30
+ };
31
+ return await this.generateKeyHandle(DeviceBoundKeyHandle_1.DeviceBoundKeyHandle, providerIdent, deviceBoundSpec);
32
+ }
33
+ static async generatePortableKeyHandle(providerIdent, encryptionAlgorithm, hashAlgorithm) {
34
+ const portableSpec = {
35
+ cipher: CryptoLayerUtils_1.CryptoLayerUtils.cipherFromCryptoEncryptionAlgorithm(encryptionAlgorithm),
36
+ signing_hash: CryptoLayerUtils_1.CryptoLayerUtils.cryptoHashFromCryptoHashAlgorithm(hashAlgorithm),
37
+ ephemeral: false,
38
+ non_exportable: false
39
+ };
40
+ return await this.generateKeyHandle(PortableKeyHandle_1.PortableKeyHandle, providerIdent, portableSpec);
41
+ }
42
+ static async encrypt(plaintext, secretKeyHandle, nonce) {
43
+ const encryptionAlgorithm = CryptoLayerUtils_1.CryptoLayerUtils.cryptoEncryptionAlgorithmFromCipher(secretKeyHandle.spec.cipher);
44
+ if (nonce === undefined || nonce.buffer.length === 0) {
45
+ nonce = await this.createNonce(encryptionAlgorithm, secretKeyHandle.provider);
46
+ }
47
+ else {
48
+ CryptoValidation_1.CryptoValidation.checkNonceForAlgorithm(nonce, encryptionAlgorithm);
49
+ }
50
+ let cipher;
51
+ try {
52
+ cipher = await secretKeyHandle.keyHandle.encryptWithIv(plaintext.buffer, nonce.buffer);
53
+ }
54
+ catch (e) {
55
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.EncryptionEncrypt, `${e}`, undefined, e, CryptoEncryptionHandle.encrypt);
56
+ }
57
+ return CryptoCipher_1.CryptoCipher.from({
58
+ cipher: CoreBuffer_1.CoreBuffer.from(cipher),
59
+ algorithm: encryptionAlgorithm,
60
+ nonce
61
+ });
62
+ }
63
+ static async encryptWithCounter(plaintext, secretKeyHandle, nonce, counter) {
64
+ const encryptionAlgorithm = CryptoLayerUtils_1.CryptoLayerUtils.cryptoEncryptionAlgorithmFromCipher(secretKeyHandle.spec.cipher);
65
+ CryptoValidation_1.CryptoValidation.checkCounter(counter);
66
+ CryptoValidation_1.CryptoValidation.checkNonceForAlgorithm(nonce, encryptionAlgorithm);
67
+ const publicNonce = this._addCounter(nonce.buffer, counter);
68
+ let cipher;
69
+ try {
70
+ cipher = await secretKeyHandle.keyHandle.encryptWithIv(plaintext.buffer, publicNonce.buffer);
71
+ }
72
+ catch (e) {
73
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.EncryptionEncrypt, `${e}`, undefined, e, CryptoEncryptionHandle.encryptWithCounter);
74
+ }
75
+ return CryptoCipher_1.CryptoCipher.from({
76
+ cipher: CoreBuffer_1.CoreBuffer.from(cipher),
77
+ algorithm: encryptionAlgorithm,
78
+ counter
79
+ });
80
+ }
81
+ static async decrypt(cipher, secretKeyHandle, nonce) {
82
+ const encryptionAlgorithm = CryptoLayerUtils_1.CryptoLayerUtils.cryptoEncryptionAlgorithmFromCipher(secretKeyHandle.spec.cipher);
83
+ let publicNonce;
84
+ if (nonce !== undefined) {
85
+ CryptoValidation_1.CryptoValidation.checkNonceForAlgorithm(nonce, encryptionAlgorithm);
86
+ publicNonce = nonce.buffer;
87
+ }
88
+ else if (cipher.nonce !== undefined) {
89
+ publicNonce = cipher.nonce.buffer;
90
+ }
91
+ else {
92
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.EncryptionWrongNonce, "Cipher does not contain a nonce and no nonce is given.").setContext(CryptoEncryptionHandle.decrypt);
93
+ }
94
+ try {
95
+ const buffer = await secretKeyHandle.keyHandle.decryptData(cipher.cipher.buffer, publicNonce);
96
+ return CoreBuffer_1.CoreBuffer.from(buffer);
97
+ }
98
+ catch (e) {
99
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.EncryptionEncrypt, `${e}`, undefined, e, CryptoEncryptionHandle.decrypt);
100
+ }
101
+ }
102
+ static async decryptWithCounter(cipher, secretKeyHandle, nonce, counter) {
103
+ const encryptionAlgorithm = CryptoLayerUtils_1.CryptoLayerUtils.cryptoEncryptionAlgorithmFromCipher(secretKeyHandle.spec.cipher);
104
+ CryptoValidation_1.CryptoValidation.checkCounter(counter);
105
+ CryptoValidation_1.CryptoValidation.checkNonceForAlgorithm(nonce, encryptionAlgorithm);
106
+ const publicNonce = this._addCounter(nonce.buffer, counter);
107
+ try {
108
+ const buffer = await secretKeyHandle.keyHandle.decryptData(cipher.cipher.buffer, publicNonce.buffer);
109
+ return CoreBuffer_1.CoreBuffer.from(buffer);
110
+ }
111
+ catch (e) {
112
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.EncryptionDecrypt, `${e}`, undefined, e, CryptoEncryptionHandle.decryptWithCounter);
113
+ }
114
+ }
115
+ static async createNonce(algorithm, provider) {
116
+ let nonceLength;
117
+ switch (algorithm) {
118
+ case 1 /* CryptoEncryptionAlgorithm.AES128_GCM */:
119
+ case 2 /* CryptoEncryptionAlgorithm.AES256_GCM */:
120
+ case 6 /* CryptoEncryptionAlgorithm.CHACHA20_POLY1305 */:
121
+ nonceLength = 12;
122
+ break;
123
+ case 4 /* CryptoEncryptionAlgorithm.AES128_CBC */:
124
+ case 5 /* CryptoEncryptionAlgorithm.AES256_CBC */:
125
+ nonceLength = 16;
126
+ break;
127
+ case 3 /* CryptoEncryptionAlgorithm.XCHACHA20_POLY1305 */:
128
+ nonceLength = 24;
129
+ break;
130
+ }
131
+ const buffer = await provider.getRandom(nonceLength);
132
+ return CoreBuffer_1.CoreBuffer.from(buffer);
133
+ }
134
+ static async extractRawKey(portableKeyHandle) {
135
+ const rawKey = await portableKeyHandle.keyHandle.extractKey();
136
+ return new CoreBuffer_1.CoreBuffer(rawKey);
137
+ }
138
+ static async cryptoSecretKeyFromPortableKeyHandle(portableKeyHandle) {
139
+ const rawKeyPromise = CryptoEncryptionHandle.extractRawKey(portableKeyHandle);
140
+ const algorithm = CryptoLayerUtils_1.CryptoLayerUtils.cryptoEncryptionAlgorithmFromCipher(portableKeyHandle.spec.cipher);
141
+ const cryptoSecretKeyObj = {
142
+ algorithm: algorithm,
143
+ secretKey: await rawKeyPromise
144
+ };
145
+ return CryptoSecretKey_1.CryptoSecretKey.from(cryptoSecretKeyObj);
146
+ }
147
+ static async keyHandleFromCryptoSecretKey(constructor, providerIdent, cryptoSecretKey, signingHash, ephemeral) {
148
+ const cipher = CryptoLayerUtils_1.CryptoLayerUtils.cipherFromCryptoEncryptionAlgorithm(cryptoSecretKey.algorithm);
149
+ const keySpec = {
150
+ cipher: cipher,
151
+ ephemeral: ephemeral,
152
+ signing_hash: CryptoLayerUtils_1.CryptoLayerUtils.cryptoHashFromCryptoHashAlgorithm(signingHash),
153
+ non_exportable: false
154
+ };
155
+ const provider = (0, CryptoLayerProviders_1.getProvider)(providerIdent);
156
+ const keyHandle = await provider.importKey(keySpec, cryptoSecretKey.secretKey.buffer);
157
+ return await constructor.fromProviderAndKeyHandle(provider, keyHandle);
158
+ }
159
+ static async portableKeyHandleFromCryptoSecretKey(providerIdent, cryptoSecretKey, signingHash = 2 /* CryptoHashAlgorithm.SHA512 */) {
160
+ return await CryptoEncryptionHandle.keyHandleFromCryptoSecretKey(PortableKeyHandle_1.PortableKeyHandle, providerIdent, cryptoSecretKey, signingHash, false);
161
+ }
162
+ static async portableDerivedKeyHandleFromCryptoSecretKey(providerIdent, cryptoSecretKey, signingHash = 2 /* CryptoHashAlgorithm.SHA512 */) {
163
+ return await CryptoEncryptionHandle.keyHandleFromCryptoSecretKey(PortableDerivedKeyHandle_1.PortableDerivedKeyHandle, providerIdent, cryptoSecretKey, signingHash, true);
164
+ }
165
+ static _addCounter(nonce, counter) {
166
+ let buffer;
167
+ if (nonce instanceof Uint8Array) {
168
+ buffer = new CoreBuffer_1.CoreBuffer(nonce);
169
+ }
170
+ else if (nonce instanceof CoreBuffer_1.CoreBuffer) {
171
+ buffer = nonce;
172
+ }
173
+ else {
174
+ throw new CryptoError_1.CryptoError(CryptoErrorCode_1.CryptoErrorCode.EncryptionWrongNonce).setContext(CryptoEncryptionHandle.decryptWithCounter);
175
+ }
176
+ const clone = buffer.clone().add(counter);
177
+ return clone;
178
+ }
179
+ }
180
+ exports.CryptoEncryptionHandle = CryptoEncryptionHandle;
181
+ //# sourceMappingURL=CryptoEncryptionHandle.js.map