Encryption and Decryption and Hash Functions

·

In the world of digital security, understanding encryption, decryption, and hash functions is essential for developers, system architects, and anyone involved in data integrity and secure communications. These cryptographic tools form the backbone of modern cybersecurity practices — from password storage to secure file transfers and authentication protocols.

This comprehensive guide explores the core functionalities provided by the crypto module, focusing on symmetric encryption, hashing algorithms (MD5, SHA series), HMAC generation, checksums, Base64 encoding, and more. Whether you're working on embedded systems or cloud-based applications, these functions are critical for ensuring data confidentiality and authenticity.


Understanding Hash Functions

Hash functions transform input data of any size into a fixed-length string of characters. They are widely used to verify data integrity and securely store passwords.

MD5, SHA1, SHA256, and SHA512

The crypto module supports several widely adopted hashing algorithms:

Each returns a hexadecimal string representing the hash.

👉 Discover how secure hashing boosts your application’s data integrity

For example:

log.info("sha256", crypto.sha256("hello world"))

This computes the SHA-256 hash of "hello world" and logs it as a hex string.

These functions are ideal for verifying file integrity or generating unique identifiers for data blocks.


HMAC: Adding Keys to Hashing

While standard hashes ensure integrity, they don’t provide authentication. That’s where HMAC (Hash-based Message Authentication Code) comes in.

HMAC combines a cryptographic hash function with a secret key, ensuring both data integrity and authenticity.

Supported HMAC functions include:

Example:

log.info("hmac_sha256", crypto.hmac_sha256("message", "secret_key"))

This ensures that only parties with the correct key can validate the message — crucial for API security and session verification.


Stream-Based Hashing for Large Data

When dealing with large files or streaming data, loading everything into memory isn't feasible. The crypto module provides a streaming interface:

  1. crypto.hash_init(type, [hmac]) – Initializes a hash context.
  2. crypto.hash_update(stream, data) – Feeds chunks of data into the stream.
  3. crypto.hash_finish(stream) – Finalizes the computation and returns the result.

Use case:

local stream = crypto.hash_init("SHA256", "my_secret")
crypto.hash_update(stream, "part1")
crypto.hash_update(stream, "part2")
local result = crypto.hash_finish(stream)

This approach is perfect for processing large files or real-time data streams without memory overload.


File Hashing Made Simple

You can compute the hash of an entire file directly using:

It supports MD5, SHA1, and SHA256 hashing on files stored locally (e.g., /luadb/logo.jpg).

Example:

log.info("file_md5", crypto.md_file("MD5", "/luadb/config.bin"))

This is invaluable for firmware updates, digital forensics, or detecting unauthorized file changes.


Symmetric Encryption with AES

Data confidentiality is achieved through encryption. The crypto.cipher_encrypt() and crypto.cipher_decrypt() functions enable strong symmetric encryption using algorithms like AES.

Key Parameters:

Encryption example:

local encrypted = crypto.cipher_encrypt("AES-128-CBC", "PKCS7", "sensitive_data", "16bytekey123456", "16byteiv12345678")

Decryption:

local decrypted = crypto.cipher_decrypt("AES-128-CBC", "PKCS7", encrypted, "16bytekey123456", "16byteiv12345678")

👉 Learn how advanced encryption protects user data across platforms

Always avoid ECB mode for sensitive data due to its vulnerability to pattern analysis.


Checksums and CRC Calculations

For lightweight error detection in communication protocols or embedded systems, checksums and CRCs are faster alternatives to full cryptographic hashes.

Available functions:

Useful in IoT devices, sensor networks, or serial communication where performance matters more than cryptographic strength.

Example:

local crc = crypto.crc16_modbus("data_string")

These help detect transmission errors efficiently.


Base64 Encoding & Decoding

Base64 is not encryption but encoding — used to represent binary data in ASCII format.

Functions:

Commonly used in email attachments, API payloads, and configuration files.

Example:

local encoded = crypto.base64_encode("Hello")
local decoded = crypto.base64_decode(encoded)

Note: These are equivalent to string.toBase64() and string.fromBase64().


Generate True Random Numbers

Security-critical operations require high-quality randomness. Use:

Example:

local random_bytes = crypto.trng(16) -- Generate 16-byte random string

Ideal for generating session tokens, salts, or cryptographic keys.


TOTP: Time-Based One-Time Passwords

Implement two-factor authentication (2FA) with:

Takes a Base32-encoded secret and generates a 6-digit code based on the current time.

Usage:

local otp = crypto.totp("JBSWY3DPEHPK3PXP")

Integrate this into login systems to enhance account security significantly.


Supported Algorithms Inquiry

To ensure compatibility across devices:

These help write portable code that adapts to different firmware versions.


Frequently Asked Questions (FAQ)

Q: What's the difference between hashing and encryption?
A: Hashing is a one-way function used to verify data integrity (e.g., passwords). Encryption is two-way — data can be decrypted back to its original form using a key.

Q: Which hash function should I use in 2025?
A: Prefer SHA-256 or higher. Avoid MD5 and SHA-1 in new systems due to known collision vulnerabilities.

Q: Can I use AES-ECB for sensitive data?
A: No. ECB mode lacks diffusion and reveals patterns. Use CBC or GCM modes instead with proper IVs.

Q: How do I securely store passwords?
A: Use salted hashes with dedicated algorithms like bcrypt or Argon2. While SHA-256 adds some protection, purpose-built KDFs are better.

Q: Is Base64 encoding secure?
A: No. It's easily reversible. Never rely on Base64 alone for protecting sensitive information.

Q: What does HMAC protect against?
A: HMAC prevents tampering and verifies that a message was sent by someone who knows the shared secret key — protecting against both modification and impersonation.


👉 Explore powerful tools that leverage encryption for next-gen app development

By mastering these cryptographic primitives — from hashing and HMACs to AES encryption and secure random generation — developers can build robust, secure systems resistant to common threats. Always follow best practices: use strong keys, avoid deprecated algorithms, and validate inputs rigorously.