Beispiel #1
0
 public override void Write(
     byte[]  buffer,
     int offset,
     int count)
 {
     if (outMac != null)
     {
         if (count > 0)
         {
             outMac.BlockUpdate(buffer, offset, count);
         }
     }
     stream.Write(buffer, offset, count);
 }
        public static byte[] GenerateHKDF(byte[] salt, byte[] ikm, byte[] info, int len)
        {
            IMac PRKGen = MacUtilities.GetMac("HmacSHA256");

            PRKGen.Init(new KeyParameter(MacUtilities.CalculateMac("HmacSHA256", new KeyParameter(salt), ikm)));
            PRKGen.BlockUpdate(info, 0, info.Length);
            PRKGen.Update((byte)1);
            byte[] Result = MacUtilities.DoFinal(PRKGen);
            if (Result.Length > len)
            {
                Array.Resize(ref Result, len);
            }
            return(Result);
        }
Beispiel #3
0
        /**
         * Calculate the MAC for some given data.
         *
         * @param type    The message type of the message.
         * @param message A byte-buffer containing the message.
         * @param offset  The number of bytes to skip, before the message starts.
         * @param length  The length of the message.
         * @return A new byte-buffer containing the MAC value.
         */
        public /*virtual */ BufferSegment CalculateMac(long seqNo, byte type, byte[] message, int offset, int length)
        {
            ProtocolVersion serverVersion = context.ServerVersion;
            bool            isSsl         = serverVersion.IsSsl;

            int macHeaderLength = isSsl ? 11 : 13;

            byte[] macHeader = BufferPool.Get(macHeaderLength, true);
            TlsUtilities.WriteUint64(seqNo, macHeader, 0);
            TlsUtilities.WriteUint8(type, macHeader, 8);
            if (!isSsl)
            {
                TlsUtilities.WriteVersion(serverVersion, macHeader, 9);
            }
            TlsUtilities.WriteUint16(length, macHeader, macHeaderLength - 2);

            mac.BlockUpdate(macHeader, 0, macHeaderLength);
            mac.BlockUpdate(message, offset, length);

            BufferPool.Release(macHeader);

            return(Truncate(MacUtilities.DoFinalOptimized(mac)));
        }
Beispiel #4
0
        private static void XTest(string mechanism, IMac digest, byte[] test)
        {
            byte[] hash1 = new byte[digest.GetMacSize()];
            byte[] hash2 = new byte[digest.GetMacSize()];
            digest.BlockUpdate(test, 0, test.Length);
            digest.DoFinal(hash1, 0);
            digest.BlockUpdate(test, 0, test.Length);
            digest.DoFinal(hash2, 0);
            bool diff = !StructuralComparisons.StructuralEqualityComparer.Equals(hash2, hash1);

            Console.Write("{0}{1} hash {2} bits - ", mechanism.PadRight(32), digest.AlgorithmName.PadRight(32), hash1.Length * 8);
            if (diff)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("diff");
                _diff++;
                Console.ResetColor();
            }
            else
            {
                Console.WriteLine("same");
            }
        }
Beispiel #5
0
        private void aliasTest(
            KeyParameter key,
            string primary,
            params string[] aliases)
        {
            IMac mac = MacUtilities.GetMac(primary);

            //
            // standard DAC - zero IV
            //
            mac.Init(key);

            mac.BlockUpdate(input, 0, input.Length);

            byte[] refBytes = new byte[mac.GetMacSize()];
            mac.DoFinal(refBytes, 0);

            for (int i = 0; i != aliases.Length; i++)
            {
                mac = MacUtilities.GetMac(aliases[i]);

                mac.Init(key);

                mac.BlockUpdate(input, 0, input.Length);

                byte[] outBytes = new byte[mac.GetMacSize()];
                mac.DoFinal(outBytes, 0);

                if (!AreEqual(outBytes, refBytes))
                {
                    Fail("Failed - expected "
                         + Hex.ToHexString(refBytes) + " got "
                         + Hex.ToHexString(outBytes));
                }
            }
        }
        /// <summary>
        /// Method to check if the mic is valid
        /// </summary>
        /// <param name="nwskey">the network security key</param>
        /// <returns></returns>
        public bool CheckMic(string nwskey)
        {
            IMac         mac = MacUtilities.GetMac("AESCMAC");
            KeyParameter key = new KeyParameter(StringToByteArray(nwskey));

            mac.Init(key);
            byte[] block = { 0x49,                                                     0x00,                        0x00, 0x00, 0x00, (byte)this.payloadMessage.direction, (byte)(this.payloadMessage.devAddr[3]), (byte)(payloadMessage.devAddr[2]), (byte)(payloadMessage.devAddr[1]),
                             (byte)(payloadMessage.devAddr[0]), this.payloadMessage.fcnt[0], this.payloadMessage.fcnt[1], 0x00, 0x00,                                0x00, (byte)(this.payloadMessage.rawMessage.Length - 4) };
            var    algoinput = block.Concat(this.payloadMessage.rawMessage.Take(this.payloadMessage.rawMessage.Length - 4)).ToArray();

            byte[] result = new byte[16];
            mac.BlockUpdate(algoinput, 0, algoinput.Length);
            result = MacUtilities.DoFinal(mac);
            return(this.payloadMessage.mic.SequenceEqual(result.Take(4).ToArray()));
        }
        /// <summary>
        /// A Method to calculate the Mic of the message
        /// </summary>
        /// <returns> the Mic bytes</returns>
        public byte[] CalculateMic(string appKey, byte[] algoinput)
        {
            IMac         mac = MacUtilities.GetMac("AESCMAC");
            KeyParameter key = new KeyParameter(ConversionHelper.StringToByteArray(appKey));

            mac.Init(key);
            byte[] rfu = new byte[1];
            rfu[0] = 0x0;
            byte[] msgLength = BitConverter.GetBytes(algoinput.Length);
            byte[] result    = new byte[16];
            mac.BlockUpdate(algoinput, 0, algoinput.Length);
            result   = MacUtilities.DoFinal(mac);
            this.Mic = result.Take(4).ToArray();
            return(this.Mic.ToArray());
        }
        private void F(
            byte[] P,
            byte[] S,
            int c,
            byte[] iBuf,
            byte[] outBytes,
            int outOff)
        {
            byte[]            state = new byte[hMac.GetMacSize()];
            ICipherParameters param = new KeyParameter(P);

            hMac.Init(param);

            if (S != null)
            {
                hMac.BlockUpdate(S, 0, S.Length);
            }

            hMac.BlockUpdate(iBuf, 0, iBuf.Length);

            hMac.DoFinal(state, 0);

            Array.Copy(state, 0, outBytes, outOff, state.Length);

            for (int count = 1; count != c; count++)
            {
                hMac.Init(param);
                hMac.BlockUpdate(state, 0, state.Length);
                hMac.DoFinal(state, 0);

                for (int j = 0; j != state.Length; j++)
                {
                    outBytes[outOff + j] ^= state[j];
                }
            }
        }
Beispiel #9
0
        public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len)
        {
            if (null == inBytes)
            {
                throw new ArgumentNullException("inBytes");
            }
            if (inOff < 0)
            {
                throw new ArgumentException("cannot be negative", "inOff");
            }
            if (len < 0)
            {
                throw new ArgumentException("cannot be negative", "len");
            }
            Check.DataLength(inBytes, inOff, len, "input buffer too short");

            CheckAad();

            if (len > 0)
            {
                this.mAadCount = IncrementCount(mAadCount, (uint)len, AadLimit);
                mPoly1305.BlockUpdate(inBytes, inOff, len);
            }
        }
Beispiel #10
0
        public override int Read(
            byte[]  buffer,
            int offset,
            int count)
        {
            int n = stream.Read(buffer, offset, count);

            if (inMac != null)
            {
                if (n > 0)
                {
                    inMac.BlockUpdate(buffer, offset, n);
                }
            }
            return(n);
        }
Beispiel #11
0
        public void SetMic(string nwskey)
        {
            rawMessage = this.ToMessage();
            IMac         mac = MacUtilities.GetMac("AESCMAC");
            KeyParameter key = new KeyParameter(StringToByteArray(nwskey));

            mac.Init(key);
            byte[] block = { 0x49,                  0x00,    0x00, 0x00, 0x00, (byte)direction, (byte)(devAddr[3]), (byte)(devAddr[2]), (byte)(devAddr[1]),
                             (byte)(devAddr[0]), fcnt[0], fcnt[1], 0x00, 0x00,            0x00, (byte)(rawMessage.Length) };
            var    algoinput = block.Concat(rawMessage.Take(rawMessage.Length)).ToArray();

            byte[] result = new byte[16];
            mac.BlockUpdate(algoinput, 0, algoinput.Length);
            result = MacUtilities.DoFinal(mac);
            mic    = result.Take(4).ToArray();
        }
Beispiel #12
0
        private byte[] CalculateDesMac(byte[] input, byte[] icv, int macType = 0)
        {
            if (icv == null)
            {
                icv = new byte[8];
            }

            IMac mac = null;

            switch (macType)
            {
            case 0:
                mac = MacUtilities.GetMac("DESEDEMAC64");
                //mac = new ISO9797Alg3Mac(new DesEngine());
                //mac = MacUtilities.GetMac("DESWITHISO9797");
                break;

            case 1:
                mac = MacUtilities.GetMac("DESEDEMAC64WITHISO7816-4PADDING");
                break;

            case 2:
                //mac = MacUtilities.GetMac("DESMAC");
                mac = MacUtilities.GetMac("ISO9797ALG3WITHISO7816-4PADDING");
                break;

            case 3:
                //mac = MacUtilities.GetMac("DESMAC/CFB8");
                mac = MacUtilities.GetMac("DESWITHISO9797");
                break;
            } //switch(macType)

            mac.Init(new KeyParameter(theKey));

            mac.BlockUpdate(input, 0, input.Length);

            byte[] result = new byte[8];
            int    outL   = mac.DoFinal(result, 0);

            if (outL > 0)
            {
                log.Debug(outL.ToString());
            }


            return(result);
        } //private byte[] CalculateDesMac(byte[] input, byte[] icv)
Beispiel #13
0
        private byte[] PerformMic(string appKey)
        {
            IMac mac = MacUtilities.GetMac("AESCMAC");

            KeyParameter key = new KeyParameter(ConversionHelper.StringToByteArray(appKey));

            mac.Init(key);

            var algoinput = Mhdr.ToArray().Concat(AppEUI.ToArray()).Concat(DevEUI.ToArray()).Concat(DevNonce.ToArray()).ToArray();

            byte[] result = new byte[19];
            mac.BlockUpdate(algoinput, 0, algoinput.Length);
            result = MacUtilities.DoFinal(mac);
            var resStr = BitConverter.ToString(result);

            return(result.Take(4).ToArray());
        }
Beispiel #14
0
        public byte[] Compute()
        {
            byte[] key = Encoding.Default.GetBytes(txtKey.Text);

            byte[] input = Encoding.Default.GetBytes(txtInput.Text);

            _mac.Reset();

            _mac.Init(new KeyParameter(key));

            byte[] result = new byte[_mac.GetMacSize()];

            _mac.BlockUpdate(input, 0, input.Length);

            _mac.DoFinal(result, 0);

            return(Result = result);
        }
Beispiel #15
0
        /// <summary>
        /// Method to check if the mic is valid
        /// </summary>
        /// <param name="nwskey">the network security key</param>
        /// <returns>if the Mic is valid or not</returns>
        public override bool CheckMic(string nwskey)
        {
            IMac         mac = MacUtilities.GetMac("AESCMAC");
            KeyParameter key = new KeyParameter(ConversionHelper.StringToByteArray(nwskey));

            mac.Init(key);
            byte[] block =
            {
                0x49,                          0x00,         0x00, 0x00, 0x00, (byte)Direction, (byte)DevAddr.Span[3], (byte)DevAddr.Span[2], (byte)DevAddr.Span[1],
                (byte)DevAddr.Span[0], Fcnt.Span[0], Fcnt.Span[1], 0x00, 0x00,            0x00, (byte)(RawMessage.Length - 4)
            };
            var algoinput = block.Concat(RawMessage.Take(RawMessage.Length - 4)).ToArray();

            byte[] result = new byte[16];
            mac.BlockUpdate(algoinput, 0, algoinput.Length);
            result = MacUtilities.DoFinal(mac);
            return(Mic.ToArray().SequenceEqual(result.Take(4).ToArray()));
        }
Beispiel #16
0
		internal static byte[] CalculatePbeMac(
			DerObjectIdentifier	oid,
			byte[]				salt,
			int					itCount,
			char[]				password,
			bool				wrongPkcs12Zero,
			byte[]				data)
		{
			Asn1Encodable asn1Params = PbeUtilities.GenerateAlgorithmParameters(
				oid, salt, itCount);
			ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(
				oid, password, wrongPkcs12Zero, asn1Params);

			IMac mac = (IMac) PbeUtilities.CreateEngine(oid);
			mac.Init(cipherParams);
			mac.BlockUpdate(data, 0, data.Length);
			return MacUtilities.DoFinal(mac);
		}
        public virtual void Init(bool forEncryption, ICipherParameters parameters)
        {
            //IL_007e: Unknown result type (might be due to invalid IL or missing references)
            this.forEncryption = forEncryption;
            byte[]            array;
            ICipherParameters parameters2;

            if (parameters is AeadParameters)
            {
                AeadParameters aeadParameters = (AeadParameters)parameters;
                array = aeadParameters.GetNonce();
                initialAssociatedText = aeadParameters.GetAssociatedText();
                macSize     = aeadParameters.MacSize / 8;
                parameters2 = aeadParameters.Key;
            }
            else
            {
                if (!(parameters is ParametersWithIV))
                {
                    throw new ArgumentException("invalid parameters passed to EAX");
                }
                ParametersWithIV parametersWithIV = (ParametersWithIV)parameters;
                array = parametersWithIV.GetIV();
                initialAssociatedText = null;
                macSize     = mac.GetMacSize() / 2;
                parameters2 = parametersWithIV.Parameters;
            }
            bufBlock = new byte[forEncryption ? blockSize : (blockSize + macSize)];
            byte[] array2 = new byte[blockSize];
            mac.Init(parameters2);
            array2[blockSize - 1] = 0;
            mac.BlockUpdate(array2, 0, blockSize);
            mac.BlockUpdate(array, 0, array.Length);
            mac.DoFinal(nonceMac, 0);
            cipher.Init(forEncryption: true, new ParametersWithIV(null, nonceMac));
            Reset();
        }
Beispiel #18
0
        public virtual byte[] Encrypt(string originStr)
        {
            if (string.IsNullOrWhiteSpace(originStr))
            {
                return(null);
            }

            var  originbytes = Encoding.UTF8.GetBytes(originStr);
            IMac mac         = MacUtilities.GetMac(AlgorithmName);

            mac.Init(Parameters);
            mac.BlockUpdate(originbytes, 0, originbytes.Length);

            var encryptBytes = new byte[mac.GetMacSize()];

            mac.DoFinal(encryptBytes, 0);

            return(encryptBytes);
        }
Beispiel #19
0
        public static byte[] ComputeMac(IMac mac, Stream s)
        {
            if (mac == null)
            {
                return(null);
            }

            byte[] buffer = new byte[512];
            byte[] result = new byte[mac.GetMacSize()];
            int    bytesRead;

            while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
            {
                mac.BlockUpdate(buffer, 0, bytesRead);
            }

            mac.DoFinal(result, 0);
            return(result);
        }
Beispiel #20
0
        public string PubnubAccessManagerSign(string key, string data)
        {
            string secret  = key;
            string message = data;

            var encoding = new System.Text.UTF8Encoding();

            byte[] keyByte      = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);

#if NETFX_CORE
            var     hmacsha256      = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
            IBuffer valueBuffer     = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8);
            IBuffer buffKeyMaterial = CryptographicBuffer.ConvertStringToBinary(secret, BinaryStringEncoding.Utf8);

            CryptographicKey cryptographicKey = hmacsha256.CreateKey(buffKeyMaterial);

            // Sign the key and message together.
            IBuffer bufferProtected = CryptographicEngine.Sign(cryptographicKey, valueBuffer);

            DataReader dataReader  = DataReader.FromBuffer(bufferProtected);
            byte[]     hashmessage = new byte[bufferProtected.Length];
            dataReader.ReadBytes(hashmessage);

            return(Convert.ToBase64String(hashmessage).Replace('+', '-').Replace('/', '_'));
#elif (WindowsCE || PocketPC)
            //http://mycsharp.de/wbb2/thread.php?postid=3550104
            KeyParameter paramKey = new KeyParameter(keyByte);
            IMac         mac      = MacUtilities.GetMac("HMac-SHA256");
            mac.Init(paramKey);
            mac.Reset();
            mac.BlockUpdate(messageBytes, 0, messageBytes.Length);
            byte[] hashmessage = new byte[mac.GetMacSize()];
            mac.DoFinal(hashmessage, 0);
            return(Convert.ToBase64String(hashmessage).Replace('+', '-').Replace('/', '_'));
#else
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return(Convert.ToBase64String(hashmessage).Replace('+', '-').Replace('/', '_'));
            }
#endif
        }
        public override bool CheckMic(string AppKey)
        {
            //appEUI = StringToByteArray("526973696E674846");
            IMac mac = MacUtilities.GetMac("AESCMAC");

            KeyParameter key = new KeyParameter(StringToByteArray(AppKey));

            mac.Init(key);

            byte[] tmp       = new byte[0];
            var    algoinput = tmp.Concat(mhdr.ToArray()).Concat(appEUI).Concat(devEUI).Concat(devNonce).ToArray();

            byte[] result = new byte[19];
            mac.BlockUpdate(algoinput, 0, algoinput.Length);
            result = MacUtilities.DoFinal(mac);
            var resStr = BitConverter.ToString(result);

            return(mic.ToArray().SequenceEqual(result.Take(4).ToArray()));
        }
Beispiel #22
0
        public string PubnubAccessManagerSign(string key, string data)
        {
            string secret  = key;
            string message = data;

            var encoding = new System.Text.UTF8Encoding();

            byte[] keyByte      = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);

            //http://mycsharp.de/wbb2/thread.php?postid=3550104
            KeyParameter paramKey = new KeyParameter(keyByte);
            IMac         mac      = MacUtilities.GetMac("HMac-SHA256");

            mac.Init(paramKey);
            mac.Reset();
            mac.BlockUpdate(messageBytes, 0, messageBytes.Length);
            byte[] hashmessage = new byte[mac.GetMacSize()];
            mac.DoFinal(hashmessage, 0);
            return(Convert.ToBase64String(hashmessage).Replace('+', '-').Replace('/', '_'));
        }
Beispiel #23
0
        public void SetMic(string nwskey)
        {
            var          byteMsg = this.GetByteMessage();
            IMac         mac     = MacUtilities.GetMac("AESCMAC");
            KeyParameter key     = new KeyParameter(ConversionHelper.StringToByteArray(nwskey));

            mac.Init(key);
            byte[] block =
            {
                0x49,                          0x00,         0x00, 0x00, 0x00, (byte)Direction, (byte)DevAddr.Span[3], (byte)DevAddr.Span[2], (byte)DevAddr.Span[1],
                (byte)DevAddr.Span[0], Fcnt.Span[0], Fcnt.Span[1], 0x00, 0x00,            0x00, (byte)byteMsg.Length
            };
            var algoinput = block.Concat(byteMsg.Take(byteMsg.Length)).ToArray();

            byte[] result = new byte[16];
            mac.BlockUpdate(algoinput, 0, algoinput.Length);
            result = MacUtilities.DoFinal(mac);
            var res = result.Take(4).ToArray();

            Array.Copy(result.Take(4).ToArray(), 0, RawMessage, RawMessage.Length - 4, 4);
            Mic = new Memory <byte>(RawMessage, RawMessage.Length - 4, 4);
        }
Beispiel #24
0
 public static byte[] DoFinal(IMac mac, byte[] input)
 {
     mac.BlockUpdate(input, 0, input.Length);
     return(DoFinal(mac));
 }
 public static void Update(this IMac hmac, byte[] input)
 {
     hmac.BlockUpdate(input, 0, input.Length);
 }
Beispiel #26
0
 private static void UpdateMac(IMac mac, byte[] bytes)
 {
     mac.BlockUpdate(bytes, 0, bytes.Length);
     Arrays.Fill(bytes, (byte)0);
 }
        protected virtual void UpdateRecordMac(IMac mac, byte[] buf, int off, int len)
        {
            mac.BlockUpdate(buf, off, len);

            byte[] longLen = Pack.UInt64_To_LE((ulong)len);
            mac.BlockUpdate(longLen, 0, longLen.Length);
        }
Beispiel #28
0
 public static byte[] DoFinal(IMac mac, byte[] input)
 {
     mac.BlockUpdate(input, 0, input.Length);
     return DoFinal(mac);
 }
Beispiel #29
0
 public override void Write(byte[] b, int off, int len)
 {
     mac.BlockUpdate(b, off, len);
 }
Beispiel #30
0
 public void BlockUpdate(byte[] input, int inOff, int length)
 {
     _hash.BlockUpdate(input, inOff, length);
 }
 private static void UpdateMac(IMac mac, byte[] bytes)
 {
     mac.BlockUpdate(bytes, 0, bytes.Length);
     Arrays.Fill(bytes, (byte)0);
 }
Beispiel #32
0
		private void testMultibyte(IMac mac, TestCase testCase)
		{
			mac.BlockUpdate(testCase.getAd(), 0, testCase.getAd().Length);
			checkMac(mac, testCase);
		}
Beispiel #33
0
        public override void PerformTest()
        {
//			Mac mac = Mac.getInstance("AESCMAC", "BC");
            IMac mac = MacUtilities.GetMac("AESCMAC");

            //128 bytes key

//			SecretKeySpec key = new SecretKeySpec(keyBytes128, "AES");
            KeyParameter key = new KeyParameter(keyBytes128);

            // 0 bytes message - 128 bytes key
            mac.Init(key);

            mac.BlockUpdate(input0, 0, input0.Length);

            byte[] output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_k128_m0))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_k128_m0)
                     + " got " + Hex.ToHexString(output));
            }

            // 16 bytes message - 128 bytes key
            mac.Init(key);

            mac.BlockUpdate(input16, 0, input16.Length);

            output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_k128_m16))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_k128_m16)
                     + " got " + Hex.ToHexString(output));
            }

            // 40 bytes message - 128 bytes key
            mac.Init(key);

            mac.BlockUpdate(input40, 0, input40.Length);

            output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_k128_m40))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_k128_m40)
                     + " got " + Hex.ToHexString(output));
            }

            // 64 bytes message - 128 bytes key
            mac.Init(key);

            mac.BlockUpdate(input64, 0, input64.Length);

            output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_k128_m64))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_k128_m64)
                     + " got " + Hex.ToHexString(output));
            }

            //192 bytes key

//			key = new SecretKeySpec(keyBytes192, "AES");
            key = new KeyParameter(keyBytes192);

            // 0 bytes message - 192 bytes key
            mac.Init(key);

            mac.BlockUpdate(input0, 0, input0.Length);

            output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_k192_m0))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_k192_m0)
                     + " got " + Hex.ToHexString(output));
            }

            // 16 bytes message - 192 bytes key
            mac.Init(key);

            mac.BlockUpdate(input16, 0, input16.Length);

            output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_k192_m16))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_k192_m16)
                     + " got " + Hex.ToHexString(output));
            }

            // 40 bytes message - 192 bytes key
            mac.Init(key);

            mac.BlockUpdate(input40, 0, input40.Length);

            output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_k192_m40))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_k192_m40)
                     + " got " + Hex.ToHexString(output));
            }

            // 64 bytes message - 192 bytes key
            mac.Init(key);

            mac.BlockUpdate(input64, 0, input64.Length);

            output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_k192_m64))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_k192_m64)
                     + " got " + Hex.ToHexString(output));
            }

            //256 bytes key

//			key = new SecretKeySpec(keyBytes256, "AES");
            key = new KeyParameter(keyBytes256);

            // 0 bytes message - 256 bytes key
            mac.Init(key);

            mac.BlockUpdate(input0, 0, input0.Length);

            output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_k256_m0))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_k256_m0)
                     + " got " + Hex.ToHexString(output));
            }

            // 16 bytes message - 256 bytes key
            mac.Init(key);

            mac.BlockUpdate(input16, 0, input16.Length);

            output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_k256_m16))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_k256_m16)
                     + " got " + Hex.ToHexString(output));
            }

            // 40 bytes message - 256 bytes key
            mac.Init(key);

            mac.BlockUpdate(input40, 0, input40.Length);

            output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_k256_m40))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_k256_m40)
                     + " got " + Hex.ToHexString(output));
            }

            // 64 bytes message - 256 bytes key
            mac.Init(key);

            mac.BlockUpdate(input64, 0, input64.Length);

            output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_k256_m64))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_k256_m64)
                     + " got " + Hex.ToHexString(output));
            }

//			mac = Mac.getInstance("DESedeCMAC", "BC");
            mac = MacUtilities.GetMac("DESedeCMAC");

            //DESede

//			key = new SecretKeySpec(keyBytes128, "DESede");
            key = new KeyParameter(keyBytes128);

            // 0 bytes message - 128 bytes key
            mac.Init(key);

            mac.BlockUpdate(input0, 0, input0.Length);

            output = MacUtilities.DoFinal(mac);

            if (!AreEqual(output, output_des_ede))
            {
                Fail("Failed - expected " + Hex.ToHexString(output_des_ede)
                     + " got " + Hex.ToHexString(output));
            }
        }
Beispiel #34
0
 protected virtual void UpdateRecordMacLength(IMac mac, int len)
 {
     byte[] longLen = Pack.UInt64_To_LE((ulong)len);
     mac.BlockUpdate(longLen, 0, longLen.Length);
 }
Beispiel #35
0
        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);

            // Ensure that the length of the input is greater than the MAC in bytes
            if (inLen < mac.GetMacSize())
            {
                throw new InvalidCipherTextException("Length of input must be greater than the MAC");
            }

            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);
        }
Beispiel #36
0
        protected virtual void UpdateRecordMacText(IMac mac, byte[] buf, int off, int len)
        {
            mac.BlockUpdate(buf, off, len);

            int partial = len % 16;
            if (partial != 0)
            {
                mac.BlockUpdate(Zeroes, 0, 16 - partial);
            }
        }