Cryptography: symmetric and asymmetric encryption, hashing, TLS
Four basic tools
| Tool | What it is for | Key | Examples |
|---|---|---|---|
| Symmetric encryption | confidentiality of large data | one shared, secret | AES-GCM, ChaCha20-Poly1305 |
| Asymmetric encryption | key exchange, confidentiality of short data | a pair: public and private | RSA, ECDH |
| Digital signature | authenticity and integrity, non-repudiation | the private key signs, the public key verifies | RSA-PSS, ECDSA, Ed25519 |
| Hash / HMAC | a digest of data, integrity checks, passwords | none (hash) or secret (HMAC) | SHA-256, HMAC-SHA256, PBKDF2, Argon2 |
Symmetric encryption
The same key encrypts and decrypts:
tekst jawny --[ klucz K ]--> szyfrogram --[ ten sam klucz K ]--> tekst jawny
- Algorithms: AES (128/192/256-bit keys), ChaCha20. DES and 3DES are obsolete.
- Advantages: very fast (hardware AES-NI), suitable for large data: files, disks, network traffic.
- Disadvantage: the key distribution problem - both sides must know the same secret and it has to be passed on securely somehow.
- Modes of operation: AES encrypts a single 16 B block, and the mode decides how to combine the blocks. ECB is dangerous (identical blocks give identical ciphertexts and patterns are visible). Use AES-GCM (it encrypts and at the same time detects modification, so-called AEAD) or CBC with a separate HMAC.
- A critical rule: never use the same nonce with the same key twice in GCM - it breaks security.
Asymmetric encryption
The keys work as a pair: what you encrypt with one, you can decrypt only with the other. The private key can't practically be computed from the public one (RSA relies on the difficulty of factoring large numbers, ECC on the discrete logarithm problem on elliptic curves).
Two uses that are easy to confuse:
- Confidentiality: you encrypt with the recipient's public key, and only the owner of the private key can decrypt.
-
Digital signature: you sign with your own private key, and everyone checks the signature with your public key. This proves that the document comes from you and hasn't been altered.
-
Advantages: no key distribution problem (the public key can be shared), enables signatures and certificates.
- Disadvantages: slow (hundreds of times slower than AES), RSA encrypts only short data, the keys are long. AES-128, RSA-3072 and ECC P-256 give similar strength, so ECC is much shorter and faster than RSA.
Comparison
| Symmetric | Asymmetric | |
|---|---|---|
| Keys | one shared, secret | a pair: public and private |
| Speed | very fast | slow |
| Data size | any | small (practically keys, digests) |
| Key distribution | a problem | solved (the public key is open) |
| Digital signature | no | yes |
| Typical use | data, disks, traffic | key exchange, signatures, certificates |
Hybrid encryption - this is how it's done in practice
Asymmetric solves the key exchange, symmetric encrypts the data. This is how HTTPS (TLS) and encrypted email (PGP, S/MIME) work: the content goes through AES, and the AES key is negotiated or encrypted with the recipient's public key.
Key agreement in TLS
Goal: the client and server must arrive at a shared, secret symmetric key, even though they talk over a network that someone may be eavesdropping on. The key is never sent anywhere - each side computes it itself.
The idea: Diffie-Hellman (DH / ECDHE)
Each side picks a temporary secret and sends only its "image" (a public value). From its own secret and the other side's public value, both arrive at the same number. An example with small numbers (public: p = 23, g = 5):
| Client | Server | |
|---|---|---|
| picks a secret | a = 6 | b = 15 |
| sends a public value | A = 5^6 mod 23 = 8 | B = 5^15 mod 23 = 19 |
| computes the shared secret | B^a mod 23 = 19^6 mod 23 = 2 | A^b mod 23 = 8^15 mod 23 = 2 |
An eavesdropper sees 23, 5, 8 and 19, but without a or b can't compute 2. With real, enormous numbers (or points on an elliptic curve, hence ECDHE, e.g. the X25519 and P-256 curves), computing the secret from the public values alone is practically infeasible.
The TLS 1.3 handshake flow
- ClientHello - the client sends the ciphers it supports, a random value and immediately its ECDHE public value (
key_share). - ServerHello - the server picks a cipher (e.g.
TLS_AES_256_GCM_SHA384) and sends back its ECDHE public value. Both sides can now compute the shared secret. - From the secret and a hash of the conversation so far, the HKDF function derives the symmetric keys. From this moment the rest of the handshake is already encrypted.
- Certificate - the server sends its certificate (a chain up to a trusted CA).
- CertificateVerify - the server signs a hash of the whole conversation with its private key, and the client verifies the signature with the public key from the certificate.
- Finished - both sides send an authentication code (an HMAC) of the entire handshake, which confirms that nobody altered it.
- Application data follows, encrypted symmetrically (AES-GCM or ChaCha20-Poly1305).
The TLS 1.3 handshake takes one round trip (1-RTT). There is also a 0-RTT mode when resuming a session (faster, but with the risk of a request being replayed).
Why a certificate is indispensable
DH on its own doesn't authenticate anyone. A man-in-the-middle attacker (MITM) could agree one key with the client and another with the server and eavesdrop on both sides. That is why the server signs the handshake with its private key, and the client verifies the signature with the certificate of a trusted CA. Asymmetric cryptography plays two roles here: ECDHE creates the key, and the signature (RSA/ECDSA) proves the server's identity. More about certificates: Securing a Web API.
Forward secrecy
ECDHE keys are ephemeral - generated for one session and thrown away afterwards. Even if the server's private key leaks a year from now, previously recorded traffic can't be decrypted, because the session key did not derive from the long-term key.
The old way: TLS 1.2 with key exchange through RSA
The client generated a random pre-master secret and encrypted it with the server's RSA public key. It worked, but without forward secrecy: whoever recorded the traffic and later obtained the private key could decrypt everything. TLS 1.3 removed key exchange through RSA and left only (EC)DH.
Key agreement in TLS in brief (an answer for an interview)
In TLS 1.3 the client and server exchange ephemeral ECDHE public keys and each side computes from them the same shared secret, which nobody sent. From the secret HKDF derives symmetric keys for AES-GCM. The server proves its identity by signing the handshake with the private key from its certificate, and because the DH keys are ephemeral, the traffic retains forward secrecy.
Hashing, HMAC and passwords
- A hash (SHA-256) is a one-way function: the data yields a fixed-length digest, and the data can't be recovered from the digest. A small change in the data gives a completely different digest. It is used for integrity checks and as part of a signature.
- HMAC is a hash with a secret key: it proves that the message hasn't been altered and that someone who knows the key sent it (e.g. the JWT signature in the HS256 algorithm).
- Passwords: don't use plain SHA - it is too fast, so an attacker tries billions of guesses a second. Use a slow function with a salt: PBKDF2, bcrypt, scrypt or Argon2 (ASP.NET Identity uses PBKDF2 by default). A salt (random, unique per password) prevents rainbow-table attacks, and do the comparison in constant time (
CryptographicOperations.FixedTimeEquals).
A working example - CryptoDemo
A .NET 8 console application, with no extra packages (dotnet new console -n CryptoDemo, paste in Program.cs, dotnet run). It shows in turn: AES-GCM with modification detection, RSA (encryption and signature), Diffie-Hellman with small numbers (A=8, B=19, shared secret 2), ECDH with AES-GCM (hybrid encryption), ECDSA, and a hash, PBKDF2 and HMAC.
using System.Numerics;
using System.Security.Cryptography;
using System.Text;
static string Hex(byte[] data) => Convert.ToHexString(data)[..Math.Min(32, data.Length * 2)] + "...";
// ---------------------------------------------------------------
// 1. Symmetric encryption: AES-GCM (confidentiality + integrity)
// ---------------------------------------------------------------
Console.WriteLine("=== 1. AES-GCM (symmetric) ===");
byte[] key = RandomNumberGenerator.GetBytes(32); // 256-bit secret key
byte[] nonce = RandomNumberGenerator.GetBytes(AesGcm.NonceByteSizes.MaxSize); // 12 bytes, unique per message
byte[] plain = Encoding.UTF8.GetBytes("Top secret message");
byte[] cipher = new byte[plain.Length];
byte[] tag = new byte[AesGcm.TagByteSizes.MaxSize]; // 16 bytes
using (var aes = new AesGcm(key, tag.Length))
{
aes.Encrypt(nonce, plain, cipher, tag);
Console.WriteLine($"cipher: {Hex(cipher)}");
var decrypted = new byte[cipher.Length];
aes.Decrypt(nonce, cipher, tag, decrypted);
Console.WriteLine($"decrypted: {Encoding.UTF8.GetString(decrypted)}");
cipher[0] ^= 1; // an attacker flips one bit
try { aes.Decrypt(nonce, cipher, tag, new byte[cipher.Length]); }
catch (CryptographicException) { Console.WriteLine("tampered data detected (authentication tag mismatch)"); }
}
// ---------------------------------------------------------------
// 2. Asymmetric encryption and signature: RSA
// ---------------------------------------------------------------
Console.WriteLine("\n=== 2. RSA (asymmetric) ===");
using (var rsa = RSA.Create(2048))
{
byte[] data = Encoding.UTF8.GetBytes("short message");
// confidentiality: encrypt with the PUBLIC key, decrypt with the PRIVATE key
byte[] encrypted = rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA256);
byte[] decrypted = rsa.Decrypt(encrypted, RSAEncryptionPadding.OaepSHA256);
Console.WriteLine($"RSA decrypted: {Encoding.UTF8.GetString(decrypted)}");
// signature: sign with the PRIVATE key, verify with the PUBLIC key
byte[] signature = rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);
bool valid = rsa.VerifyData(data, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);
bool validAfterChange = rsa.VerifyData(Encoding.UTF8.GetBytes("other message"), signature,
HashAlgorithmName.SHA256, RSASignaturePadding.Pss);
Console.WriteLine($"signature valid: {valid}, after changing the message: {validAfterChange}");
}
// ---------------------------------------------------------------
// 3. Key agreement (what happens in the TLS handshake)
// ---------------------------------------------------------------
Console.WriteLine("\n=== 3a. Diffie-Hellman on small numbers ===");
BigInteger p = 23, g = 5;
BigInteger a = 6, b = 15; // private values (never sent)
BigInteger A = BigInteger.ModPow(g, a, p); // public value of the client = 8
BigInteger B = BigInteger.ModPow(g, b, p); // public value of the server = 19
Console.WriteLine($"A={A}, B={B}");
Console.WriteLine($"client secret = {BigInteger.ModPow(B, a, p)}, server secret = {BigInteger.ModPow(A, b, p)}");
Console.WriteLine("\n=== 3b. ECDH (P-256) + AES-GCM: hybrid encryption ===");
using var client = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256);
using var server = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256);
// each side combines ITS private key with the OTHER side's public key
byte[] clientKey = client.DeriveKeyFromHash(server.PublicKey, HashAlgorithmName.SHA256);
byte[] serverKey = server.DeriveKeyFromHash(client.PublicKey, HashAlgorithmName.SHA256);
Console.WriteLine($"both sides derived the same 256-bit key: {clientKey.SequenceEqual(serverKey)}");
byte[] n2 = RandomNumberGenerator.GetBytes(12);
byte[] msg = Encoding.UTF8.GetBytes("hello over the 'TLS' channel");
byte[] ct = new byte[msg.Length];
byte[] t2 = new byte[16];
using (var sender = new AesGcm(clientKey, 16)) sender.Encrypt(n2, msg, ct, t2);
var pt = new byte[ct.Length];
using (var receiver = new AesGcm(serverKey, 16)) receiver.Decrypt(n2, ct, t2, pt);
Console.WriteLine($"server read: {Encoding.UTF8.GetString(pt)}");
// ---------------------------------------------------------------
// 4. Digital signature with elliptic curves: ECDSA
// ---------------------------------------------------------------
Console.WriteLine("\n=== 4. ECDSA (signature) ===");
using (var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256))
{
byte[] document = Encoding.UTF8.GetBytes("Invoice #123, total 100 PLN");
byte[] sig = ecdsa.SignData(document, HashAlgorithmName.SHA256);
Console.WriteLine($"valid: {ecdsa.VerifyData(document, sig, HashAlgorithmName.SHA256)}");
}
// ---------------------------------------------------------------
// 5. Hashing and password storage
// ---------------------------------------------------------------
Console.WriteLine("\n=== 5. Hash and password hashing ===");
byte[] sha = SHA256.HashData(Encoding.UTF8.GetBytes("abc")); // one-way, fast: NOT for passwords
Console.WriteLine($"SHA-256(abc) = {Convert.ToHexString(sha)[..16]}...");
byte[] salt = RandomNumberGenerator.GetBytes(16); // unique per password
byte[] hash = Rfc2898DeriveBytes.Pbkdf2("MyPassword!", salt, 600_000, HashAlgorithmName.SHA256, 32); // slow on purpose
byte[] attempt = Rfc2898DeriveBytes.Pbkdf2("MyPassword!", salt, 600_000, HashAlgorithmName.SHA256, 32);
Console.WriteLine($"password matches: {CryptographicOperations.FixedTimeEquals(hash, attempt)}"); // constant-time compare
// HMAC: a hash with a secret key (integrity + authenticity of a message)
byte[] mac = HMACSHA256.HashData(key, Encoding.UTF8.GetBytes("message"));
Console.WriteLine($"HMAC = {Hex(mac)}");
If you prefer to have it in a single snippet, the most important are the three lines illustrating the hybrid: each side combines its own private key with the other's public key, and the AES key is created from the result:
byte[] clientKey = client.DeriveKeyFromHash(server.PublicKey, HashAlgorithmName.SHA256);
byte[] serverKey = server.DeriveKeyFromHash(client.PublicKey, HashAlgorithmName.SHA256);
// clientKey == serverKey, and the key itself never travelled over the network
The most common mistakes
- Hashing is not encryption - a digest can't be decrypted.
- Base64 is an encoding, not encryption.
- The public key can be disclosed, the private one never - keep it in Key Vault, an HSM or a certificate store, not in the repository.
- Rolling your own cryptography is a bad idea - use
System.Security.Cryptographyand AEAD modes. - The same nonce twice in AES-GCM destroys security.
- ECB reveals patterns in the data.
- A signature is not "encryption with the private key" - in modern schemes (PSS, ECDSA) it is a separate operation.
Interview questions
- How does symmetric encryption differ from asymmetric? Symmetric uses one shared key and is fast, but requires the key to be passed on securely. Asymmetric uses a key pair, solves key exchange and enables signatures, but is slow.
- How does HTTPS work? The client and server agree a session key through ECDHE, the server proves its identity with a signature and a certificate, and the data is encrypted symmetrically (AES-GCM).
- What is forward secrecy? Session keys are ephemeral, so a leak of the server's private key doesn't allow old traffic to be decrypted.
- Why isn't Diffie-Hellman alone enough? It doesn't authenticate the parties, so it is vulnerable to MITM. A signature and a certificate are needed.
- Hash, encryption and encoding? A hash is one-way, encryption is reversible with a key, encoding (Base64) is reversible without a key.
- How should passwords be stored? A slow function with a salt (PBKDF2, bcrypt, Argon2), never plain SHA or encryption.
- Why is ECB mode bad? Identical plaintext blocks give identical ciphertexts, so patterns leak.