Add streaming encrypt functions

This commit is contained in:
Alexander Neumann
2015-02-11 17:41:11 +01:00
parent 93abaf204a
commit c6901af5aa
2 changed files with 182 additions and 4 deletions

91
key.go
View File

@@ -1,6 +1,7 @@
package restic
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
@@ -9,6 +10,7 @@ import (
"encoding/json"
"errors"
"fmt"
"hash"
"io"
"os"
"os/user"
@@ -315,6 +317,95 @@ func (k *Key) Encrypt(ciphertext, plaintext []byte) (int, error) {
return k.encrypt(k.master, ciphertext, plaintext)
}
type HashReader struct {
r io.Reader
h hash.Hash
sum []byte
closed bool
}
func NewHashReader(r io.Reader, h hash.Hash) *HashReader {
return &HashReader{
h: h,
r: io.TeeReader(r, h),
sum: make([]byte, 0, h.Size()),
}
}
func (h *HashReader) Read(p []byte) (n int, err error) {
if !h.closed {
n, err = h.r.Read(p)
if err == io.EOF {
h.closed = true
h.sum = h.h.Sum(h.sum)
} else if err != nil {
return
}
}
if h.closed {
// output hash
r := len(p) - n
if r > 0 {
c := copy(p[n:], h.sum)
h.sum = h.sum[c:]
n += c
err = nil
}
if len(h.sum) == 0 {
err = io.EOF
}
}
return
}
// encryptFrom encrypts and signs data read from rd with ks. The returned
// io.Reader reads IV || Ciphertext || HMAC. For the hash function, SHA256 is
// used.
func (k *Key) encryptFrom(ks *keys, rd io.Reader) io.Reader {
// create IV
iv := make([]byte, ivSize)
_, err := io.ReadFull(rand.Reader, iv)
if err != nil {
panic(fmt.Sprintf("unable to generate new random iv: %v", err))
}
c, err := aes.NewCipher(ks.Encrypt)
if err != nil {
panic(fmt.Sprintf("unable to create cipher: %v", err))
}
ivReader := bytes.NewReader(iv)
encryptReader := cipher.StreamReader{
R: rd,
S: cipher.NewCTR(c, iv),
}
return NewHashReader(io.MultiReader(ivReader, encryptReader),
hmac.New(sha256.New, ks.Sign))
}
// EncryptFrom encrypts and signs data read from rd with the master key. The
// returned io.Reader reads IV || Ciphertext || HMAC. For the hash function,
// SHA256 is used.
func (k *Key) EncryptFrom(rd io.Reader) io.Reader {
return k.encryptFrom(k.master, rd)
}
// EncryptFrom encrypts and signs data read from rd with the user key. The
// returned io.Reader reads IV || Ciphertext || HMAC. For the hash function,
// SHA256 is used.
func (k *Key) EncryptUserFrom(rd io.Reader) io.Reader {
return k.encryptFrom(k.user, rd)
}
// Decrypt verifes and decrypts the ciphertext. Ciphertext must be in the form
// IV || Ciphertext || HMAC.
func (k *Key) decrypt(ks *keys, ciphertext []byte) ([]byte, error) {