CCM is one of the supported [AEAD algorithms][]. Applications which use this mode must adhere to certain restrictions when using the cipher API:

    • The authentication tag length must be specified during cipher creation by setting the authTagLength option and must be one of 4, 6, 8, 10, 12, 14 or 16 bytes.
    • The length of the initialization vector (nonce) N must be between 7 and 13 bytes (7 ≤ N ≤ 13).
    • The length of the plaintext is limited to 2 ** (8 * (15 - N)) bytes.
    • When decrypting, the authentication tag must be set via setAuthTag() before calling update(). Otherwise, decryption will fail and final() will throw an error in compliance with section 2.6 of [RFC 3610][].
    • Using stream methods such as write(data), end(data) or pipe() in CCM mode might fail as CCM cannot handle more than one chunk of data per instance.
    • When passing additional authenticated data (AAD), the length of the actual message in bytes must be passed to setAAD() via the plaintextLength option. Many crypto libraries include the authentication tag in the ciphertext, which means that they produce ciphertexts of the length plaintextLength + authTagLength. Node.js does not include the authentication tag, so the ciphertext length is always plaintextLength. This is not necessary if no AAD is used.
    • As CCM processes the whole message at once, update() can only be called once.
    • Even though calling update() is sufficient to encrypt/decrypt the message, applications must call final() to compute or verify the authentication tag.
    1. const crypto = require('crypto');
    2. const key = 'keykeykeykeykeykeykeykey';
    3. const nonce = crypto.randomBytes(12);
    4. const aad = Buffer.from('0123456789', 'hex');
    5. const cipher = crypto.createCipheriv('aes-192-ccm', key, nonce, {
    6. authTagLength: 16
    7. });
    8. const plaintext = 'Hello world';
    9. cipher.setAAD(aad, {
    10. plaintextLength: Buffer.byteLength(plaintext)
    11. });
    12. const ciphertext = cipher.update(plaintext, 'utf8');
    13. cipher.final();
    14. const tag = cipher.getAuthTag();
    15. // Now transmit { ciphertext, nonce, tag }.
    16. const decipher = crypto.createDecipheriv('aes-192-ccm', key, nonce, {
    17. authTagLength: 16
    18. });
    19. decipher.setAuthTag(tag);
    20. decipher.setAAD(aad, {
    21. plaintextLength: ciphertext.length
    22. });
    23. const receivedPlaintext = decipher.update(ciphertext, null, 'utf8');
    24. try {
    25. decipher.final();
    26. } catch (err) {
    27. console.error('Authentication failed!');
    28. return;
    29. }
    30. console.log(receivedPlaintext);