25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

174 satır
5.5 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 nonces—for
  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/internal/subtle"
  28. "golang.org/x/crypto/poly1305"
  29. "golang.org/x/crypto/salsa20/salsa"
  30. )
  31. // Overhead is the number of bytes of overhead when boxing a message.
  32. const Overhead = poly1305.TagSize
  33. // setup produces a sub-key and Salsa20 counter given a nonce and key.
  34. func setup(subKey *[32]byte, counter *[16]byte, nonce *[24]byte, key *[32]byte) {
  35. // We use XSalsa20 for encryption so first we need to generate a
  36. // key and nonce with HSalsa20.
  37. var hNonce [16]byte
  38. copy(hNonce[:], nonce[:])
  39. salsa.HSalsa20(subKey, &hNonce, key, &salsa.Sigma)
  40. // The final 8 bytes of the original nonce form the new nonce.
  41. copy(counter[:], nonce[16:])
  42. }
  43. // sliceForAppend takes a slice and a requested number of bytes. It returns a
  44. // slice with the contents of the given slice followed by that many bytes and a
  45. // second slice that aliases into it and contains only the extra bytes. If the
  46. // original slice has sufficient capacity then no allocation is performed.
  47. func sliceForAppend(in []byte, n int) (head, tail []byte) {
  48. if total := len(in) + n; cap(in) >= total {
  49. head = in[:total]
  50. } else {
  51. head = make([]byte, total)
  52. copy(head, in)
  53. }
  54. tail = head[len(in):]
  55. return
  56. }
  57. // Seal appends an encrypted and authenticated copy of message to out, which
  58. // must not overlap message. The key and nonce pair must be unique for each
  59. // distinct message and the output will be Overhead bytes longer than message.
  60. func Seal(out, message []byte, nonce *[24]byte, key *[32]byte) []byte {
  61. var subKey [32]byte
  62. var counter [16]byte
  63. setup(&subKey, &counter, nonce, key)
  64. // The Poly1305 key is generated by encrypting 32 bytes of zeros. Since
  65. // Salsa20 works with 64-byte blocks, we also generate 32 bytes of
  66. // keystream as a side effect.
  67. var firstBlock [64]byte
  68. salsa.XORKeyStream(firstBlock[:], firstBlock[:], &counter, &subKey)
  69. var poly1305Key [32]byte
  70. copy(poly1305Key[:], firstBlock[:])
  71. ret, out := sliceForAppend(out, len(message)+poly1305.TagSize)
  72. if subtle.AnyOverlap(out, message) {
  73. panic("nacl: invalid buffer overlap")
  74. }
  75. // We XOR up to 32 bytes of message with the keystream generated from
  76. // the first block.
  77. firstMessageBlock := message
  78. if len(firstMessageBlock) > 32 {
  79. firstMessageBlock = firstMessageBlock[:32]
  80. }
  81. tagOut := out
  82. out = out[poly1305.TagSize:]
  83. for i, x := range firstMessageBlock {
  84. out[i] = firstBlock[32+i] ^ x
  85. }
  86. message = message[len(firstMessageBlock):]
  87. ciphertext := out
  88. out = out[len(firstMessageBlock):]
  89. // Now encrypt the rest.
  90. counter[8] = 1
  91. salsa.XORKeyStream(out, message, &counter, &subKey)
  92. var tag [poly1305.TagSize]byte
  93. poly1305.Sum(&tag, ciphertext, &poly1305Key)
  94. copy(tagOut, tag[:])
  95. return ret
  96. }
  97. // Open authenticates and decrypts a box produced by Seal and appends the
  98. // message to out, which must not overlap box. The output will be Overhead
  99. // bytes smaller than box.
  100. func Open(out, box []byte, nonce *[24]byte, key *[32]byte) ([]byte, bool) {
  101. if len(box) < Overhead {
  102. return nil, false
  103. }
  104. var subKey [32]byte
  105. var counter [16]byte
  106. setup(&subKey, &counter, nonce, key)
  107. // The Poly1305 key is generated by encrypting 32 bytes of zeros. Since
  108. // Salsa20 works with 64-byte blocks, we also generate 32 bytes of
  109. // keystream as a side effect.
  110. var firstBlock [64]byte
  111. salsa.XORKeyStream(firstBlock[:], firstBlock[:], &counter, &subKey)
  112. var poly1305Key [32]byte
  113. copy(poly1305Key[:], firstBlock[:])
  114. var tag [poly1305.TagSize]byte
  115. copy(tag[:], box)
  116. if !poly1305.Verify(&tag, box[poly1305.TagSize:], &poly1305Key) {
  117. return nil, false
  118. }
  119. ret, out := sliceForAppend(out, len(box)-Overhead)
  120. if subtle.AnyOverlap(out, box) {
  121. panic("nacl: invalid buffer overlap")
  122. }
  123. // We XOR up to 32 bytes of box with the keystream generated from
  124. // the first block.
  125. box = box[Overhead:]
  126. firstMessageBlock := box
  127. if len(firstMessageBlock) > 32 {
  128. firstMessageBlock = firstMessageBlock[:32]
  129. }
  130. for i, x := range firstMessageBlock {
  131. out[i] = firstBlock[32+i] ^ x
  132. }
  133. box = box[len(firstMessageBlock):]
  134. out = out[len(firstMessageBlock):]
  135. // Now decrypt the rest.
  136. counter[8] = 1
  137. salsa.XORKeyStream(out, box, &counter, &subKey)
  138. return ret, true
  139. }