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.
 
 
 

55 lines
1.9 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 salsa20 implements the Salsa20 stream cipher as specified in http://cr.yp.to/snuffle/spec.pdf.
  6. Salsa20 differs from many other stream ciphers in that it is message orientated
  7. rather than byte orientated. Keystream blocks are not preserved between calls,
  8. therefore each side must encrypt/decrypt data with the same segmentation.
  9. Another aspect of this difference is that part of the counter is exposed as
  10. an nonce in each call. Encrypting two different messages with the same (key,
  11. nonce) pair leads to trivial plaintext recovery. This is analogous to
  12. encrypting two different messages with the same key with a traditional stream
  13. cipher.
  14. This package also implements XSalsa20: a version of Salsa20 with a 24-byte
  15. nonce as specified in http://cr.yp.to/snuffle/xsalsa-20081128.pdf. Simply
  16. passing a 24-byte slice as the nonce triggers XSalsa20.
  17. */
  18. package salsa20 // import "golang.org/x/crypto/salsa20"
  19. // TODO(agl): implement XORKeyStream12 and XORKeyStream8 - the reduced round variants of Salsa20.
  20. import (
  21. "golang.org/x/crypto/salsa20/salsa"
  22. )
  23. // XORKeyStream crypts bytes from in to out using the given key and nonce. In
  24. // and out may be the same slice but otherwise should not overlap. Nonce must
  25. // be either 8 or 24 bytes long.
  26. func XORKeyStream(out, in []byte, nonce []byte, key *[32]byte) {
  27. if len(out) < len(in) {
  28. in = in[:len(out)]
  29. }
  30. var subNonce [16]byte
  31. if len(nonce) == 24 {
  32. var subKey [32]byte
  33. var hNonce [16]byte
  34. copy(hNonce[:], nonce[:16])
  35. salsa.HSalsa20(&subKey, &hNonce, key, &salsa.Sigma)
  36. copy(subNonce[:], nonce[16:])
  37. key = &subKey
  38. } else if len(nonce) == 8 {
  39. copy(subNonce[:], nonce[:])
  40. } else {
  41. panic("salsa20: nonce must be 8 or 24 bytes")
  42. }
  43. salsa.XORKeyStream(out, in, &subNonce, key)
  44. }