chacha20.go 494 B

1234567891011121314151617181920212223242526272829
  1. package crypto
  2. import (
  3. "crypto/cipher"
  4. "github.com/aead/chacha20"
  5. )
  6. func makeNonce(nonce *[chacha20.NonceSize]byte, iv []byte) {
  7. switch len(iv) {
  8. case 8:
  9. copy(nonce[4:], iv)
  10. case 12:
  11. copy(nonce[:], iv)
  12. default:
  13. panic("bad nonce length")
  14. }
  15. }
  16. func NewChaCha20Stream(key []byte, iv []byte) cipher.Stream {
  17. var Key [32]byte
  18. var Nonce [12]byte
  19. if len(key) != 32 {
  20. panic("bad key length")
  21. }
  22. copy(Key[:], key)
  23. makeNonce(&Nonce, iv)
  24. return chacha20.NewCipher(&Nonce, &Key)
  25. }