I use AES CTR to encrypt our documents for now. This is done to provide ability to make range-requests to encrypted documents. With AES CTR it is possible to calculate IV for specific block by simple function like that:
private static int AES_BLOCK_SIZE = 16;
private static ParametersWithIV CalculateIvForOffset(KeyParameter sk, ParametersWithIV iv, long blockOffset)
{
var ivBI = new BigInteger(1, iv.GetIV());
var ivForOffsetBi = ivBI.Add(BigInteger.ValueOf(blockOffset/ AES_BLOCK_SIZE));
var ivForOffsetBA = ivForOffsetBi.ToByteArray();
ParametersWithIV ivForOffset;
if (ivForOffsetBA.Length >= AES_BLOCK_SIZE) {
ivForOffset = new ParametersWithIV(sk, ivForOffsetBA, ivForOffsetBA.Length - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
} else {
byte[] ivForOffsetBASized = new byte[AES_BLOCK_SIZE];
Array.Copy(ivForOffsetBA, 0, ivForOffsetBASized, AES_BLOCK_SIZE
- ivForOffsetBA.Length, ivForOffsetBA.Length);
ivForOffset = new ParametersWithIV(sk, ivForOffsetBASized);/**/
}
return ivForOffset;
}
I use BouncyCastle in my app. But in particular cases I need to track document integrity. And I want to use AES GCM for this purpose. However I still need ability to decipher particular block of data. Is it possible to calculate IV for specific position/block of GCM and how to do it?
Simplified code I use for encryption decryption is here:
var offset = 0;
var decryptionSize = 128;
var file = Hex.Decode("2B7E151628AED2A6ABF7158809CF4F3C12312312312312312312312312312312312391792837012937019238102938012938017230192830192830192830192730129730129830192380192730192730");
var encryptor = CipherUtilities.GetCipher("AES/GCM/NoPadding");
var sk = ParameterUtilities.CreateKeyParameter("AES", Hex.Decode("2B7E151628AED2A6ABF7158809CF4F3C"));
encryptor.Init(true, new ParametersWithIV(sk, Hex.Decode("F0F1F2F3F4F5F6F7F8F9FAFBFCFD0001")));
var encryptedFile = encryptor.DoFinal(file);
var decryptor = CipherUtilities.GetCipher("AES/GCM/NoPadding");
var arrayToDecrypt = encryptedFile.Skip(offset).Take(decryptionSize).ToArray();
// recalculate initial vector for offset
var newiv = CalculateIvForOffset(sk, new ParametersWithIV(sk, Hex.Decode("F0F1F2F3F4F5F6F7F8F9FAFBFCFD0001")),offset);
decryptor.Init(false, newiv);
var output2 = decryptor.ProcessBytes(arrayToDecrypt, 0, arrayToDecrypt.Length);
Thanks!