You have someone's public key and want to send them a secret. The usual shortcut goes like this: run ECDH, use the 32 bytes of the shared secret as the AES key, encrypt in CBC with whatever IV, done. It decrypts fine in tests. But it has three problems: nobody checks that the ciphertext wasn't tampered with, the ECDH secret is used as a key as is, and if the IV or the keys repeat, the same message produces the same ciphertext.
All three fit in the same OWASP Top 10 category. In this post I use it as a thread to walk, step by step and with code you can run, through how ECIES encrypts in encloom 2.0.7 (encloom/ecies): ECDH over secp256k1, SHA-512, AES-256-CBC, and HMAC-SHA256 in encrypt-then-MAC order.
Not a compliance guide and not an audit. encloom isn't audited, and OWASP doesn't certify libraries. This is about what each byte does and why.
A04:2025 Cryptographic Failures, in short
The current OWASP Top 10 is the 2025 edition. Cryptographic failures are A04:2025 – Cryptographic Failures. In the 2021 edition they were A02, and the page itself says they're "Moving down two positions to #4".
The page isn't a list of banned algorithms; it's a list of questions. Three of them are the backbone of this post:
"Are initialization vectors ignored, reused, or not generated sufficiently secure for the cryptographic mode of operation? Is an insecure mode of operation such as ECB in use? Is encryption used when authenticated encryption is more appropriate?"
"Are cryptographic error messages or side channel information exploitable, for example in the form of padding oracle attacks?"
And under how to prevent:
"Always use authenticated encryption instead of just encryption."
"In all cases, the IV should never be used twice for a fixed key."
Among the 32 CWEs the category maps are, for example, CWE-323 Reusing a Nonce, Key Pair in Encryption, CWE-325 Missing Required Cryptographic Step, and CWE-329 Not Using a Random IV with CBC Mode.
One thing to keep in mind for the end: that same page also recommends avoiding CBC. I deal with it in the limits section, because I don't want to sell ECIES with CBC as "what OWASP asks for".
ECIES as a mental picture
ECIES is hybrid encryption: the elliptic-curve part agrees on keys and the symmetric part encrypts the message. This is how encloom/ecies does it:
sender recipient (Bob) ────── ─────────────── new ephemeral pair (e, E) Z = x( e · PubBob ) Z = x( privBob · E ) H = SHA-512(Z) → 64 bytes H = SHA-512(Z) kEnc = H[0..32) kMac = H[32..64) same keys IV = 16 random bytes C = AES-256-CBC(kEnc, IV, message + PKCS#7) T = HMAC-SHA256(kMac, IV ‖ E ‖ C) ── sends IV, E, C, T ──▶ 1) recomputes T and compares 2) only if it matches, decrypts C E is the ephemeral public key. It travels in the clear and isn't secret: without Bob's private key it can't be used to recompute Z.
Step by step with encloom
1. Round trip
import { generateKeyPair } from "encloom/ecdsa"; import { encrypt, decrypt, serialize, deserialize } from "encloom/ecies"; import { utf8ToBuffer, bufferToUtf8 } from "encloom/helpers/encoding"; const bob = generateKeyPair(); // privateKey: 32 bytes, publicKey: 65 bytes (0x04…) const msg = utf8ToBuffer("hello, OWASP"); // 12 bytes const enc = await encrypt(bob.publicKey, msg); console.log(enc.iv.length, enc.ephemPublicKey.length, enc.ciphertext.length, enc.mac.length); // 16 65 16 32 const wire = serialize(enc); console.log(wire.length); // 97 = 16 + 33 + 32 + 16 const out = await decrypt(bob.privateKey, deserialize(wire)); console.log(bufferToUtf8(out)); // hello, OWASP encrypt returns an object with four fields: iv, ephemPublicKey, ciphertext, and mac. There are synchronous versions (encryptSync / decryptSync) with the same signature, minus the Promise.
2. The wire format
serialize concatenates in this order:
| Field | Bytes |
|---|---|
| IV | 16 |
Ephemeral public key, compressed (prefix 0x02/0x03) | 33 |
| MAC (HMAC-SHA256) | 32 |
| Ciphertext (AES-256-CBC with PKCS#7) | multiple of 16, minimum 16 |
A few details worth knowing if you're going to implement the other end in another language:
- On the wire the ephemeral key is compressed (33 bytes), but
encryptreturns it uncompressed (65 bytes), and the MAC is computed over the 65-byte version.deserializedecompresses it again before returning it, and since 2.0.6,decryptalso accepts the 33-byte key and decompresses it before verifying the MAC. - The wire order (
IV ‖ E ‖ MAC ‖ C) isn't the order of the data that goes into the MAC (IV ‖ E ‖ C). - The format didn't change between 2.0.4 and 2.0.7: anything encrypted with one of them decrypts with the other, in both directions.
deserialize rejects any buffer shorter than 81 bytes (16 + 33 + 32) with ECIES deserialize: buffer shorter than minimum serialized length.
3. The same thing, by hand
To show there's no magic, this example reproduces the encryption with encloom's individual primitives and compares the result with encryptSync's. I pass a fixed ephemeral key only so the computation can be repeated; in normal use you don't pass it (see below).
import { generateKeyPair } from "encloom/ecdsa"; import { encryptSync } from "encloom/ecies"; import { derive } from "encloom/ecdh"; import { sha512Sync } from "encloom/sha2"; import { aesCbcEncryptSync } from "encloom/aes"; import { hmacSha256SignSync } from "encloom/hmac"; import { concatBuffers, utf8ToBuffer } from "encloom/helpers/encoding"; const bob = generateKeyPair(); const ephemeral = generateKeyPair(); // only so the computation can be reproduced const msg = utf8ToBuffer("hello, OWASP"); const enc = encryptSync(bob.publicKey, msg, { ephemPrivateKey: ephemeral.privateKey }); const z = derive(ephemeral.privateKey, bob.publicKey); // x coordinate of the shared point const h = sha512Sync(z); const encKey = h.slice(0, 32); const macKey = h.slice(32); console.log(z.length, h.length, encKey.length, macKey.length); // 32 64 32 32 const ct = aesCbcEncryptSync(enc.iv, encKey, msg); const mac = hmacSha256SignSync(macKey, concatBuffers(enc.iv, ephemeral.publicKey, ct)); const same = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]); console.log(same(ct, enc.ciphertext), same(mac, enc.mac)); // true true console.log(same(derive(bob.privateKey, ephemeral.publicKey), z)); // true There are the four steps:
- ECDH.
derivemultiplies Bob's public key by the ephemeral private key and returns thexcoordinate of the resulting point, 32 bytes. - Derivation. SHA-512 over those 32 bytes gives 64. The first 32 are the AES key and the last 32, the HMAC key.
- Encryption. AES-256-CBC with a 16-byte IV and PKCS#7 padding.
- MAC. HMAC-SHA256 over
IV ‖ ephemeral key ‖ ciphertext.
The last line checks Bob's side: with his private key and the ephemeral public key he gets to the same Z.
Three mistakes this design avoids
Mistake 1: encrypting without authenticating
AES-CBC only provides confidentiality. If someone flips bits in the ciphertext, decryption doesn't notice: it returns garbage or something worse. And if your code responds differently when the padding is invalid, you're handing an attacker a padding oracle, which is exactly the OWASP question quoted above.
encloom applies encrypt-then-MAC: it encrypts first and then computes the HMAC over the result (plus the IV and the ephemeral key). On decryption the order is reversed and strict: it recomputes the HMAC, compares it in constant time and, if it doesn't match, throws Bad MAC before touching AES. The padding is only checked once the MAC is already valid, so a tampered ciphertext never reaches the stage where the padding could produce a different error.
You can check it by flipping a single bit in each part of the payload:
import { generateKeyPair } from "encloom/ecdsa"; import { encrypt, decrypt, serialize, deserialize } from "encloom/ecies"; import { utf8ToBuffer } from "encloom/helpers/encoding"; const bob = generateKeyPair(); const wire = serialize(await encrypt(bob.publicKey, utf8ToBuffer("hello, OWASP"))); for (const [name, pos] of [["IV", 0], ["ephemeral key", 16], ["MAC", 49], ["ciphertext", wire.length - 1]]) { const t = wire.slice(); t[pos] ^= 0x01; try { await decrypt(bob.privateKey, deserialize(t)); } catch (e) { console.log(name, "→", e.message); } } // IV → Bad MAC // ephemeral key → Bad MAC // MAC → Bad MAC // ciphertext → Bad MAC Always the same error, wherever the change comes from. Since the MAC also covers the IV and the ephemeral key, tampering with either of them is detected just like tampering with the ciphertext.
The order matters. The notes The Structure of Secure Systems (Corrigan-Gibbs, Devadas, Kalai, and Zeldovich, based on the 6.1600 course lectures) explain it in section 9.4. Paraphrasing: first you encrypt, then you compute the MAC over the ciphertext with an independent key, and you output both. On decryption, verbatim: "The decryption routine first checks the MAC tag, then decrypts the ciphertext." And the warning that follows compares the three ways: "Warning! Only use encrypt-then-MAC. There are a number of bad ways to combine encryption and MACs to attempt to build authenticated-encryption schemes. Encrypt-and-MAC (i.e., MAC the message instead of the ciphertext) is one way. MAC-then-Encrypt is another way." That's exactly what encloom does: HMAC over the ciphertext and verification before decrypting. And OWASP's Cryptographic Storage Cheat Sheet names it explicitly for when no authenticated mode is available: "If GCM or CCM are not available, then CTR mode or CBC mode should be used. As these do not provide any guarantees about the authenticity of the data, separate authentication should be implemented, such as using the Encrypt-then-MAC technique."
Mistake 2: using the raw ECDH secret as a key
The ECDH shared point isn't a ready-to-use key. You need two independent keys (one for AES and one for HMAC), and you shouldn't reuse the same material for both. NIST's recommendation for key agreement, SP 800-56A Rev. 3, says so in section 5.8: "The shared secret shall be used only by an approved key-derivation method (as specified in SP 800-56C) and shall not be used for any other purpose."
Note: Rev. 3 is from April 2018. Its NIST page carries a note dated January 6, 2026: "Planning Note (01/06/2026): NIST has decided to update this publication.", and the announcement explains the goals of that update. Until it's published, Rev. 3 remains the current version.
encloom runs the x coordinate through SHA-512 and splits the output into two 32-byte halves: [0, 32) for AES-256 and [32, 64) for HMAC-SHA256. That way the encryption key and the authentication key are never the same.
To be precise: a plain SHA-512 is a simple derivation. It isn't HKDF, nor the one-step KDF of SP 800-56C Rev. 2 (August 2020, NIST's current version). That KDF computes each block as "K(i) = H(counter || Z || FixedInfo)": paraphrasing, a 4-byte counter, the shared secret Z, and FixedInfo, which the standard defines as "A bit string of context-specific data that is appropriate for the relying key-establishment scheme." (section 4.1). A more recent NIST recommendation on key derivation, SP 800-108 Rev. 1 (August 2022, with updates from February 2024), follows the same pattern in its counter mode: "K(i) := PRF (KIN, [i]₂ || Label || 0x00 || Context || [L]₂)". I cite both to explain why you need to derive, not to claim that encloom follows those standards to the letter. The README itself (since 2.0.6) describes it as a legacy derivation, with no HKDF and no info context, kept for wire-format compatibility.
Mistake 3: reusing keys or IVs
If you encrypt the same message twice with the same key and the same IV, you get the same ciphertext, and anyone watching the traffic knows you repeated yourself. OWASP asks about it in so many words and maps CWE-323 and CWE-329 to this category.
In encloom/ecies, every call to encrypt generates:
- a new ephemeral key pair, with a private key of 32 random bytes that is redrawn if it doesn't fall within secp256k1's valid range; so the AES key and the HMAC key are different for every message;
- a new 16-byte IV from
crypto.getRandomValues.
import { generateKeyPair } from "encloom/ecdsa"; import { encrypt } from "encloom/ecies"; import { utf8ToBuffer, bufferToHex } from "encloom/helpers/encoding"; const bob = generateKeyPair(); const msg = utf8ToBuffer("same message"); const a = await encrypt(bob.publicKey, msg); const b = await encrypt(bob.publicKey, msg); console.log(bufferToHex(a.ephemPublicKey) === bufferToHex(b.ephemPublicKey)); // false console.log(bufferToHex(a.iv) === bufferToHex(b.iv)); // false console.log(bufferToHex(a.ciphertext) === bufferToHex(b.ciphertext)); // false An honest warning: encrypt accepts iv and ephemPrivateKey in an optional third argument, meant for test vectors (that's what I used in step 3). Since 2.0.6 the README marks them as "use only for test vectors, never in production", and since 2.0.7 the encrypt documentation you see in your editor repeats it. If you pin them in production, you cancel exactly this protection: with the same iv, the same ephemeral key, and the same message, the ciphertext comes out identical. Leave them out.
Bonus: invalid public keys
A public key that isn't a point on the curve shouldn't get into ECDH. encloom first checks the length and the prefix (33 bytes with 0x02/0x03, or 65 with 0x04) and then delegates to @noble/secp256k1's Point.fromBytes, which verifies that the point is on the curve:
import { generateKeyPair } from "encloom/ecdsa"; import { encrypt } from "encloom/ecies"; import { utf8ToBuffer } from "encloom/helpers/encoding"; const bob = generateKeyPair(); const broken = bob.publicKey.slice(); broken[64] ^= 0x01; // flips one bit of the y coordinate: the point is no longer on the curve try { await encrypt(broken, utf8ToBuffer("hello")); } catch (e) { console.log(e.message); // bad point: not on curve } const short = new Uint8Array(64); // no 0x04 prefix try { await encrypt(short, utf8ToBuffer("hello")); } catch (e) { console.log(e.message); // Bad public key } Limits: when to prefer something else
- OWASP says to avoid CBC. The same A04:2025 page says: "Avoid deprecated cryptographic functions, block building methods and padding schemes, such as MD5, SHA1, Cipher Block Chaining Mode (CBC), PKCS number 1 v1.5." AES-CBC with encrypt-then-MAC done right is still a valid construction (the Cheat Sheet accepts it as a fallback), but today an AEAD mode is preferable, such as AES-GCM or ChaCha20-Poly1305 (RFC 8439), which encrypts and authenticates in a single step. RFC 9771 (CFRG, May 2025) sums it up like this: "In contrast to generic compositions of Message Authentication Code (MAC) and encryption algorithms, an AEAD algorithm allows for a reduction in key and state sizes, improving the data processing speed." If you're interested in GCM, I covered it in the post about the 12-byte nonce and the tag.
- For new public-key encryption, look at HPKE. The Cryptographic Storage Cheat Sheet recommends "a maintained library implementing an established hybrid encryption scheme, such as Hybrid Public Key Encryption (HPKE)" (RFC 9180). encloom's ECIES makes the most sense when you already work with secp256k1 keys or need compatibility with this format.
- It doesn't authenticate the sender. Bob's public key is all it takes to encrypt something for him, so Bob doesn't know who sent it. CWE-322 (Key Exchange without Entity Authentication) is on the same OWASP list. If you need to know who's sending, sign the message (encloom has ECDSA in
encloom/ecdsa) or use an authenticated HPKE mode. - There's no replay protection. A valid payload can be sent again and will decrypt just the same. If that matters, add a unique identifier and record it on the recipient's side.
- It isn't post-quantum. The Cheat Sheet points it out: ECC-based public-key cryptography isn't secure against a future cryptographically relevant quantum computer.
- It isn't an audit. Everything I describe here can be checked in the 2.0.7 source code, but that doesn't replace an independent review.
Wrapping up
If you encrypt with ECIES, check these four things:
- Is the MAC verified before decrypting, and is the comparison constant-time?
- Does the ECDH secret go through a derivation that separates the encryption key from the MAC key?
- Does every message get a new ephemeral key and a new IV?
- Is the public key validated as a point on the curve?
encloom/ecies answers yes to all four as long as you don't force iv or ephemPrivateKey on it. Still, if you're starting from scratch and aren't tied to secp256k1, an AEAD scheme or HPKE is the more modern option.
If you want to keep going with encloom, these are the previous posts in the series:
- AES-GCM in TypeScript: the 12-byte nonce, the tag, and why your ciphertext won't decrypt on the other side (Medium)
- SHA-3 isn't Keccak: why your hash doesn't match Ethereum's (Medium)
And before those, HMAC over JSON in TypeScript — why verify fails in production and Buffer vs Uint8Array in TypeScript crypto (and why it hurts).
References
- OWASP Top 10:2025 — A04:2025 Cryptographic Failures
- OWASP — Cryptographic Storage Cheat Sheet
- NIST — SP 800-56A Rev. 3, section 5.8 · update announcement (January 2026)
- NIST — SP 800-56C Rev. 2, section 4.1 · SP 800-108 Rev. 1 (upd1), section "KDF in Counter Mode"
- H. Corrigan-Gibbs, S. Devadas, Y. Kalai, and N. Zeldovich — The Structure of Secure Systems, chapter 9: Authenticated Encryption, section 9.4
- RFC 9180 (HPKE) · RFC 8439 (ChaCha20-Poly1305) · RFC 9771 (properties of AEAD algorithms)
- encloom 2.0.7 — source on GitHub · npm
The examples were run with encloom 2.0.7 and Node 24.22.1.

