box.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 box authenticates and encrypts small messages using public-key cryptography.
  6. Box uses Curve25519, XSalsa20 and Poly1305 to encrypt and authenticate
  7. messages. 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/box.html.
  24. Anonymous sealing/opening is an extension of NaCl defined by and interoperable
  25. with libsodium:
  26. https://libsodium.gitbook.io/doc/public-key_cryptography/sealed_boxes.
  27. */
  28. package box // import "golang.org/x/crypto/nacl/box"
  29. import (
  30. cryptorand "crypto/rand"
  31. "io"
  32. "golang.org/x/crypto/blake2b"
  33. "golang.org/x/crypto/curve25519"
  34. "golang.org/x/crypto/nacl/secretbox"
  35. "golang.org/x/crypto/salsa20/salsa"
  36. )
  37. const (
  38. // Overhead is the number of bytes of overhead when boxing a message.
  39. Overhead = secretbox.Overhead
  40. // AnonymousOverhead is the number of bytes of overhead when using anonymous
  41. // sealed boxes.
  42. AnonymousOverhead = Overhead + 32
  43. )
  44. // GenerateKey generates a new public/private key pair suitable for use with
  45. // Seal and Open.
  46. func GenerateKey(rand io.Reader) (publicKey, privateKey *[32]byte, err error) {
  47. publicKey = new([32]byte)
  48. privateKey = new([32]byte)
  49. _, err = io.ReadFull(rand, privateKey[:])
  50. if err != nil {
  51. publicKey = nil
  52. privateKey = nil
  53. return
  54. }
  55. curve25519.ScalarBaseMult(publicKey, privateKey)
  56. return
  57. }
  58. var zeros [16]byte
  59. // Precompute calculates the shared key between peersPublicKey and privateKey
  60. // and writes it to sharedKey. The shared key can be used with
  61. // OpenAfterPrecomputation and SealAfterPrecomputation to speed up processing
  62. // when using the same pair of keys repeatedly.
  63. func Precompute(sharedKey, peersPublicKey, privateKey *[32]byte) {
  64. curve25519.ScalarMult(sharedKey, privateKey, peersPublicKey)
  65. salsa.HSalsa20(sharedKey, &zeros, sharedKey, &salsa.Sigma)
  66. }
  67. // Seal appends an encrypted and authenticated copy of message to out, which
  68. // will be Overhead bytes longer than the original and must not overlap it. The
  69. // nonce must be unique for each distinct message for a given pair of keys.
  70. func Seal(out, message []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) []byte {
  71. var sharedKey [32]byte
  72. Precompute(&sharedKey, peersPublicKey, privateKey)
  73. return secretbox.Seal(out, message, nonce, &sharedKey)
  74. }
  75. // SealAfterPrecomputation performs the same actions as Seal, but takes a
  76. // shared key as generated by Precompute.
  77. func SealAfterPrecomputation(out, message []byte, nonce *[24]byte, sharedKey *[32]byte) []byte {
  78. return secretbox.Seal(out, message, nonce, sharedKey)
  79. }
  80. // Open authenticates and decrypts a box produced by Seal and appends the
  81. // message to out, which must not overlap box. The output will be Overhead
  82. // bytes smaller than box.
  83. func Open(out, box []byte, nonce *[24]byte, peersPublicKey, privateKey *[32]byte) ([]byte, bool) {
  84. var sharedKey [32]byte
  85. Precompute(&sharedKey, peersPublicKey, privateKey)
  86. return secretbox.Open(out, box, nonce, &sharedKey)
  87. }
  88. // OpenAfterPrecomputation performs the same actions as Open, but takes a
  89. // shared key as generated by Precompute.
  90. func OpenAfterPrecomputation(out, box []byte, nonce *[24]byte, sharedKey *[32]byte) ([]byte, bool) {
  91. return secretbox.Open(out, box, nonce, sharedKey)
  92. }
  93. // SealAnonymous appends an encrypted and authenticated copy of message to out,
  94. // which will be AnonymousOverhead bytes longer than the original and must not
  95. // overlap it. This differs from Seal in that the sender is not required to
  96. // provide a private key.
  97. func SealAnonymous(out, message []byte, recipient *[32]byte, rand io.Reader) ([]byte, error) {
  98. if rand == nil {
  99. rand = cryptorand.Reader
  100. }
  101. ephemeralPub, ephemeralPriv, err := GenerateKey(rand)
  102. if err != nil {
  103. return nil, err
  104. }
  105. var nonce [24]byte
  106. if err := sealNonce(ephemeralPub, recipient, &nonce); err != nil {
  107. return nil, err
  108. }
  109. if total := len(out) + AnonymousOverhead + len(message); cap(out) < total {
  110. original := out
  111. out = make([]byte, 0, total)
  112. out = append(out, original...)
  113. }
  114. out = append(out, ephemeralPub[:]...)
  115. return Seal(out, message, &nonce, recipient, ephemeralPriv), nil
  116. }
  117. // OpenAnonymous authenticates and decrypts a box produced by SealAnonymous and
  118. // appends the message to out, which must not overlap box. The output will be
  119. // AnonymousOverhead bytes smaller than box.
  120. func OpenAnonymous(out, box []byte, publicKey, privateKey *[32]byte) (message []byte, ok bool) {
  121. if len(box) < AnonymousOverhead {
  122. return nil, false
  123. }
  124. var ephemeralPub [32]byte
  125. copy(ephemeralPub[:], box[:32])
  126. var nonce [24]byte
  127. if err := sealNonce(&ephemeralPub, publicKey, &nonce); err != nil {
  128. return nil, false
  129. }
  130. return Open(out, box[32:], &nonce, &ephemeralPub, privateKey)
  131. }
  132. // sealNonce generates a 24 byte nonce that is a blake2b digest of the
  133. // ephemeral public key and the receiver's public key.
  134. func sealNonce(ephemeralPub, peersPublicKey *[32]byte, nonce *[24]byte) error {
  135. h, err := blake2b.New(24, nil)
  136. if err != nil {
  137. return err
  138. }
  139. if _, err = h.Write(ephemeralPub[:]); err != nil {
  140. return err
  141. }
  142. if _, err = h.Write(peersPublicKey[:]); err != nil {
  143. return err
  144. }
  145. h.Sum(nonce[:0])
  146. return nil
  147. }