Cryptography Concepts and Safe Algorithms

Understand encryption, hashes, digital signatures, keys, and secure randomness, then learn how to choose vetted cryptographic libraries for real systems.

published: reading time: 13 min read author: Geek Workbench
Quick Summary

Cryptography tools answer different questions: encryption protects confidentiality, hashes fingerprint data, and MACs or signatures help verify integrity and authenticity. This guide compares key types, randomness, nonces, password storage, and safe algorithm choices, with examples of common failure modes. Use it to select maintained library APIs for each job and plan key handling without inventing a protocol.

Cryptography Concepts and Safe Algorithms

Introduction

Cryptography helps software protect data and check who sent it. It is easy to mix up the tools: encryption hides data, a hash summarizes it, and a digital signature helps verify a message and its signer. None of these replaces access control, secure key handling, or a clear threat model.

This guide introduces the main concepts and shows how to reason about choosing them. If you are working through confidentiality and integrity, these ideas connect those goals to concrete tools.

Encryption, Hashing, and Signatures

The easiest way to keep these tools straight is to ask what question each one answers:

Operation What it does Key use Typical use
Encryption Turns readable plaintext into ciphertext that can later be recovered Secret key or public/private key system Protect a file, database field, or network message
Hashing Maps input to a fixed-length digest; it is designed to be one-way No key for a plain hash Identify content, detect changes when the expected digest is trusted
MAC Produces a tag that verifies data and possession of a shared secret Shared secret Authenticate messages between services that share a key
Digital signature Signs data so a matching public key can verify it Private signing key and public verification key Verify software releases, documents, or signed protocol messages

A plain hash does not authenticate data. If an attacker can replace both a file and its published hash, the pair still matches. A MAC or signature lets a verifier detect changes by checking a secret or a trusted public key.

For a public software release, a developer might calculate a SHA-256 digest with a standard library and compare it with a digest obtained through a separately trusted channel:

import hashlib

artifact = open("release.tar", "rb").read()
digest = hashlib.sha256(artifact).hexdigest()
print(digest)

This example fingerprints bytes; it does not prove who published them. The expected digest must itself come from a trusted source. For large files, use a streaming file API instead of reading the whole file into memory.

Password storage is a special case. Do not encrypt passwords for later recovery or store SHA-256(password). Use a password-hashing function designed to make guessing expensive, such as Argon2id, through a maintained framework or password library. The OWASP Password Storage Cheat Sheet explains salts and work factors.

Symmetric and Asymmetric Keys

Symmetric cryptography uses the same secret key to encrypt and decrypt, or to create and verify a MAC. It is efficient for large amounts of data. The hard part is getting the key to the right parties and keeping it out of everyone else’s hands.

Asymmetric cryptography uses a related key pair. A public key can be shared; its corresponding private key must stay protected. Depending on the algorithm, the pair can support encryption or key agreement, signatures, or both within a protocol. A signature’s public key needs a trustworthy link to the claimed person or service. A bare public key proves only that the signer held the matching private key.

Protocols often combine the two approaches: asymmetric operations establish or authenticate a session, then a fresh symmetric key protects the data. This is one of the ideas behind TLS and HTTPS. Application developers should generally use a complete, maintained protocol implementation rather than assembling those steps themselves.

flowchart LR
    A[Choose the security goal] --> B{Need to hide data?}
    B -->|Yes| C[Authenticated encryption]
    B -->|No| D{Need to detect changes?}
    D -->|Shared secret| E[MAC]
    D -->|Public verification| F[Digital signature]
    C --> G[Protect and manage keys]
    E --> G
    F --> H[Bind public key to trusted identity]

Randomness, Nonces, and Keys

Secure systems need unpredictable secret keys and, for many encryption schemes, nonces or initialization vectors. Use the operating system’s cryptographic random-number generator through a trusted library. A simulation or ordinary pseudo-random generator may repeat or expose patterns; it is fine for shuffling a demo deck, but not for generating a key, reset token, or session secret.

Some algorithms require a nonce to be unique for each encryption under a given key. A nonce usually does not need to be secret, but accidentally reusing one can break security badly. Let the chosen library generate or manage nonces as its documented API requires; store the nonce alongside ciphertext when needed. Never invent a nonce rule from a sample snippet without understanding its limits.

Keys need a lifecycle: generate them securely, restrict who can use them, rotate or revoke them when needed, and retain old keys only as long as data recovery or verification requires. Keep keys separate from the encrypted data where practical. A code repository, log file, or client-side bundle is not a key vault. The OWASP Cryptographic Storage Cheat Sheet and NIST key-management guidance cover these operational concerns.

Choosing Algorithms and Libraries

There is no universal “best algorithm” independent of the job, protocol, platform, and policy. Start with the threat model and use the highest-level standard feature that meets it. For new application encryption, look for a maintained library API for authenticated encryption (AEAD), such as AES-GCM or ChaCha20-Poly1305 where supported and appropriate. For general-purpose hashing, SHA-256 or SHA-3 are common choices; for password storage, choose a password KDF rather than a fast general-purpose hash. Use signatures only when the design needs public verification.

Before choosing, check that the algorithm and mode are supported by current standards and organizational requirements, the library is maintained and reviewed, key sizes and parameters follow its guidance, and your deployment can store and rotate keys safely. Regulatory requirements can impose approved modules or configurations, so verify the current rules for your environment. If a framework already provides password storage, TLS, or encrypted storage, prefer that integration over a low-level cryptographic API.

For example, a service that stores a private API token needs confidentiality and tamper detection. A high-level AEAD API is appropriate; a bare hash is not, because the service must recover the token. A service comparing downloaded public files may use a trusted digest for integrity checks. A software publisher can sign release metadata so users can verify it with a public key distributed through a trusted channel.

Do not invent a cipher, hash function, key format, or protocol. Cryptographic failures often come from the parts around an algorithm: nonce reuse, unauthenticated ciphertext, weak password handling, leaked keys, or incorrect verification. A vetted library reduces the amount of sensitive machinery your application must get right. It cannot fix a poor design or unsafe key storage, so understand the API contract and follow its documentation.

When to Use

  • Use encryption when an attacker might access stored or transmitted data but should not read it.
  • Use authenticated encryption when you need both confidentiality and tamper detection for data protected with a shared key.
  • Use a MAC when parties share a secret and need to authenticate messages without public verification.
  • Use digital signatures when recipients need to verify content with a public key, such as signed releases or protocol messages.
  • Use a password-hashing function when storing passwords; use a general-purpose hash only for tasks it is designed to serve.
  • Prefer an established protocol such as HTTPS/TLS for network connections instead of designing a custom handshake.

Production Failure Scenarios

Failure What goes wrong Safer response
Nonce reused with an AEAD key Confidentiality or integrity guarantees can fail, depending on the scheme Follow the library’s nonce requirements and key rotation guidance; monitor for generation errors
Ciphertext is encrypted without authentication An attacker may modify data without detection Use AEAD or a correctly designed encrypt-then-MAC construction from a vetted API
Key is stored beside a database backup One stolen copy may contain both ciphertext and its decryption key Separate key management from data storage and limit key access
Passwords use a fast hash such as SHA-256 Attackers can test guesses quickly after a database leak Use a dedicated password KDF with per-password salt and an appropriate work factor
Signature verification checks the signature but not the signer key A valid signature from an attacker’s key may be accepted Validate the public-key identity, certificate chain, or trusted-key policy too
Crypto failures are logged with secrets Logs become another source of credential or plaintext exposure Record operation outcomes and key identifiers, never keys, plaintext, or sensitive tokens

Trade-Off Table

Choice Strength Cost or limitation Good fit
Symmetric encryption Fast for bulk data Secure key distribution and storage are required Files, database fields, backups
Public-key cryptography Supports key agreement or public verification without sharing one secret with every verifier Slower and requires identity/key validation Protocol setup, signatures, software release verification
AEAD Encryption and integrity checks in one operation Nonce and key-use rules must be followed exactly Most application data encryption
Plain hash Simple content fingerprint with no secret key Does not authenticate data if an attacker can replace the expected digest Deduplication, checksums from a trusted channel
Password KDF Makes offline password guessing more expensive Deliberately costs time and memory per verification Password storage

Observability Checklist

  • Track encryption, decryption, MAC, and signature verification failures as security events.
  • Record algorithm or key version identifiers when useful for rotation and incident response.
  • Alert on unexpected key-version use, repeated verification failures, or access outside normal service patterns.
  • Ensure logs omit plaintext, passwords, private keys, secret keys, tokens, and full sensitive payloads.
  • Test key rotation and recovery procedures before production data depends on them.
  • Keep clock and certificate-validation failures visible for protocols that rely on certificates.

Security and Compliance Notes

Cryptographic algorithms have deployment rules, and approved configurations may differ by jurisdiction, sector, or contract. Check the policy that applies to the actual system; a familiar algorithm name alone does not establish compliance. Track library updates and deprecations, and plan how encrypted data can be migrated if a key or algorithm must be retired.

Encryption also has boundaries. Application code that can decrypt data may expose it to an attacker who compromises that application. Minimize sensitive data, restrict decryption access, and keep authorization checks in place. For wider context on how these controls fit together, see confidentiality, integrity, and availability.

Common Pitfalls / Anti-Patterns

  • Rolling your own crypto: use a vetted library’s high-level API instead of creating a custom algorithm or protocol.
  • Treating Base64 as encryption: Base64 is a reversible text encoding and provides no secrecy.
  • Using a hash as encryption: hashes are not designed to recover the input.
  • Using a plain hash as proof of origin: an attacker who can change the data may also replace an untrusted digest.
  • Encrypting without authentication: use an authenticated mode or another established integrity mechanism.
  • Reusing keys or nonces carelessly: follow the library’s documented limits and rotation guidance.
  • Hard-coding keys: keep secrets out of source control, client bundles, logs, and examples that might be copied into production.
  • Assuming encryption solves access control: check who may request decryption and what data they may access.

Quick Recap Checklist

  • State whether you need confidentiality, integrity, authenticity, or a combination.
  • Choose encryption, hashing, a MAC, a signature, or a password KDF for that specific job.
  • Prefer authenticated encryption for ordinary application data encryption.
  • Generate keys and security-sensitive random values with a cryptographic random source.
  • Follow the library’s nonce, key size, and rotation rules.
  • Store keys separately from protected data where practical, and restrict their use.
  • Use maintained libraries and standard protocols; do not invent cryptography.
  • Test verification failures, key rotation, and recovery paths.

Interview Questions

1. How does hashing differ from encryption?

Encryption is reversible with the appropriate key and is used to protect confidentiality. A cryptographic hash creates a fixed-length digest and is designed to be one-way. A plain hash does not prove who created the data; use a MAC or digital signature when authenticity is required.

2. What does authenticated encryption add?

Authenticated encryption with associated data (AEAD) protects ciphertext confidentiality and detects unauthorized changes. The recipient must reject a message if tag verification fails. It does not decide whether the authenticated sender is authorized to perform an action.

3. Why do encryption schemes use nonces?

A nonce helps ensure that repeated encryption under a key does not reuse the same cryptographic input in unsafe ways. Depending on the scheme, it may need to be unique for each use with that key. Follow the library's exact generation and storage requirements; a nonce is generally public, but it is not optional metadata.

4. Why should application teams avoid implementing their own cryptography?

Security depends on subtle details such as key generation, nonce rules, padding, authentication, and error handling. A reviewed library implements those mechanisms and receives maintenance as weaknesses are found. Teams still need to choose the right high-level operation, protect keys, and follow the library's documented API.

Further Reading

Conclusion

The algorithm’s name cannot rescue a design with leaked keys, reused nonces, or skipped signature checks. Match the operation to the protection you need, let a maintained library handle the cryptographic mechanics, and give the same care to key storage and verification.

Category

Related Posts

Password Hashing and Message Integrity

Learn why passwords need slow, salted hashes, how SHA-256 differs from a keyed MAC, and how to verify credentials and data safely.

#cybersecurity #cryptography #password-security

Public-Key Infrastructure and Certificates

Learn how public-key infrastructure uses certificates and trusted authorities to verify names, support TLS, and avoid common renewal and revocation failures.

#cybersecurity #pki #certificates

Access Control Models and Least Privilege

Learn how DAC, MAC, RBAC, and ABAC control access, how least privilege limits damage, and how to review human and service permissions safely.

#cybersecurity #access-control #least-privilege