You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

166 lines
5.3 KiB

  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. /*
  5. Package secretbox encrypts and authenticates small messages.
  6. Secretbox uses XSalsa20 and Poly1305 to encrypt and authenticate messages with
  7. secret-key cryptography. The length of messages is not hidden.
  8. It is the caller's responsibility to ensure the uniqueness of noncesfor
  9. example, by using nonce 1 for the first message, nonce 2 for the second
  10. message, etc. Nonces are long enough that randomly generated nonces have
  11. negligible risk of collision.
  12. Messages should be small because:
  13. 1. The whole message needs to be held in memory to be processed.
  14. 2. Using large messages pressures implementations on small machines to decrypt
  15. and process plaintext before authenticating it. This is very dangerous, and
  16. this API does not allow it, but a protocol that uses excessive message sizes
  17. might present some implementations with no other choice.
  18. 3. Fixed overheads will be sufficiently amortised by messages as small as 8KB.
  19. 4. Performance may be improved by working with messages that fit into data caches.
  20. Thus large amounts of data should be chunked so that each message is small.
  21. (Each message still needs a unique nonce.) If in doubt, 16KB is a reasonable
  22. chunk size.
  23. This package is interoperable with NaCl: https://nacl.cr.yp.to/secretbox.html.
  24. */
  25. package secretbox // import "golang.org/x/crypto/nacl/secretbox"
  26. import (
  27. "golang.org/x/crypto/poly1305"
  28. "golang.org/x/crypto/salsa20/salsa"
  29. )
  30. // Overhead is the number of bytes of overhead when boxing a message.
  31. const Overhead = poly1305.TagSize
  32. // setup produces a sub-key and Salsa20 counter given a nonce and key.
  33. func setup(subKey *[32]byte, counter *[16]byte, nonce *[24]byte, key *[32]byte) {
  34. // We use XSalsa20 for encryption so first we need to generate a
  35. // key and nonce with HSalsa20.
  36. var hNonce [16]byte
  37. copy(hNonce[:], nonce[:])
  38. salsa.HSalsa20(subKey, &hNonce, key, &salsa.Sigma)
  39. // The final 8 bytes of the original nonce form the new nonce.
  40. copy(counter[:], nonce[16:])
  41. }
  42. // sliceForAppend takes a slice and a requested number of bytes. It returns a
  43. // slice with the contents of the given slice followed by that many bytes and a
  44. // second slice that aliases into it and contains only the extra bytes. If the
  45. // original slice has sufficient capacity then no allocation is performed.
  46. func sliceForAppend(in []byte, n int) (head, tail []byte) {
  47. if total := len(in) + n; cap(in) >= total {
  48. head = in[:total]
  49. } else {
  50. head = make([]byte, total)
  51. copy(head, in)
  52. }
  53. tail = head[len(in):]
  54. return
  55. }
  56. // Seal appends an encrypted and authenticated copy of message to out, which
  57. // must not overlap message. The key and nonce pair must be unique for each
  58. // distinct message and the output will be Overhead bytes longer than message.
  59. func Seal(out, message []byte, nonce *[24]byte, key *[32]byte) []byte {
  60. var subKey [32]byte
  61. var counter [16]byte
  62. setup(&subKey, &counter, nonce, key)
  63. // The Poly1305 key is generated by encrypting 32 bytes of zeros. Since
  64. // Salsa20 works with 64-byte blocks, we also generate 32 bytes of
  65. // keystream as a side effect.
  66. var firstBlock [64]byte
  67. salsa.XORKeyStream(firstBlock[:], firstBlock[:], &counter, &subKey)
  68. var poly1305Key [32]byte
  69. copy(poly1305Key[:], firstBlock[:])
  70. ret, out := sliceForAppend(out, len(message)+poly1305.TagSize)
  71. // We XOR up to 32 bytes of message with the keystream generated from
  72. // the first block.
  73. firstMessageBlock := message
  74. if len(firstMessageBlock) > 32 {
  75. firstMessageBlock = firstMessageBlock[:32]
  76. }
  77. tagOut := out
  78. out = out[poly1305.TagSize:]
  79. for i, x := range firstMessageBlock {
  80. out[i] = firstBlock[32+i] ^ x
  81. }
  82. message = message[len(firstMessageBlock):]
  83. ciphertext := out
  84. out = out[len(firstMessageBlock):]
  85. // Now encrypt the rest.
  86. counter[8] = 1
  87. salsa.XORKeyStream(out, message, &counter, &subKey)
  88. var tag [poly1305.TagSize]byte
  89. poly1305.Sum(&tag, ciphertext, &poly1305Key)
  90. copy(tagOut, tag[:])
  91. return ret
  92. }
  93. // Open authenticates and decrypts a box produced by Seal and appends the
  94. // message to out, which must not overlap box. The output will be Overhead
  95. // bytes smaller than box.
  96. func Open(out []byte, box []byte, nonce *[24]byte, key *[32]byte) ([]byte, bool) {
  97. if len(box) < Overhead {
  98. return nil, false
  99. }
  100. var subKey [32]byte
  101. var counter [16]byte
  102. setup(&subKey, &counter, nonce, key)
  103. // The Poly1305 key is generated by encrypting 32 bytes of zeros. Since
  104. // Salsa20 works with 64-byte blocks, we also generate 32 bytes of
  105. // keystream as a side effect.
  106. var firstBlock [64]byte
  107. salsa.XORKeyStream(firstBlock[:], firstBlock[:], &counter, &subKey)
  108. var poly1305Key [32]byte
  109. copy(poly1305Key[:], firstBlock[:])
  110. var tag [poly1305.TagSize]byte
  111. copy(tag[:], box)
  112. if !poly1305.Verify(&tag, box[poly1305.TagSize:], &poly1305Key) {
  113. return nil, false
  114. }
  115. ret, out := sliceForAppend(out, len(box)-Overhead)
  116. // We XOR up to 32 bytes of box with the keystream generated from
  117. // the first block.
  118. box = box[Overhead:]
  119. firstMessageBlock := box
  120. if len(firstMessageBlock) > 32 {
  121. firstMessageBlock = firstMessageBlock[:32]
  122. }
  123. for i, x := range firstMessageBlock {
  124. out[i] = firstBlock[32+i] ^ x
  125. }
  126. box = box[len(firstMessageBlock):]
  127. out = out[len(firstMessageBlock):]
  128. // Now decrypt the rest.
  129. counter[8] = 1
  130. salsa.XORKeyStream(out, box, &counter, &subKey)
  131. return ret, true
  132. }