Skip to content

Commit

Permalink
aes: encrypt and decrypt one block at a time
Browse files Browse the repository at this point in the history
  • Loading branch information
qmuntal committed Sep 27, 2024
1 parent fde8545 commit b0dfd48
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
21 changes: 15 additions & 6 deletions cng/aes.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,20 @@ func (c *aesCipher) finalize() {
func (c *aesCipher) BlockSize() int { return aesBlockSize }

func (c *aesCipher) Encrypt(dst, src []byte) {
if subtle.InexactOverlap(dst, src) {
panic("crypto/cipher: invalid buffer overlap")
}
if len(src) < aesBlockSize {
panic("crypto/aes: input not full block")
}
if len(dst) < aesBlockSize {
panic("crypto/aes: output not full block")
}

// cypher.Block.Encrypt() is documented to encrypt one full block
// at a time, so we truncate the input and output to the block size.
dst, src = dst[:aesBlockSize], src[:aesBlockSize]
if subtle.InexactOverlap(dst, src) {
panic("crypto/cipher: invalid buffer overlap")
}

var ret uint32
err := bcrypt.Encrypt(c.kh, src, nil, nil, dst, &ret, 0)
if err != nil {
Expand All @@ -62,16 +67,20 @@ func (c *aesCipher) Encrypt(dst, src []byte) {
}

func (c *aesCipher) Decrypt(dst, src []byte) {
if subtle.InexactOverlap(dst, src) {
panic("crypto/cipher: invalid buffer overlap")
}
if len(src) < aesBlockSize {
panic("crypto/aes: input not full block")
}
if len(dst) < aesBlockSize {
panic("crypto/aes: output not full block")
}

// cypher.Block.Decrypt() is documented to decrypt one full block
// at a time, so we truncate the input and output to the block size.
dst, src = dst[:aesBlockSize], src[:aesBlockSize]
if subtle.InexactOverlap(dst, src) {
panic("crypto/cipher: invalid buffer overlap")
}

var ret uint32
err := bcrypt.Decrypt(c.kh, src, nil, nil, dst, &ret, 0)
if err != nil {
Expand Down
12 changes: 12 additions & 0 deletions cng/aes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ package cng
import (
"bytes"
"crypto/cipher"
"fmt"
"testing"

"github.com/microsoft/go-crypto-winnative/internal/cryptotest"
)

var key = []byte("D249BF6DEC97B1EBD69BC4D6B3A3C49D")
Expand Down Expand Up @@ -375,3 +378,12 @@ func TestCBCDecryptSimple(t *testing.T) {
t.Errorf("decryption incorrect\nexp %v, got %v\n", plainText, decrypted)
}
}

// Test AES against the general cipher.Block interface tester.
func TestAESBlock(t *testing.T) {
for _, keylen := range []int{128, 192, 256} {
t.Run(fmt.Sprintf("AES-%d", keylen), func(t *testing.T) {
cryptotest.TestBlock(t, keylen/8, NewAESCipher)
})
}
}

0 comments on commit b0dfd48

Please sign in to comment.