doc.odin 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. A generic interface to Authenticated Encryption with Associated Data (`AEAD`) algorithms.
  3. Both a one-shot and context based interface are provided, with similar
  4. usage. If multiple messages are to be sealed/opened via the same key,
  5. the context based interface may be more efficient, depending on the
  6. algorithm.
  7. WARNING: Reusing the same key + iv to seal (encrypt) multiple messages
  8. results in catastrophic loss of security for most algorithms.
  9. Example:
  10. package aead_example
  11. import "core:bytes"
  12. import "core:crypto"
  13. import "core:crypto/aead"
  14. main :: proc() {
  15. algo := aead.Algorithm.XCHACHA20POLY1305
  16. // The example added associated data, and plaintext.
  17. aad_str := "Get your ass in gear boys."
  18. pt_str := "They're immanetizing the Eschaton."
  19. aad := transmute([]byte)aad_str
  20. plaintext := transmute([]byte)pt_str
  21. pt_len := len(plaintext)
  22. // Generate a random key for the purposes of illustration.
  23. key := make([]byte, aead.KEY_SIZES[algo])
  24. defer delete(key)
  25. crypto.rand_bytes(key)
  26. // `ciphertext || tag`, is a common way data is transmitted, so
  27. // demonstrate that.
  28. buf := make([]byte, pt_len + aead.TAG_SIZES[algo])
  29. defer delete(buf)
  30. ciphertext, tag := buf[:pt_len], buf[pt_len:]
  31. // Seal the AAD + Plaintext.
  32. iv := make([]byte, aead.IV_SIZES[algo])
  33. defer delete(iv)
  34. crypto.rand_bytes(iv) // Random IVs are safe with XChaCha20-Poly1305.
  35. aead.seal(algo, ciphertext, tag, key, iv, aad, plaintext)
  36. // Open the AAD + Ciphertext.
  37. opened_pt := buf[:pt_len]
  38. if ok := aead.open(algo, opened_pt, key, iv, aad, ciphertext, tag); !ok {
  39. panic("aead example: failed to open")
  40. }
  41. assert(bytes.equal(opened_pt, plaintext))
  42. }
  43. */
  44. package aead