norx.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // norx.go - High-level interface
  2. //
  3. // To the extent possible under law, Yawning Angel has waived all copyright
  4. // and related or neighboring rights to the software, using the Creative
  5. // Commons "CC0" public domain dedication. See LICENSE or
  6. // <http://creativecommons.org/publicdomain/zero/1.0/> for full details.
  7. package norx
  8. import "crypto/subtle"
  9. const (
  10. // KeySize is the size of a key in bytes.
  11. KeySize = 32
  12. // NonceSize is the size of a nonce in bytes.
  13. NonceSize = 32
  14. // TagSize is the size of an authentication tag in bytes.
  15. TagSize = 32
  16. // Version is the version of the NORX specification implemented.
  17. Version = "3.0"
  18. )
  19. func aeadEncrypt(l int, c, a, m, z, nonce, key []byte) []byte {
  20. var k [bytesK]byte
  21. s := &state{rounds: l}
  22. mLen := len(m)
  23. ret, out := sliceForAppend(c, mLen+bytesT)
  24. copy(k[:], key)
  25. hardwareAccelImpl.initFn(s, k[:], nonce)
  26. hardwareAccelImpl.absorbDataFn(s, a, tagHeader)
  27. hardwareAccelImpl.encryptDataFn(s, out, m)
  28. hardwareAccelImpl.absorbDataFn(s, z, tagTrailer)
  29. hardwareAccelImpl.finalizeFn(s, out[mLen:], k[:])
  30. burnUint64s(s.s[:])
  31. burnBytes(k[:])
  32. return ret
  33. }
  34. func aeadDecrypt(l int, m, a, c, z, nonce, key []byte) ([]byte, bool) {
  35. var k [bytesK]byte
  36. var tag [bytesT]byte
  37. s := &state{rounds: l}
  38. cLen := len(c)
  39. if cLen < bytesT {
  40. return nil, false
  41. }
  42. mLen := cLen - bytesT
  43. ret, out := sliceForAppend(m, mLen)
  44. copy(k[:], key)
  45. hardwareAccelImpl.initFn(s, k[:], nonce)
  46. hardwareAccelImpl.absorbDataFn(s, a, tagHeader)
  47. hardwareAccelImpl.decryptDataFn(s, out, c[:mLen])
  48. hardwareAccelImpl.absorbDataFn(s, z, tagTrailer)
  49. hardwareAccelImpl.finalizeFn(s, tag[:], k[:])
  50. srcTag := c[mLen:]
  51. ok := subtle.ConstantTimeCompare(srcTag, tag[:]) == 1
  52. if !ok && mLen > 0 { // burn decrypted plaintext on auth failure
  53. burnBytes(out[:mLen])
  54. ret = nil
  55. }
  56. burnUint64s(s.s[:])
  57. burnBytes(k[:])
  58. return ret, ok
  59. }
  60. // Shamelessly stolen from the Go runtime library.
  61. func sliceForAppend(in []byte, n int) (head, tail []byte) {
  62. if total := len(in) + n; cap(in) >= total {
  63. head = in[:total]
  64. } else {
  65. head = make([]byte, total)
  66. copy(head, in)
  67. }
  68. tail = head[len(in):]
  69. return
  70. }
  71. func init() {
  72. if KeySize != bytesK {
  73. panic("BUG: KeySize != paramK/8")
  74. }
  75. if NonceSize != paramN/8 {
  76. panic("BUG: NonceSize != paramN/8")
  77. }
  78. if TagSize != bytesT {
  79. panic("BUG: TagSize != bytesT")
  80. }
  81. }