Symmetric Encryption, Hashing and AuthenticationIntroduction and ContextBlockchain systems depend on cryptographic mechanisms that provide confidentiality, integrity, authenticity and resistance to manipulation. Public-key cryptography is prominent in digital signatures and key exchange, but symmetric encryption, cryptographic hashing, message authentication codes (MACs), password hashing and secure random-number generation are equally important. They protect wallet backups, peer-to-peer channels, authenticated data structures, application secrets and consensus-related software. This chapter distinguishes the security goals and operating assumptions of these mechanisms. Encryption hides information; hashing produces a one-way integrity-oriented digest; authentication confirms that data came from a holder of a secret or key. Confusing these purposes is a frequent source of blockchain vulnerabilities. Learning ObjectivesBy the end of this chapter, you should be able to: - distinguish block ciphers from stream ciphers;
- select and evaluate encryption modes;
- explain authenticated encryption and nonce requirements;
- describe the security properties and limitations of cryptographic hashes;
- construct and evaluate MAC and HMAC-based designs;
- explain password hashing, salting and key stretching;
- assess secure randomness, key management and implementation risks;
- apply these principles to a blockchain-related security scenario.
1. Security Goals and TerminologyConfidentiality prevents unauthorized disclosure. Integrity ensures that data has not been altered. Authentication establishes the identity or authority of the sender. Non-repudiation is normally associated with digital signatures rather than symmetric encryption, because parties sharing one symmetric key cannot prove which party created a particular MAC. A cryptographic key is secret information controlling an algorithm. A nonce is a value intended to be used once with a particular key; it need not always be secret. An initialization vector (IV) initializes certain modes and may be public, but its reuse requirements depend on the mode. A tag is an authenticator attached to ciphertext or plaintext. A digest is the fixed-length output of a hash function. Security is usually expressed against an adversary with defined capabilities. Modern designs assume that algorithms are public and that security depends on keeping keys secret, not on hiding algorithms. This is the principle of Kerckhoffs: a system should remain secure when its design is known. 2. Symmetric EncryptionSymmetric encryption uses the same secret key, or computationally related secret keys, for encryption and decryption. An encryption scheme consists conceptually of algorithms Enc and Dec such that: DecK(EncK(M)) = M Here, K is the secret key and M is the plaintext. Correctness assumes a valid key, compatible parameters and an unmodified ciphertext. Confidentiality additionally requires resistance to practical attacks under the intended threat model. Block CiphersA block cipher transforms fixed-size blocks under a key. AES, the dominant modern standard, has a 128-bit block size and supports 128-, 192- and 256-bit keys. A block cipher by itself is not a complete method for encrypting arbitrary-length data; a mode of operation specifies how blocks, IVs, nonces and authentication are handled. The block size is not the same as the key size. A larger key generally increases resistance to exhaustive key search, while the block size affects how data can be processed and the probability of collisions in some modes. Brute-force work for an ideal k-bit key is approximately 2k trials in the worst case and about 2k-1 trials on average, although real security also depends on implementation and attack cost. Stream CiphersA stream cipher generates a keystream and combines it with plaintext, commonly using exclusive OR (XOR): Ci = Pi ⊕ Zi where P_i is a plaintext unit, Z_i is the corresponding keystream unit and C_i is ciphertext. Decryption applies XOR with the same keystream: Pi = Ci ⊕ Zi The crucial condition is that the same key-and-nonce combination must not generate the same keystream for two different messages. If it does, then: C1 ⊕ C2 = P1 ⊕ P2 This can reveal relationships between plaintexts and may enable recovery of both messages when one is known or predictable. ChaCha20 is a widely deployed modern stream cipher, usually used with Poly1305 in an authenticated-encryption construction. Block and Stream Ciphers Compared| Property | Block cipher | Stream cipher |
|---|
| Basic operation | Fixed-size blocks | Generated keystream units | | Typical issue | Incorrect mode or padding | Keystream/nonce reuse | | Partial data | Requires a suitable mode | Naturally supports arbitrary lengths | | Examples | AES | ChaCha20 | | Confidentiality alone? | No; authentication is still needed | No; authentication is still needed |
3. Modes of Operation and Authenticated EncryptionCommon Confidentiality ModesECB encrypts each block independently. Equal plaintext blocks produce equal ciphertext blocks, exposing patterns; ECB should not be used for ordinary data. CBC chains blocks so that each plaintext block depends on the previous ciphertext block. It requires an unpredictable or suitably unique IV, padding for many data formats, and separate integrity protection. CBC implementations are vulnerable to padding-oracle attacks when error behavior reveals padding validity. CTR converts a block cipher into a stream-like construction by encrypting counters and XORing the result with plaintext. Counter values must never repeat under the same key. CTR does not provide integrity. The security limitations of these modes illustrate a central principle: confidentiality does not imply authenticity. An attacker may alter unauthenticated ciphertext, and the receiver may be unable to detect the change. Authenticated EncryptionAuthenticated encryption with associated data (AEAD) provides confidentiality and integrity for plaintext while also authenticating unencrypted metadata. Abstractly: (C, T) = EncK(N, P, A) P = DecK(N, C, T, A) \quad \text{or rejection} K is the key, N the nonce, P the plaintext, A associated data, C ciphertext and T the authentication tag. Decryption must reject invalid tags before releasing plaintext to the application. A typical AEAD design is AES-GCM; another is ChaCha20-Poly1305. Nonce uniqueness is a critical operational condition. In GCM, accidental nonce reuse can seriously damage both confidentiality and authentication. A robust design uses a sufficiently large nonce space, a counter or a carefully engineered allocation scheme, and prevents resets that repeat a nonce under the same key. A random nonce is not automatically safe if the probability of collision is material; uniqueness-based designs often use counters, while randomised designs require collision analysis. Associated data is authenticated but not encrypted. Examples include a protocol version, record number, sender identifier or blockchain network identifier. It must be supplied identically during decryption. AEAD does not authenticate data omitted from both the ciphertext and associated-data inputs. Key SeparationDifferent purposes should use different keys. For example, encryption, MAC, database authentication and key wrapping should not all use one secret. Keys can be derived from a master secret using a standard key-derivation function (KDF), with distinct context labels. This limits the consequences of a compromise and avoids cross-protocol attacks. 4. Cryptographic Hash FunctionsA cryptographic hash function maps an input of arbitrary practical length to a fixed-length digest: h = H(M) A secure hash is designed to provide: - Preimage resistance: given h, it should be computationally infeasible to find M such that H(M) = h.
- Second-preimage resistance: given M, it should be infeasible to find M′ ≠ M with H(M′) = H(M).
- Collision resistance: it should be infeasible to find any distinct M and M′ with equal digests.
For an ideal n-bit hash, generic collision search requires approximately 2n/2 evaluations because of the birthday effect, whereas generic preimage search requires approximately 2n. These are estimates for idealised attacks, not guarantees for every design or implementation. SHA-256 produces a 256-bit digest. Its hexadecimal representation contains 64 characters because each hexadecimal character represents four bits. A digest is not encryption: it is not designed to be reversible, and it does not conceal a low-entropy password from guessing. Hashes in Blockchain SystemsBlockchains use hashes for transaction identifiers, block-header commitments, Merkle trees and proof-of-work systems. A Merkle tree compresses many transaction hashes into one root. Changing a transaction changes its leaf hash and, normally, every hash on the path to the root. A verifier can check inclusion using a logarithmic number of sibling hashes relative to the number of leaves, although the exact path structure depends on the tree construction. Hashing does not by itself prove who created data. Anyone can calculate a hash. Authenticity requires a MAC, digital signature or another trusted mechanism. 5. Message Authentication CodesA MAC is a keyed function that produces a tag: T = MACK(M) A verifier recomputes the tag using K and accepts only if the received tag matches. The comparison should be performed in constant time where practical, reducing timing leakage from early termination. MACs provide integrity and authentication to parties sharing K, but not public verifiability or non-repudiation. HMAC is a widely used construction based on a hash function. For a hash with block size b, key K is normalised to a block-sized value K′, and: HMACK(M) = H((K′ ⊕ opad) ∥ H((K′ ⊕ ipad) ∥ M)) Here H is the hash function, ∥ denotes concatenation, ipad and opad are fixed inner and outer padding constants, and ⊕ denotes XOR. HMAC-SHA-256 is a standard choice. The formula applies to the specified HMAC construction; it is not a recommendation to invent a different keyed-hash format. A MAC must cover all security-relevant fields, including algorithm identifiers, versions, sequence numbers and context. Short tags increase the probability of successful forgery; the acceptable tag length depends on the protocol’s threat model and standards. 6. Password Hashing and SaltingPasswords are usually low-entropy human choices. Storing them with SHA-256 alone is unsafe because attackers can test huge numbers of guesses rapidly, especially using GPUs. Password storage should use a dedicated, memory-hard password hashing function such as Argon2id, scrypt or, where appropriate, bcrypt. A password system stores a record containing a salt, algorithm parameters and a derived value: D = KDF(password, salt, parameters) A salt is a unique, non-secret random value generated for each password record. It prevents identical passwords from producing identical stored values and defeats precomputed rainbow tables. A salt does not make a weak password strong and need not be encrypted. A password KDF deliberately increases guessing cost through time, memory and, in some designs, parallelism. Parameters should be selected through benchmarking on the actual service infrastructure, then reviewed as hardware improves. Verification should use the stored salt and parameters, and comparisons should avoid unnecessary timing leakage. A pepper is an additional secret held separately from the password database, often in a hardware security module or protected secret store. It can add defence in depth, but it introduces key-management and recovery requirements. Password hashing is distinct from key derivation for high-entropy cryptographic keys, although related KDF families may serve different purposes. 7. Secure RandomnessCryptography requires unpredictable keys, nonces where random generation is selected, salts and challenge values. A cryptographically secure pseudorandom number generator (CSPRNG) is seeded from an operating-system entropy source and expands internal state into unpredictable output. General-purpose pseudo-random functions used for simulation, games or statistical sampling are not suitable for key generation. Important practices include: - use the operating system or a vetted cryptographic library’s CSPRNG;
- never seed a generator with time alone;
- check library errors and entropy-source failures;
- generate keys and salts directly with approved APIs;
- avoid logging secrets, seeds or raw random output;
- protect and rotate long-lived keys according to a documented policy.
Randomness failures can be catastrophic. Predictable wallet keys, repeated nonces or duplicated salts may expose assets or enable forgery. In blockchain applications, care is also needed when generating validator, wallet or protocol randomness: public block data may be manipulable or predictable and should not automatically be treated as a secure random source. 8. Illustrative Case: Protecting a Blockchain Payment GatewayBackgroundA payment gateway receives blockchain payment notifications and stores customer account information. Its first design encrypts database fields with AES-CTR, stores passwords as SHA-256 digests, and uses a single application-wide key. ProblemSecurity testing discovers that the same CTR nonce is reused after service restarts. The system has no authentication tag, so altered ciphertext may be accepted. Password guesses can be tested rapidly, and the single key creates a large blast radius. AnalysisCTR nonce reuse exposes relationships between plaintexts. The absence of authentication permits undetected modification. SHA-256 is not an adequate password-storage KDF. A shared key used for every purpose prevents effective isolation and complicates rotation. Approach and SolutionThe gateway replaces CTR with AES-GCM or ChaCha20-Poly1305. It allocates unique nonces per key and authenticates record identifiers, schema versions and tenant identifiers as associated data. Decryption rejects invalid tags before returning plaintext. Passwords are migrated to Argon2id with a unique random salt and calibrated memory, time and parallelism parameters. Separate keys are derived or provisioned for encryption and other services, with key versions included in records and keys protected by a key-management service. The migration uses a safe sequence: verify an old password using the legacy method, immediately rehash it with the new KDF, and disable the legacy path after a defined transition period. Existing encrypted records are re-encrypted under the new AEAD scheme, with integrity checked during migration. OutcomeThe redesigned system detects tampering, reduces password-guessing efficiency, prevents nonce reuse through explicit allocation, and limits compromise through key separation. Operational monitoring records authentication failures and key-version use without exposing secrets. Learning PointsThe case demonstrates that algorithm selection alone is insufficient. Security depends on mode parameters, nonce lifecycle, authentication, password-specific processing, key management and controlled migration. 9. Limitations, Governance and Professional PracticeNo primitive compensates for compromised endpoints, stolen keys or poor access control. Encryption can also create availability and recovery challenges: lost keys may make data permanently unrecoverable. Organisations should document ownership, backup, rotation, revocation, retention and destruction procedures. Use approved standards and maintained libraries rather than implementing AES, GCM, ChaCha20, HMAC or Argon2 independently. Security reviews should examine threat models, parameter choices, nonce allocation, error handling, side channels, logging and test coverage. Cryptographic failures should be treated as governance risks because they can affect privacy legislation, financial obligations and audit evidence. AI-assisted code generation can produce insecure nonce handling, obsolete algorithms or incorrect cryptographic composition. Generated code must therefore undergo expert review, testing and dependency analysis. AI tools should not receive production keys, passwords or confidential plaintexts. Contemporary practice increasingly favours AEAD by default, memory-hard password hashing, hardware-backed key storage, automated key rotation and formally analysed protocols. Post-quantum cryptography mainly affects public-key mechanisms; it does not remove the need for correct symmetric encryption, hashing, authentication or randomness. Grover-style quantum search motivates conservative symmetric-key sizing, but implementation correctness remains the immediate engineering priority. Chapter SummarySymmetric encryption provides efficient confidentiality but requires correct key management and a safe mode of operation. Block ciphers process fixed-size blocks, while stream ciphers generate keystreams; neither provides integrity automatically. ECB is unsuitable for ordinary confidential data, and CTR or stream-cipher keystreams must never be reused with the same key. AEAD schemes such as AES-GCM and ChaCha20-Poly1305 combine confidentiality with integrity and can authenticate associated data, provided nonce rules are obeyed. Cryptographic hashes provide fixed-length, one-way digests and support commitments and Merkle trees, but they do not authenticate data or safely store ordinary passwords. MACs authenticate messages for parties sharing a secret, while HMAC supplies a standard keyed-hash construction. Passwords require salted, deliberately expensive KDFs such as Argon2id. Secure randomness, key separation, lifecycle management, constant-time verification and vetted libraries are essential parts of a complete security design. Key TermsSymmetric encryption: Encryption using a shared secret key. Block cipher: A cipher operating on fixed-size blocks. Stream cipher: A cipher combining plaintext with a generated keystream. Nonce: A value intended for controlled, usually single, use with a key. Initialization vector: A mode-specific starting value. AEAD: Authenticated encryption with associated data. Authentication tag: Data used to verify integrity and authenticity. Cryptographic hash: A fixed-length digest function designed to resist specified attacks. Preimage resistance: Difficulty of finding an input for a given digest. Collision resistance: Difficulty of finding two inputs with the same digest. MAC: A keyed message authentication code. HMAC: A standard hash-based MAC construction. Salt: A unique, non-secret random value used in password hashing. Pepper: An additional secret applied to password protection. KDF: A key-derivation function. CSPRNG: A cryptographically secure pseudorandom number generator. Key separation: Using distinct keys for distinct purposes. Associated data: Unencrypted data authenticated by an AEAD scheme. Merkle tree: A hash tree committing to a collection of data. Review QuestionsShort Answer Questions- Why is confidentiality alone insufficient for a blockchain payment message?
- Explain the difference between a nonce and a password salt.
- State the three principal resistance properties expected from a cryptographic hash.
- Why should passwords not normally be stored using SHA-256 alone?
- What does associated data mean in an AEAD scheme?
Long Answer Questions- Compare block ciphers and stream ciphers, including their principal operational risks.
- Explain how AEAD improves on unauthenticated encryption and discuss nonce management.
- Describe HMAC, its security purpose and the meaning of each major component in its construction.
- Design a secure password-storage process for a blockchain application.
- Explain how hashes and Merkle trees support blockchain data integrity without providing authentication by themselves.
Analytical / Application Questions- A service encrypts two records with AES-CTR under one key and accidentally reuses the same counter value. Analyse what an attacker can learn and recommend a redesign.
- A wallet platform uses one secret for encryption, password verification and API authentication. Evaluate the risks and propose a key-separation strategy.
- During a security audit, a system uses random salts but a fast unsalted-style password digest computation with no memory cost. Assess the design and specify a migration plan.
Multiple Choice Questions with AnswersQuestion 1Which property is provided directly by a cryptographic hash function? A. Confidentiality of the original message B. Resistance to finding practical collisions C. Proof of the sender’s identity D. Recovery of the original plaintext Correct Answer: B. Resistance to finding practical collisions Question 2What is the most serious consequence of reusing a stream-cipher keystream with two plaintexts? A. The key becomes publicly visible immediately B. The ciphertexts reveal the XOR of the plaintexts C. The plaintexts are automatically compressed D. The nonce becomes a password salt Correct Answer: B. The ciphertexts reveal the XOR of the plaintexts Question 3Which construction provides confidentiality and integrity together? A. ECB mode B. Plain SHA-256 C. AES-GCM D. A random salt Correct Answer: C. AES-GCM Question 4What is the primary purpose of a password salt? A. To make the password recoverable B. To provide encryption for the database C. To prevent identical passwords from producing identical stored values D. To replace the password KDF Correct Answer: C. To prevent identical passwords from producing identical stored values Question 5For an ideal n-bit hash, generic collision search requires approximately how many evaluations? A. 2n B. n2 C. 2n/2 D. n/2 Correct Answer: C. 2n/2 Question 6What does a MAC primarily provide? A. Publicly verifiable non-repudiation B. Integrity and authentication for parties sharing a secret C. Compression of the message D. Password recovery Correct Answer: B. Integrity and authentication for parties sharing a secret Question 7Which practice is appropriate for password storage? A. Using a fast unsalted hash B. Using Argon2id with a unique salt C. Encrypting every password with one public key D. Using the current time as the only salt Correct Answer: B. Using Argon2id with a unique salt Question 8In AEAD, associated data is normally: A. Encrypted but not authenticated B. Authenticated but not encrypted C. Neither encrypted nor authenticated D. Used only to generate passwords Correct Answer: B. Authenticated but not encrypted Question 9What is the main reason to use key separation? A. To make all protocols share one secret B. To reduce the consequences of compromise and prevent cross-purpose misuse C. To eliminate the need for nonces D. To make hashes reversible Correct Answer: B. To reduce the consequences of compromise and prevent cross-purpose misuse Question 10Which source is suitable for generating cryptographic keys? A. A general-purpose game random-number function B. The current system time alone C. An operating-system CSPRNG accessed through a vetted library D. A predictable counter reused across devices Correct Answer: C. An operating-system CSPRNG accessed through a vetted library
|