crypter.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package crypt
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/sha512"
  6. "io"
  7. "github.com/pkg/errors"
  8. )
  9. // Crypter can only be used once
  10. type Crypter struct {
  11. key []byte
  12. block cipher.Block
  13. used bool
  14. }
  15. // NewCrypter creates a new Crypter, or nil if there is an error
  16. func NewCrypter(key []byte) (e *Crypter, err error) {
  17. e = new(Crypter)
  18. if len(key) != sha512.Size256 {
  19. return nil, errors.Errorf("whatwhat: wrong key length. Got:%d", len(key))
  20. }
  21. e.key = key
  22. e.block, err = aes.NewCipher(e.key)
  23. if err != nil {
  24. return nil, errors.Wrap(err, "whatwhat: couldn't create AES cipher")
  25. }
  26. return e, nil
  27. }
  28. // MakePipe takes an output (for the cipher text) writer and returns a writer to which you writer your cleartext
  29. func (e *Crypter) MakePipe(out io.Writer) (io.Writer, error) {
  30. if e.used == true {
  31. return nil, errors.New("whatwhat: crypter was used twice")
  32. }
  33. // we only use Crypter once, its ok to have a zero IV
  34. var iv [aes.BlockSize]byte
  35. stream := cipher.NewCTR(e.block, iv[:])
  36. e.used = true
  37. return &cipher.StreamWriter{S: stream, W: out}, nil
  38. }