private byte[] GenerateKdfBytes( KdfParameters kParam, int length) { byte[] buf = new byte[length]; kdf.Init(kParam); kdf.GenerateBytes(buf, 0, buf.Length); return buf; }
private byte[] DecryptBlock( byte[] in_enc, int inOff, int inLen, byte[] z) { byte[] M = null; KeyParameter macKey = null; KdfParameters kParam = new KdfParameters(z, param.GetDerivationV()); int macKeySize = param.MacKeySize; kdf.Init(kParam); inLen -= mac.GetMacSize(); if (cipher == null) // stream mode { byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8)); M = new byte[inLen]; for (int i = 0; i != inLen; i++) { M[i] = (byte)(in_enc[inOff + i] ^ Buffer[i]); } macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8)); } else { int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize; byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8)); cipher.Init(false, new KeyParameter(Buffer, 0, (cipherKeySize / 8))); M = cipher.DoFinal(in_enc, inOff, inLen); macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8)); } byte[] macIV = param.GetEncodingV(); mac.Init(macKey); mac.BlockUpdate(in_enc, inOff, inLen); mac.BlockUpdate(macIV, 0, macIV.Length); mac.DoFinal(macBuf, 0); inOff += inLen; byte[] T1 = Arrays.CopyOfRange(in_enc, inOff, inOff + macBuf.Length); if (!Arrays.ConstantTimeAreEqual(T1, macBuf)) throw (new InvalidCipherTextException("Invalid MAC.")); return M; }
private byte[] EncryptBlock( byte[] input, int inOff, int inLen, byte[] z) { byte[] C = null; KeyParameter macKey = null; KdfParameters kParam = new KdfParameters(z, param.GetDerivationV()); int c_text_length = 0; int macKeySize = param.MacKeySize; if (cipher == null) // stream mode { byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8)); C = new byte[inLen + mac.GetMacSize()]; c_text_length = inLen; for (int i = 0; i != inLen; i++) { C[i] = (byte)(input[inOff + i] ^ Buffer[i]); } macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8)); } else { int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize; byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8)); cipher.Init(true, new KeyParameter(Buffer, 0, (cipherKeySize / 8))); c_text_length = cipher.GetOutputSize(inLen); byte[] tmp = new byte[c_text_length]; int len = cipher.ProcessBytes(input, inOff, inLen, tmp, 0); len += cipher.DoFinal(tmp, len); C = new byte[len + mac.GetMacSize()]; c_text_length = len; Array.Copy(tmp, 0, C, 0, len); macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8)); } byte[] macIV = param.GetEncodingV(); mac.Init(macKey); mac.BlockUpdate(C, 0, c_text_length); mac.BlockUpdate(macIV, 0, macIV.Length); // // return the message and it's MAC // mac.DoFinal(C, c_text_length); return C; }