MCPcopy Index your code
hub / github.com/nodejs/node / wrapKeyImpl

Function wrapKeyImpl

lib/internal/crypto/webcrypto.js:1029–1078  ·  view source on GitHub ↗
(format, key, wrappingKey, wrapAlgorithm)

Source from the content-addressed store, hash-verified

1027}
1028
1029function wrapKeyImpl(format, key, wrappingKey, wrapAlgorithm) {
1030 const prefix = prepareSubtleMethod(this, 'wrapKey', arguments.length, 4);
1031 let i = 0;
1032 format = convertSubtleArgument(prefix, 'KeyFormat', format, i++);
1033 key = convertSubtleArgument(prefix, 'CryptoKey', key, i++);
1034 wrappingKey = convertSubtleArgument(prefix, 'CryptoKey', wrappingKey, i++);
1035 const algorithm = convertSubtleArgument(
1036 prefix, 'AlgorithmIdentifier', wrapAlgorithm, i++);
1037 let normalizedAlgorithm;
1038 try {
1039 normalizedAlgorithm = normalizeAlgorithm(algorithm, 'wrapKey');
1040 } catch {
1041 normalizedAlgorithm = normalizeAlgorithm(algorithm, 'encrypt');
1042 }
1043
1044 if (normalizedAlgorithm.name !== getCryptoKeyAlgorithm(wrappingKey).name)
1045 throw lazyDOMException('Key algorithm mismatch', 'InvalidAccessError');
1046
1047 if (!hasCryptoKeyUsage(wrappingKey, 'wrapKey'))
1048 throw lazyDOMException(
1049 'Unable to use this key to wrapKey', 'InvalidAccessError');
1050
1051 const exportedKey = exportKeySync(format, key);
1052 let bytes = exportedKey;
1053
1054 if (format === 'jwk') {
1055 // The WebCrypto spec stringifies JWKs in a new global object. Rather
1056 // than create a new realm here, detach this internally generated JWK from
1057 // user-mutated prototypes so JSON.stringify cannot read inherited toJSON
1058 // hooks from the current global.
1059 detachFromUserPrototypes(exportedKey);
1060 const json = JSONStringify(exportedKey);
1061 // As per the NOTE in step 13 https://w3c.github.io/webcrypto/#SubtleCrypto-method-wrapKey
1062 // we're padding AES-KW wrapped JWK to make sure it is always a multiple of 8 bytes
1063 // in length
1064 // The spec then UTF-8 encodes json.
1065 if (normalizedAlgorithm.name === 'AES-KW' && json.length % 8 !== 0) {
1066 bytes = encodeUtf8String(
1067 json + StringPrototypeRepeat(' ', 8 - (json.length % 8)));
1068 } else {
1069 bytes = encodeUtf8String(json);
1070 }
1071 }
1072
1073 return cipherOrWrap(
1074 kWebCryptoCipherEncrypt,
1075 normalizedAlgorithm,
1076 wrappingKey,
1077 bytes);
1078}
1079
1080// subtle.unwrapKey() is essentially a subtle.decrypt() followed
1081// by a subtle.importKey().

Callers

nothing calls this directly

Calls 9

prepareSubtleMethodFunction · 0.85
convertSubtleArgumentFunction · 0.85
getCryptoKeyAlgorithmFunction · 0.85
lazyDOMExceptionFunction · 0.85
hasCryptoKeyUsageFunction · 0.85
exportKeySyncFunction · 0.85
detachFromUserPrototypesFunction · 0.85
cipherOrWrapFunction · 0.85
normalizeAlgorithmFunction · 0.70

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…