doc.odin 1.7 KB

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