Skip to content

Commit

Permalink
Merge pull request #4 from Cistern/3-randomize-iv
Browse files Browse the repository at this point in the history
Randomize IV
  • Loading branch information
Preetam committed Apr 23, 2016
2 parents 8a3ffcc + 75e75aa commit f8b93c8
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 36 deletions.
25 changes: 12 additions & 13 deletions payloadcrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,19 @@ func (c *Crypt) Encrypt(payload []byte) ([]byte, error) {
if c.iv == nil {
// Initialize IV
c.iv = make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, c.iv); err != nil {
return nil, fmt.Errorf("payloadcrypt: couldn't initialize IV: %v", err)
err := c.generateIV()
if err != nil {
return nil, err
}
}
ciphertext := make([]byte, aes.BlockSize+len(payload))
copy(ciphertext[:aes.BlockSize], c.iv)
stream := cipher.NewCFBEncrypter(c.block, c.iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], payload)
c.incIV()
err := c.generateIV()
if err != nil {
return nil, err
}
c.hmac.Reset()
c.hmac.Write(ciphertext)
sum := c.hmac.Sum(nil)
Expand Down Expand Up @@ -88,17 +92,12 @@ func (c *Crypt) Decrypt(payload []byte) ([]byte, error) {
return encryptedPayload, nil
}

func (c *Crypt) incIV() {
incBytes(c.iv)
}

func incBytes(b []byte) {
for i := 0; i < len(b); i++ {
b[i]++
if b[i] != 0 {
break
}
func (c *Crypt) generateIV() error {
_, err := io.ReadFull(rand.Reader, c.iv)
if err != nil {
return fmt.Errorf("payloadcrypt: couldn't initialize IV: %v", err)
}
return nil
}

func passphraseToKey(passphrase []byte) []byte {
Expand Down
23 changes: 0 additions & 23 deletions payloadcrypt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,26 +40,3 @@ func TestEncryptDecrypt(t *testing.T) {
t.Error("Did not decrypt what was encrypted")
}
}

func TestIncBytes(t *testing.T) {
b := []byte{0, 1, 2, 3, 4, 5}
incBytes(b)
expected := []byte{1, 1, 2, 3, 4, 5}
if bytes.Compare(b, expected) != 0 {
t.Errorf("expected %v, got %v", expected, b)
}

b = []byte{255, 1, 2, 3, 4, 5}
incBytes(b)
expected = []byte{0, 2, 2, 3, 4, 5}
if bytes.Compare(b, expected) != 0 {
t.Errorf("expected %v, got %v", expected, b)
}

b = []byte{255, 255, 255, 255, 255, 255}
incBytes(b)
expected = []byte{0, 0, 0, 0, 0, 0}
if bytes.Compare(b, expected) != 0 {
t.Errorf("expected %v, got %v", expected, b)
}
}

0 comments on commit f8b93c8

Please sign in to comment.