bc-java icon indicating copy to clipboard operation
bc-java copied to clipboard

CCMBlockCipher mac doesn't match

Open campbellwray opened this issue 9 years ago • 1 comments

From my understanding, I should be able to encrypt a byte array with this cipher and use the mac to validate that it decrypted properly (or something along those lines).

This is done by reading the last macSize/8 bytes of the encrypted data, to cipher.getMac() after decryption, however this is not the case.

The code I am using is as follows:

CCMBlockCipher cipher = new CCMBlockCipher(new AESEngine());
CipherParameters params = new AEADParameters(key, 32, nonce, null); 
//encrypt
cipher.init(true, params);	
byte [] encryptedBytes = new byte[cipher.getOutputSize(input.length)];
int bytesWritten = cipher.processBytes(input, 0, input.length, encryptedBytes, 0);
cipher.doFinal(encryptedBytes, bytesWritten);

//decrypt
cipher.reset();
cipher.init(false, params);		
byte [] decryptedBytes = new byte[cipher.getOutputSize(encryptedBytes.length)];
int bytesWritten2 = cipher.processBytes(encryptedBytes, 0, encryptedBytes.length, decryptedBytes, 0);
cipher.doFinal(decryptedBytes, bytesWritten2);

When comparing the last 4 bytes to cipher.getMac(), the last 4 bytes are: 0xff138354 Whereas cipher.getMac() returns: 0x9f450151

Clearly these don't match, the payload however, is fine.

It is possible that I am implementing the cipher wrong but what I have done looks correct based on the BC documentation.

campbellwray avatar Jun 12 '17 06:06 campbellwray

It is important to remember that the MAC is encrypted when it is presented in the cipher output.

ghost avatar Jun 20 '17 23:06 ghost