private void randomTest( SecureRandom srng, IGcmMultiplier m) { int kLength = 16 + 8 * srng.Next(3); byte[] K = new byte[kLength]; srng.NextBytes(K); int pLength = srng.Next(1024); byte[] P = new byte[pLength]; srng.NextBytes(P); int aLength = srng.Next(1024); byte[] A = new byte[aLength]; srng.NextBytes(A); int ivLength = 1 + srng.Next(1024); byte[] IV = new byte[ivLength]; srng.NextBytes(IV); GcmBlockCipher cipher = new GcmBlockCipher(new AesFastEngine(), m); AeadParameters parameters = new AeadParameters(new KeyParameter(K), 16 * 8, IV, A); cipher.Init(true, parameters); byte[] C = new byte[cipher.GetOutputSize(P.Length)]; int len = cipher.ProcessBytes(P, 0, P.Length, C, 0); len += cipher.DoFinal(C, len); if (C.Length != len) { // Console.WriteLine("" + C.Length + "/" + len); Fail("encryption reported incorrect length in randomised test"); } byte[] encT = cipher.GetMac(); byte[] tail = new byte[C.Length - P.Length]; Array.Copy(C, P.Length, tail, 0, tail.Length); if (!AreEqual(encT, tail)) { Fail("stream contained wrong mac in randomised test"); } cipher.Init(false, parameters); byte[] decP = new byte[cipher.GetOutputSize(C.Length)]; len = cipher.ProcessBytes(C, 0, C.Length, decP, 0); len += cipher.DoFinal(decP, len); if (!AreEqual(P, decP)) { Fail("incorrect decrypt in randomised test"); } byte[] decT = cipher.GetMac(); if (!AreEqual(encT, decT)) { Fail("decryption produced different mac from encryption"); } }
private void checkTestCase( GcmBlockCipher encCipher, GcmBlockCipher decCipher, string testName, byte[] P, byte[] C, byte[] T) { byte[] enc = new byte[encCipher.GetOutputSize(P.Length)]; int len = encCipher.ProcessBytes(P, 0, P.Length, enc, 0); len += encCipher.DoFinal(enc, len); if (enc.Length != len) { // Console.WriteLine("" + enc.Length + "/" + len); Fail("encryption reported incorrect length: " + testName); } byte[] mac = encCipher.GetMac(); byte[] data = new byte[P.Length]; Array.Copy(enc, data, data.Length); byte[] tail = new byte[enc.Length - P.Length]; Array.Copy(enc, P.Length, tail, 0, tail.Length); if (!AreEqual(C, data)) { Fail("incorrect encrypt in: " + testName); } if (!AreEqual(T, mac)) { Fail("GetMac() returned wrong mac in: " + testName); } if (!AreEqual(T, tail)) { Fail("stream contained wrong mac in: " + testName); } byte[] dec = new byte[decCipher.GetOutputSize(enc.Length)]; len = decCipher.ProcessBytes(enc, 0, enc.Length, dec, 0); len += decCipher.DoFinal(dec, len); mac = decCipher.GetMac(); data = new byte[C.Length]; Array.Copy(dec, data, data.Length); if (!AreEqual(P, data)) { Fail("incorrect decrypt in: " + testName); } }