contentenc: deduplicate AD packing into new concatAD() func

The encrypt and decrypt path both had a copy that were equivalent
but ordered differently, which was confusing.

Consolidate it in a new dedicated function.
This commit is contained in:
Jakob Unterwurzacher 2017-09-17 11:21:48 +02:00
parent 4bd2c6736a
commit 885fdcabda
1 changed files with 18 additions and 6 deletions

View File

@ -121,6 +121,22 @@ func (be *ContentEnc) DecryptBlocks(ciphertext []byte, firstBlockNo uint64, file
return pBuf.Bytes(), err return pBuf.Bytes(), err
} }
// concatAD concatenates the block number and the file ID to a byte blob
// that can be passed to AES-GCM as associated data (AD).
// Result is: aData = blockNo.bigEndian + fileID.
func concatAD(blockNo uint64, fileID []byte) (aData []byte) {
if fileID != nil && len(fileID) != headerIDLen {
// fileID is nil when decrypting the master key from the config file
log.Panicf("wrong fileID length: %d", len(fileID))
}
const lenUint64 = 8
// Preallocate space to save an allocation in append()
aData = make([]byte, lenUint64, lenUint64+headerIDLen)
binary.BigEndian.PutUint64(aData, blockNo)
aData = append(aData, fileID...)
return aData
}
// DecryptBlock - Verify and decrypt GCM block // DecryptBlock - Verify and decrypt GCM block
// //
// Corner case: A full-sized block of all-zero ciphertext bytes is translated // Corner case: A full-sized block of all-zero ciphertext bytes is translated
@ -157,9 +173,7 @@ func (be *ContentEnc) DecryptBlock(ciphertext []byte, blockNo uint64, fileID []b
// Decrypt // Decrypt
plaintext := be.pBlockPool.Get() plaintext := be.pBlockPool.Get()
plaintext = plaintext[:0] plaintext = plaintext[:0]
aData := make([]byte, 8) aData := concatAD(blockNo, fileID)
aData = append(aData, fileID...)
binary.BigEndian.PutUint64(aData, blockNo)
plaintext, err := be.cryptoCore.AEADCipher.Open(plaintext, nonce, ciphertext, aData) plaintext, err := be.cryptoCore.AEADCipher.Open(plaintext, nonce, ciphertext, aData)
if err != nil { if err != nil {
@ -257,9 +271,7 @@ func (be *ContentEnc) doEncryptBlock(plaintext []byte, blockNo uint64, fileID []
log.Panic("wrong nonce length") log.Panic("wrong nonce length")
} }
// Block is authenticated with block number and file ID // Block is authenticated with block number and file ID
aData := make([]byte, 8) aData := concatAD(blockNo, fileID)
binary.BigEndian.PutUint64(aData, blockNo)
aData = append(aData, fileID...)
// Get a cipherBS-sized block of memory, copy the nonce into it and truncate to // Get a cipherBS-sized block of memory, copy the nonce into it and truncate to
// nonce length // nonce length
cBlock := be.cBlockPool.Get() cBlock := be.cBlockPool.Get()