Introduction to Encryption and Decryption
Encryption is the process of converting plain text (readable data) into cipher text (unreadable data) using an algorithm and a key. Its primary goal is to protect sensitive data from unauthorized access.
It is critical in software development because it helps protect data, ensure compliance, and build user trust.
Encryption is Used
- Data Security: Prevents unauthorized access.
- Confidentiality: Ensures only intended recipients can read the message.
- Integrity: Helps ensure data isn’t altered during transmission.
- Authentication: Verifies the identity of sender/receiver.
- Compliance: Many industries (finance, healthcare) require it by law.
When to Use Encryption
- Storing passwords, files, or sensitive information
- Transmitting data over the internet (e.g., HTTPS)
- Sending secure emails or messages
- Storing user credentials in applications
- Encrypting backups or cloud data
How Encryption Works
- Input (Plain Text):
"Hello World"
- Algorithm: AES, RSA, DES, etc.
- Key: A secret (e.g., 128-bit key)
- Process: Algorithm uses the key to encrypt
- Output (Cipher Text):
"Xy$#92@!..."
To decrypt, the recipient uses a decryption key and the algorithm to turn it back into "Hello World"
.
Types of Encryption
Type |
Description |
Example Use |
Symmetric |
Same key for encryption/decryption |
File storage, backups |
Asymmetric |
Public/private key pair |
Secure email, HTTPS (TLS) |
Hashing |
One-way function cannot be decrypted |
Password storage |
When we use Encryption in a project.
Protecting Sensitive Data
-
User credentials (passwords, personal info)
-
Payment information (credit cards, UPI IDs)
-
Health records, financial data, etc.
Without encryption, this data is vulnerable to hackers.
Secure Communication
-
APIs, web applications, mobile apps, and microservices transmit data over networks.
-
Using encryption (like HTTPS/TLS) ensures data isn’t intercepted or tampered with in transit.
Authentication & Authorization
-
Encryption is used in tokens (e.g., JWT), cookies, and secure sessions to validate user identity and prevent tampering.
Data Integrity
Regulatory Compliance
-
Laws like GDPR, HIPAA, PCI-DSS require data encryption for legal compliance.
-
Failure to encrypt can result in. penalties, data breaches, and loss of reputation.
User Trust & Privacy
-
Users expect apps to safeguard their data.
-
Encryption shows a commitment to privacy and security, boosting trust and reliability.
Example
Scenario |
Without Encryption |
With Encryption |
Login form submission |
Password in plain text |
Password sent via encrypted HTTPS |
Storing user passwords |
Plain text in DB |
Hashed + salted with AES or bcrypt |
Saving confidential files |
Anyone can open |
Encrypted file only accessi |
When to Use What?
Use Case |
Use |
Secure user credentials |
Hashing with salt |
Encrypt files for storage |
Encryption |
Transfer image in JSON API |
Encoding (Base64) |
Verify file integrity |
Hashing |
Protect API communication |
Encryption (TLS/HTTPS) |
Difference between Encryption, Hashing, and Encoding
Feature |
Encryption |
Hashing |
Encoding |
Purpose |
Protect data confidentiality |
Ensure data integrity and verify identity |
Ensure data is in a readable/transmittable format |
Reversible |
Yes (with key) |
No (one-way function) |
Yes (using the same algorithm) |
>Uses a Key |
Yes (symmetric/asymmetric) |
No |
No |
Example Use |
Secure communication (HTTPS, emails) |
Password storage, digital signatures |
Data transmission (e.g., Base64 in URLs) |
Example Output |
Cipher Text |
Fixed-length hash |
Encoded string |
Security Focused? |
Yes |
Yes |
No (not for security) |
Plaintext
- Definition: The original readable data or message before encryption.
- Example:
"Hello, world!"
is plaintext before it's encrypted.
Ciphertext
- Definition: The encrypted version of the plaintext — unreadable without decryption.
- Example:
"A3F1B2C4D..."
might be ciphertext after encryption.
Key
- Definition: A secret value used in encryption and decryption processes.
- Types:
- Symmetric Key: Same key is used for both encryption and decryption.
- Asymmetric Key: Uses a key pair — one for encryption (public key) and one for decryption (private key).
- Example:
bXlTZWNyZXRLZXk=
(Base64 encoded string)
IV (Initialization Vector)
- Definition: A random or pseudo-random value used along with the key to ensure unique encryption even for the same plaintext.
- Purpose: Prevents patterns and adds randomness.
- Used In: Block ciphers (e.g., AES in CBC mode).
- Example:
0x4e5a6f82...
Algorithm
- Definition: A defined set of rules or steps for encryption and decryption.
- Examples
- AES (Advanced Encryption Standard) — Symmetric.
- RSA — Asymmetric.
- DES, Blowfish, ChaCha20 — Other encryption algorithms.
- Note: Security depends not only on the algorithm but also on key length and implementation.
Types of Encryption
Symmetric Encryption
- Definition: Uses one single key for both encryption and decryption.
- Key Point: Both the sender and receiver must share the same secret key securely.
- Advantages
- Faster than asymmetric encryption
- Suitable for encrypting large amounts of data
- Examples
- AES (Advanced Encryption Standard)
- DES (Data Encryption Standard)
- Blowfish, ChaCha20
Use Case: Encrypting files, database fields, and internal communication.
Asymmetric Encryption
- Definition: Uses a pair of keys — one public and one private.
- How It Works
- Data encrypted with the public key can only be decrypted with the private key, and vice versa.
- Advantages
- More secure for key exchange and digital signatures
- No need to share private key
- Examples
- RSA
- ECC (Elliptic Curve Cryptography)
- DSA (Digital Signature Algorithm)
Use Case: Secure email (PGP), HTTPS/SSL certificates, digital signatures.
Hashing (One-Way Encryption)
- Definition: Converts data into a fixed-length string (hash) using a one-way function — cannot be reversed.
- Key Point: Not encryption — no decryption is possible.
- Purpose
- Verify data integrity
- Password storage
- Examples
- SHA-256
- SHA-512
- MD5 (obsolete for security)
Use Case: Password hashing, digital fingerprints, file integrity verification.
Decryption
Decryption is the process of converting ciphertext (unreadable data) back into plaintext (readable form) using an algorithm and a key. It is the reverse of encryption and is used to retrieve the original message/data by an authorized recipient.
Just like encryption, decryption plays a critical role in secure communication, authentication, and data protection in modern software systems.
Decryption is Used
- Data Access: Converts encrypted data back to a readable format when needed.
- Secure Communication: Decodes encrypted messages from HTTPS, secure emails, or chat apps.
- User Authentication: Decrypts tokens (e.g., JWT) to verify identity and authorize access.
- Payment Processing: Retrieves original payment details from encrypted transaction data.
- Config Secrets: Decrypts API keys, DB passwords, or app secrets stored securely.
- Email Privacy: Reads emails encrypted using PGP or other public-key systems.
- Data Recovery: Restores encrypted backups and documents to their original form.
- Digital Signature Verification: Confirms authenticity and integrity of data using decrypted signature info.
- Compliance & Audits: Allows legal or regulatory access to encrypted records when required.
- Software Licensing: Decrypts license keys or tokens to validate application usage.
When to Use Decryption
- Accessing encrypted files or backups: When sensitive files need to be restored to readable form.
- Reading secure API or HTTP responses: To interpret data sent over HTTPS or other encrypted channels.
- Validating user identity: To decode encrypted authentication tokens (e.g., JWT, OAuth).
- Processing secure payments: To decrypt credit card data, UPI IDs, or encrypted payment tokens.
- Loading secure configuration: At app startup, decrypt secrets like API keys or DB passwords.
- Viewing encrypted emails or messages: When using PGP/S/MIME in secure communications.
- Verifying digital signatures: To check data authenticity by decrypting signature metadata.
- Decrypting logs or audit data: For legal access or troubleshooting encrypted system logs.
- Reversing encryption during data migration: When securely moving encrypted data between systems.
- Compliance-driven access: When required by laws like GDPR, HIPAA, or PCI-DSS.
How Decryption Works
- Input (Ciphertext): Xy$#92@!...
- Algorithm: AES, RSA, DES, etc.
- Key: Secret or private key (based on encryption type)
- Process: Algorithm uses the key to decrypt the data
- Output (Plain Text): Hello World
Scenario |
With Encryption |
With Decryption |
Login Token |
Encrypted JWT sent |
Decrypted to verify user identity |
API Response with Encrypted Payload |
JSON with cipher text |
Client decrypts to get meaningful data |
Encrypted Configuration File |
appsettings.sec.json |
Decrypted by application on runtime |
Encrypted Email (PGP) |
Public key encrypts email |
Recipient uses private key to decrypt message |
Encryption vs Decryption
Feature |
Encryption |
Decryption |
Purpose |
Convert plaintext to ciphertext |
Convert ciphertext back to plaintext |
Requires Key? |
Yes |
Yes |
Key Type |
Symmetric or Asymmetric |
Same as encryption counterpart |
Used In |
Sending secure data |
Receiving and processing secure data |
Example Algorithm |
AES, RSA, Blowfish |
AES, RSA, Blowfish (same as encryption) |
Output |
Ciphertext |
Original Plaintext |
Key Concepts Related to Decryption
1. Ciphertext
- Encrypted data that's unreadable without decryption.
2. Decryption Key
- Secret/private key used to decode encrypted data.
3. Algorithm
- Same algorithm must be used for both encryption and decryption.
4. Initialization Vector (IV)
- Used to ensure randomness and uniqueness. Must also be known or transferred securely for decryption.
5. Key Management
- Crucial for both encryption and decryption; loss of a key can result in data loss.
Symmetric Decryption
- Same key is used to encrypt and decrypt.
- Fast and efficient, but key sharing must be secure.
- Common in:
- Encrypted database fields
- File decryption
- Application configuration
Asymmetric Decryption
- Data encrypted with a public key is decrypted with a private key.
- More secure for communication and identity verification.
- Common in:
- Secure emails (PGP)
- HTTPS/TLS (SSL certificates)
- Digital signature validation
Not Decryptable: Hashing
- Hashing is a one-way function and cannot be decrypted.
- Instead, the original value is hashed again and compared with the stored hash.
C# Console Application that demonstrates:
- AES Symmetric Encryption & Decryption
- RSA Asymmetric Encryption & Decryption
- SHA-256 Hashing (One-Way)
// EncryptionDecryptionConsoleApp.cs
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
class EncryptionDecryptionConsoleApp
{
static void Main()
{
Console.WriteLine("--- Encryption & Decryption Console App ---\n");
string originalText = "Hello World!! \n" +
" Welcome to C# Corner \n " +
"Encryption & Decryption Article";
string aesKey = "1234567890123456"; // 16 characters = 128-bit key
string aesIV = "6543210987654321"; // 16 characters = 128-bit IV
// Symmetric AES Encryption
string encryptedAES = EncryptAES(originalText, aesKey, aesIV);
Console.WriteLine($"\n AES Encrypted:\n {encryptedAES}");
string decryptedAES = DecryptAES(encryptedAES, aesKey, aesIV);
Console.WriteLine($"\n AES Decrypted:\n {decryptedAES}\n");
// Asymmetric RSA Encryption/Decryption
using var rsa = RSA.Create(2048);
byte[] originalBytes = Encoding.UTF8.GetBytes(originalText);
byte[] encryptedRSA = rsa.Encrypt(originalBytes, RSAEncryptionPadding.OaepSHA256);
string encryptedRSAString = Convert.ToBase64String(encryptedRSA);
Console.WriteLine($"\n RSA Encrypted:\n {encryptedRSAString}");
byte[] decryptedRSA = rsa.Decrypt(encryptedRSA, RSAEncryptionPadding.OaepSHA256);
Console.WriteLine($"\n RSA Decrypted:\n {Encoding.UTF8.GetString(decryptedRSA)}\n");
// Hashing Example (SHA256)
string hashed = HashSHA256(originalText);
Console.WriteLine($"SHA-256 Hashed (one-way): {hashed}");
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
static string EncryptAES(string plainText, string key, string iv)
{
using Aes aes = Aes.Create();
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = Encoding.UTF8.GetBytes(iv);
using var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using var ms = new MemoryStream();
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
using (var sw = new StreamWriter(cs))
sw.Write(plainText);
return Convert.ToBase64String(ms.ToArray());
}
static string DecryptAES(string cipherText, string key, string iv)
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using Aes aes = Aes.Create();
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = Encoding.UTF8.GetBytes(iv);
using var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using var ms = new MemoryStream(cipherBytes);
using var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
using var sr = new StreamReader(cs);
return sr.ReadToEnd();
}
static string HashSHA256(string text)
{
using SHA256 sha256 = SHA256.Create();
byte[] bytes = Encoding.UTF8.GetBytes(text);
byte[] hash = sha256.ComputeHash(bytes);
return BitConverter.ToString(hash).Replace("-", "").ToLower();
}
}
Output
------------------------------
--- Encryption & Decryption Console App ---
AES Encrypted:
hVF5CJzPIU6cIVktU7nmt9+Sp6TI9OJbOV4UxuAlozRAgEzCEFh9FYNQBkDxxhsvGm3zEQev4oSc0VLFnIo8k716ncg1xDhdMwgpF50FZog=
AES Decrypted:
Hello World!!
Welcome to C# Corner
Encryption & Decryption Article
RSA Encrypted:
H27Ba8N1lNw6c8P80PNczMDoLUP56q3rMo9kbnL+9Je29Lx0PFkMjckQk5dnOyrkqgXL6GiKz7Cmzz30xevQLF6lVER9/UkblKZSkrPs8k33++4csLEo760yCXiqZfNIrfYNzRNx1crX8PqJYtOjEGi6dL/Dxuahtm4gjZ5EGhuZ/G8VJaTDir/Ixxj9Z54Ki7s0U8Oc/jqCXWr03klSlMhcXZjLt5B9l7Gn+9IgtUXcGCZNi/VuiUPbbB4ql5ANqqgA5lLla9SlLx1aa9p4b/7oag4WZZJZC3HhVeVzRcx25a+UMCsNzPOjzHTRIFbxDi8ukuUmVx81/fZlOfNmqg==
RSA Decrypted:
Hello World!!
Welcome to C# Corner
Encryption & Decryption Article
SHA-256 Hashed (one-way): 2b9a99da60ee437e2f663f0085fb1de5a13c43237a10af875e4bb35231552d50
In today’s digital world, encryption and decryption are no longer optional — they are essential building blocks of secure software and data protection. Whether you're safeguarding user credentials, securing communication between services, or ensuring compliance with data protection laws, understanding how to implement and apply encryption effectively is a must for every developer.
Security isn't just a feature — it's a responsibility. By integrating proper encryption and decryption techniques in your applications, you not only protect sensitive data but also build trust, achieve regulatory compliance, and ensure system reliability.
Thank you for taking the time to read this post. I hope it has provided you better understanding of encryption and decryption and empowers you to apply these techniques effectively in real-world projects.
Keep learning, keep practicing, and keep building secure software.