Example #1
0
        public byte[] Encrypt(byte[] plain, byte[] key, byte[] iv, byte[] aad = null, byte[] associated = null)
        {
            if (key.Length * 8 != this.KeySize)
            {
                throw new InvalidOperationException($"the given key has invalid size {key.Length * 8}, expect {this.KeySize}");
            }

            var cipher = new Modes.GcmBlockCipher(new Engines.AesEngine());

            cipher.Init(true, new Parameters.AeadParameters(new Parameters.KeyParameter(key), this.MacSize, iv, associated));

            if (aad != null)
            {
                cipher.ProcessAadBytes(aad, 0, aad.Length);
            }

            var ret = new byte[cipher.GetOutputSize(plain.Length)];
            var len = cipher.ProcessBytes(plain, 0, plain.Length, ret, 0);

            cipher.DoFinal(ret, len);

            return(ret);
        }
Example #2
0
        private void CheckTestCase(
            GcmBlockCipher	encCipher,
            GcmBlockCipher	decCipher,
            string			testName,
            byte[]          SA,
            byte[]          P,
            byte[]			C,
            byte[]			T)
        {
            byte[] enc = new byte[encCipher.GetOutputSize(P.Length)];
            if (SA != null)
            {
                encCipher.ProcessAadBytes(SA, 0, SA.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)];
            if (SA != null)
            {
                decCipher.ProcessAadBytes(SA, 0, SA.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);
            }
        }