Compare and contrast `crypto.subtle.wrapKey` and `crypto.subtle.encrypt`. When would you choose one over the other?
Node.js interview question for Advanced practice.
Answer
subtle.encrypt and subtle.wrapKey both perform encryption, but their intended targets are different. subtle.encrypt: This function is for encrypting general-purpose data (plaintext). It takes a key and an ArrayBuffer of data and returns the ciphertext. This is what you would use to encrypt a user's message, a file, or any other application data. subtle.wrapKey: This function is specifically for encrypting another CryptoKey object. It takes a 'wrapping' key and the CryptoKey to be wrapped (encrypted) and returns the encrypted key material. This is used for key management, particularly a pattern called envelope encryption, where you encrypt a high-volume data encryption key (DEK) with a lower-volume key encryption key (KEK). When to choose: Use encrypt for all general data encryption needs. Use wrapKey when you need to securely store or transmit a cryptographic key by encrypting it with another key.
Explanation
wrapKey is a fundamental operation in 'envelope encryption', a common pattern for managing data encryption keys.