Skip to content

Commit

Permalink
factor out aes params validation
Browse files Browse the repository at this point in the history
  • Loading branch information
qmuntal committed Sep 29, 2024
1 parent c3f8deb commit e26c51c
Showing 1 changed file with 15 additions and 20 deletions.
35 changes: 15 additions & 20 deletions cng/aes.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,27 @@ func (c *aesCipher) finalize() {

func (c *aesCipher) BlockSize() int { return aesBlockSize }

func (c *aesCipher) Encrypt(dst, src []byte) {
// validateAndClipInputs checks that dst and src meet the [cipher.Block]
// interface requirements and clips them to a single block.
func (c *aesCipher) validateAndClipInputs(dst, src []byte) (d, s []byte) {
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")
// cypher.Block methods are documented to operate on
// one block at a time, so we truncate the input and output
// to the block size.
d, s = dst[:aesBlockSize], src[:aesBlockSize]
if subtle.InexactOverlap(d, s) {
panic("crypto/aes: invalid buffer overlap")
}
return d, s
}

func (c *aesCipher) Encrypt(dst, src []byte) {
dst, src = c.validateAndClipInputs(dst, src)

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

func (c *aesCipher) Decrypt(dst, src []byte) {
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")
}
dst, src = c.validateAndClipInputs(dst, src)

var ret uint32
err := bcrypt.Decrypt(c.kh, src, nil, nil, dst, &ret, 0)
Expand Down

0 comments on commit e26c51c

Please sign in to comment.