posts-go/posts/2023-08-23-real-world-crypt...

80 lines
2.4 KiB
Markdown
Raw Normal View History

2023-08-23 17:09:04 +00:00
# Real World Crypto 101
My notes when reading
[Real-World Cryptography](https://www.manning.com/books/real-world-cryptography)
2023-09-10 18:03:48 +00:00
## **Hash** function convert from input to digest
2023-08-23 17:09:04 +00:00
- Pre-image resistance: Given digest, can not find input
- Second pre-image resistance: Given input, digest, can not find another input
produce same digest. Small change to input make digest big change.
- Collision resistance: Can not find 2 input produce same digest.
2023-09-10 18:03:48 +00:00
## **MAC** aka Message Authentication Code produce from key, message to authentication tag.
- A send B message with MAC (generate from message and A key).
- B double check message with MAC (generate from receive message and B key).
- A and B use same key.
2023-09-10 16:39:41 +00:00
2023-09-10 18:03:48 +00:00
```mermaid
sequenceDiagram
participant alice
participant bob
alice ->> bob: send alice, mac(secret_key_alice, alice)
bob ->> bob: compare mac(secret_key_alice, alice) with mac(secret_key_bob, alice)
```
- Prevent forgery: without secret_key, can not generate MAC even if knowing **a
lot of** alice and mac(secret_key, alice),
- Prevent collisions: keep MAC long enough (256-bit),
- Replay attacks: send transaction 2 times with perfectly MAC and u know why ->
instead of mac(secret_key, alice), use **counter** as mac(secret_key, counter,
alice).
- Verify must be done in **constant time**: if not, probaly return error the
moment the bytes differ -> attacker recreate byte by byte by measuring how
long -> timing attacks
Constant time comparision:
```go
for i := 0; i < len(x); i++ {
// Use XOR instead of compare x[i] == y[i]
// If x[i] == y[i] -> XOR is 1
// Otherwise XOR is 0
v |= x[i] ^ y[i]
}
// v == 1 means all XOR is 1 means x == y
```
Use for:
- Integrity: because MAC ensure no one can tamper with message without noticing
2023-09-10 16:41:21 +00:00
```mermaid
2023-09-10 16:39:41 +00:00
sequenceDiagram
participant alice
participant bob
alice ->> bob: send username, password
2023-09-10 18:03:48 +00:00
bob -->> alice: return alice|mac(secret_key, alice)
alice ->> bob: send alice|mac(secret_key, alice)
2023-09-10 16:39:41 +00:00
bob -->> alice: return OK
2023-09-10 18:03:48 +00:00
alice ->> bob: send bob|mac(secret_key, alice)
2023-09-10 16:39:41 +00:00
bob -->> alice: return ERROR
```
2023-09-10 18:03:48 +00:00
**HMAC** is MAC using hash
2023-11-07 17:56:37 +00:00
## AES
Currently (2023) the world using AES-128 which take a key 128 bits == 16 bytes/
- Take a variable-length key
- Take plaintext of 128 bits
- Give ciphertext of 128 bits
AES is kind of cipher, handle fixed-size plaintext so we called **block
cipher**.