2015-04-12 08:57:41 +00:00
|
|
|
package crypto
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/aes"
|
|
|
|
"crypto/cipher"
|
2015-04-24 20:55:40 +00:00
|
|
|
"errors"
|
2015-04-12 08:57:41 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
|
|
|
type encryptWriter struct {
|
2015-04-24 20:55:40 +00:00
|
|
|
data []byte
|
|
|
|
key *Key
|
|
|
|
s cipher.Stream
|
|
|
|
w io.Writer
|
|
|
|
closed bool
|
2015-04-12 08:57:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (e *encryptWriter) Close() error {
|
2015-04-24 20:55:40 +00:00
|
|
|
if e.closed {
|
|
|
|
return errors.New("Close() called on already closed writer")
|
|
|
|
}
|
|
|
|
e.closed = true
|
|
|
|
|
|
|
|
// encrypt everything
|
|
|
|
iv, c := e.data[:ivSize], e.data[ivSize:]
|
|
|
|
e.s.XORKeyStream(c, c)
|
|
|
|
|
|
|
|
// compute mac
|
|
|
|
mac := poly1305Sign(c, iv, &e.key.Sign)
|
|
|
|
e.data = append(e.data, mac...)
|
|
|
|
|
|
|
|
// write everything
|
|
|
|
n, err := e.w.Write(e.data)
|
2015-04-12 08:57:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2015-04-24 20:55:40 +00:00
|
|
|
if n != len(e.data) {
|
|
|
|
return errors.New("not all bytes written")
|
|
|
|
}
|
2015-04-12 08:57:41 +00:00
|
|
|
|
2015-04-24 20:55:40 +00:00
|
|
|
// return buffer to pool
|
|
|
|
freeBuffer(e.data)
|
2015-04-12 08:57:41 +00:00
|
|
|
|
2015-04-24 20:55:40 +00:00
|
|
|
return nil
|
2015-04-12 08:57:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (e *encryptWriter) Write(p []byte) (int, error) {
|
2015-04-24 20:55:40 +00:00
|
|
|
// if e.data is too small, return it to the buffer and create new slice
|
|
|
|
if cap(e.data) < len(e.data)+len(p) {
|
|
|
|
b := make([]byte, len(e.data), len(e.data)*2)
|
|
|
|
copy(b, e.data)
|
|
|
|
freeBuffer(e.data)
|
|
|
|
e.data = b
|
2015-04-12 08:57:41 +00:00
|
|
|
}
|
|
|
|
|
2015-04-24 20:55:40 +00:00
|
|
|
// copy new data to e.data
|
|
|
|
e.data = append(e.data, p...)
|
|
|
|
return len(p), nil
|
2015-04-12 08:57:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// EncryptTo buffers data written to the returned io.WriteCloser. When Close()
|
2015-04-24 20:55:40 +00:00
|
|
|
// is called, the data is encrypted and written to the underlying writer.
|
2015-04-12 08:57:41 +00:00
|
|
|
func EncryptTo(ks *Key, wr io.Writer) io.WriteCloser {
|
|
|
|
ew := &encryptWriter{
|
2015-04-24 20:55:40 +00:00
|
|
|
data: getBuffer(),
|
|
|
|
key: ks,
|
2015-04-12 08:57:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// buffer iv for mac
|
2015-04-24 20:55:40 +00:00
|
|
|
ew.data = ew.data[:ivSize]
|
|
|
|
copy(ew.data, newIV())
|
2015-04-12 08:57:41 +00:00
|
|
|
|
|
|
|
c, err := aes.NewCipher(ks.Encrypt[:])
|
|
|
|
if err != nil {
|
|
|
|
panic(fmt.Sprintf("unable to create cipher: %v", err))
|
|
|
|
}
|
|
|
|
|
2015-04-24 20:55:40 +00:00
|
|
|
ew.s = cipher.NewCTR(c, ew.data[:ivSize])
|
|
|
|
ew.w = wr
|
2015-04-12 08:57:41 +00:00
|
|
|
|
|
|
|
return ew
|
|
|
|
}
|