Esempio n. 1
0
        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()));
        }
Esempio n. 2
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
        }
Esempio n. 3
0
        private void doTestExceptions()
        {
            IMac mac = MacUtilities.GetMac("HmacSHA1");

            byte [] b = { (byte)1, (byte)2, (byte)3, (byte)4, (byte)5 };
//			KeyParameter sks = new KeyParameter(b); //, "HmacSHA1");
//			RC5ParameterSpec algPS = new RC5ParameterSpec(100, 100, 100);
            RC5Parameters rc5Parameters = new RC5Parameters(b, 100);

            try
            {
//				mac.Init(sks, algPS);
                mac.Init(rc5Parameters);
            }
//			catch (InvalidAlgorithmParameterException e)
            catch (Exception)
            {
                // ignore okay
            }

            try
            {
                mac.Init(null); //, null);
            }
//			catch (InvalidKeyException)
//			{
//				// ignore okay
//			}
//			catch (InvalidAlgorithmParameterException e)
            catch (Exception)
            {
                // ignore okay
            }

//			try
//			{
//				mac.Init(null);
//			}
//			catch (InvalidKeyException)
//			{
//				// ignore okay
//			}
        }
Esempio n. 4
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 byte[] CalculateMac(long seqNo, byte type, byte[] message, int offset, int length)
        {
            ProtocolVersion serverVersion = context.ServerVersion;
            bool            isSsl         = serverVersion.IsSsl;

            byte[] macHeader = new byte[isSsl ? 11 : 13];
            TlsUtilities.WriteUint64(seqNo, macHeader, 0);
            TlsUtilities.WriteUint8(type, macHeader, 8);
            if (!isSsl)
            {
                TlsUtilities.WriteVersion(serverVersion, macHeader, 9);
            }
            TlsUtilities.WriteUint16(length, macHeader, macHeader.Length - 2);

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

            return(Truncate(MacUtilities.DoFinal(mac)));
        }
Esempio n. 5
0
        /// <summary>
        /// A Method to calculate the Mic of the message
        /// </summary>
        /// <param name="nwskey">The Network Secret Key</param>
        /// <returns></returns>
        public byte[] CalculateMic(string appKey, byte [] algoinput)
        {
            IMac         mac = MacUtilities.GetMac("AESCMAC");
            KeyParameter key = new KeyParameter(StringToByteArray(appKey));

            mac.Init(key);
            byte[] rfu = new byte[1];
            rfu[0] = 0x0;
            //move


            byte[] msgLength = BitConverter.GetBytes(algoinput.Length);

            byte[] result = new byte[16];
            mac.BlockUpdate(algoinput, 0, algoinput.Length);
            result = MacUtilities.DoFinal(mac);
            mic    = result.Take(4).ToArray();
            return(mic);
        }
Esempio n. 6
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));
        }
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    macStream.Dispose();

                    // TODO Parent context(s) should really be be closed explicitly

                    eiGen.Close();

                    // [TODO] auth attributes go here
                    byte[] macOctets = MacUtilities.DoFinal(mac);
                    authGen.AddObject(new DerOctetString(macOctets));
                    // [TODO] unauth attributes go here

                    authGen.Close();
                    cGen.Close();
                }
            }
Esempio n. 8
0
        public void ComputeSignature(IMac macAlg)
        {
            if (macAlg == null)
            {
                throw new ArgumentNullException("macAlg");
            }

            string method = null;


            if (macAlg.AlgorithmName == MacUtilities.GetAlgorithmName(PkcsObjectIdentifiers.IdHmacWithSha1))
            {
                method = XmlDsigConstants.XmlDsigHMACSHA1Url;
            }
            else if (macAlg.AlgorithmName == MacUtilities.GetAlgorithmName(PkcsObjectIdentifiers.IdHmacWithSha256))
            {
                method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
            }
            else if (macAlg.AlgorithmName == MacUtilities.GetAlgorithmName(PkcsObjectIdentifiers.IdHmacWithSha384))
            {
                method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384";
            }
            else if (macAlg.AlgorithmName == MacUtilities.GetAlgorithmName(PkcsObjectIdentifiers.IdHmacWithSha512))
            {
                method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512";
            }

            /*
             * TODO: RIPEMD160 support
             * else if (macAlg.AlgorithmName == MacUtilities.GetAlgorithmName(PkcsObjectIdentifiers.)) {
             *                  method = "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160";
             *          }
             */

            if (method == null)
            {
                throw new CryptographicException("unsupported algorithm");
            }

            DigestReferences();
            m_signature.SignedInfo.SignatureMethod = method;
            m_signature.SignatureValue             = HMACHelpers.ComputeMac(macAlg, SignedInfoTransformed());
        }
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(macStream);

                    // TODO Parent context(s) should really be be closed explicitly

                    eiGen.Close();

                    // [TODO] auth attributes go here
                    byte[] macOctets = MacUtilities.DoFinal(mac);
                    authGen.AddObject(new DerOctetString(macOctets));
                    // [TODO] unauth attributes go here

                    authGen.Close();
                    cGen.Close();
                }
                base.Dispose(disposing);
            }
Esempio n. 10
0
        /// <summary>
        /// 哈希计算
        /// </summary>
        /// <param name="data">输入字符串</param>
        /// <param name="key">密钥KEY</param>
        /// <param name="algorithm">密文算法,参考Algorithms.cs中提供的HMac algorithm</param>
        /// <returns>哈希值</returns>
        public static byte[] Compute(string data, string key, string algorithm)
        {
            if (string.IsNullOrEmpty(data))
            {
                throw new ArgumentNullException(nameof(data));
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            var keyParameter = new Org.BouncyCastle.Crypto.Parameters.KeyParameter(Encoding.UTF8.GetBytes(key));
            var input        = Encoding.UTF8.GetBytes(data);
            var mac          = MacUtilities.GetMac(algorithm);

            mac.Init(keyParameter);
            mac.BlockUpdate(input, 0, input.Length);
            return(MacUtilities.DoFinal(mac));
        }
Esempio n. 11
0
        /// <summary>
        /// Calculate the signature of <paramref name="data"/>
        /// </summary>
        /// <param name="data">The data to sign</param>
        /// <param name="consumerSecret">The consumer secret</param>
        /// <param name="tokenSecret">The token secret</param>
        /// <returns>The signature</returns>
        public string CalculateSignature(byte[] data, string consumerSecret, string tokenSecret)
        {
            var key     = $"{consumerSecret}&{tokenSecret}";
            var keyData = _encoding.GetBytes(key);

#if USE_BOUNCYCASTLE
            var digest = new Sha1Digest();
            var crypto = new HMac(digest);
            crypto.Init(new KeyParameter(keyData));
            crypto.BlockUpdate(data, 0, data.Length);
            var hash = MacUtilities.DoFinal(crypto);
            return(System.Convert.ToBase64String(hash));
#else
            using (var digest = new HMACSHA1(keyData))
            {
                var hash = digest.ComputeHash(data);
                return(System.Convert.ToBase64String(hash));
            }
#endif
        }
        public void CanStretchKeysUsingBouncyCastle(string curve, string cipher, string hash)
        {
            var ekeypair1  = EphemeralKeyPair.Generate(curve);
            var ekeypair2  = EphemeralKeyPair.Generate(curve);
            var secret1    = ekeypair1.GenerateSharedKey(ekeypair2.PublicKey);
            var secret2    = ekeypair2.GenerateSharedKey(ekeypair1.PublicKey);
            var stretched1 = StretchedKeys.Generate(cipher, hash, secret1);
            var stretched2 = StretchedKeys.Generate(cipher, hash, secret2);

            var raw = Encoding.UTF8.GetBytes("Hello world, this should be encrypted.");

            byte[] encoded = null;
            byte[] decoded = null;

            cipher = cipher.Split('-').First();
            hash   = "HMAC" + hash;

            var cipherKey1 = new ParametersWithIV(ParameterUtilities.CreateKeyParameter(cipher, stretched1.Item1.CipherKey), stretched1.Item1.IV);
            var cipherKey2 = new ParametersWithIV(ParameterUtilities.CreateKeyParameter(cipher, stretched2.Item1.CipherKey), stretched2.Item1.IV);

            var encryptor = CipherUtilities.GetCipher(cipher + "/CTR/NoPadding");

            encryptor.Init(true, cipherKey1);

            encoded = encryptor.DoFinal(raw);
            encoded = encoded.Append(MacUtilities.CalculateMac(hash, new KeyParameter(stretched1.Item1.MacKey), encoded));

            var decryptor = CipherUtilities.GetCipher(cipher + "/CTR/NoPadding");

            decryptor.Init(false, cipherKey2);

            var mac = MacUtilities.GetMac(hash);

            mac.Init(new KeyParameter(stretched2.Item1.MacKey));
            var digest = encoded.Slice(encoded.Length - mac.GetMacSize());

            Assert.Equal(MacUtilities.DoFinal(mac, encoded.Slice(0, encoded.Length - digest.Length)), digest);

            decoded = decryptor.DoFinal(encoded, 0, encoded.Length - digest.Length);
            Assert.Equal(Encoding.UTF8.GetString(decoded), Encoding.UTF8.GetString(raw));
        }
Esempio n. 13
0
        public void doTestHMac(
            string hmacName,
            byte[]  output)
        {
            KeyParameter key = new KeyParameter(keyBytes); //, hmacName);

            IMac mac = MacUtilities.GetMac(hmacName);

            mac.Init(key);

            mac.Reset();

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

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

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

            // no key generator for the old algorithms
            if (hmacName.StartsWith("Old"))
            {
                return;
            }

            CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(hmacName);

            mac.Init(new KeyParameter(kGen.GenerateKey())); // hmacName

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

//			outBytes = mac.DoFinal();
            outBytes = new byte[mac.GetMacSize()];
            mac.DoFinal(outBytes, 0);
        }
        // https://tools.ietf.org/html/rfc7836#section-4.5
        protected static byte[] KDF_GOSTR3411_2012_256(byte[] k_in, byte[] label, byte[] seed)
        {
            var data = new byte[label.Length + seed.Length + 4];

            Array.Copy(label, 0, data, 1, label.Length);
            Array.Copy(seed, 0, data, label.Length + 2, seed.Length);
            data[0] = 1;
            data[data.Length - 2] = 1;

            var mac = MacUtilities.GetMac(RosstandartObjectIdentifiers.id_tc26_hmac_gost_3411_12_256);

            mac.Init(new KeyParameter(k_in));

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

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

            mac.DoFinal(result, 0);

            return(result);
        }
Esempio n. 15
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('/', '_'));
        }
Esempio n. 16
0
        private PascalCoinIesEngine GetEciesPascalCoinCompatibilityEngine()
        {
            // Set up IES Cipher Engine For Compatibility With PascalCoin

            ECDHBasicAgreement ecdhBasicAgreementInstance = new ECDHBasicAgreement();

            PascalCoinEciesKdfBytesGenerator kdfInstance = new PascalCoinEciesKdfBytesGenerator
                                                               (DigestUtilities.GetDigest("SHA-512"));

            IMac digestMacInstance = MacUtilities.GetMac("HMAC-MD5");

            // Set Up Block Cipher
            AesEngine aesEngine = new AesEngine(); // AES Engine

            BufferedBlockCipher cipher =
                new PaddedBufferedBlockCipher(new CbcBlockCipher(aesEngine),
                                              new ZeroBytePadding()); // AES-256 CBC ZeroBytePadding

            return(new PascalCoinIesEngine(ecdhBasicAgreementInstance, kdfInstance,
                                           digestMacInstance, cipher));
        }
Esempio n. 17
0
        protected Stream Open(Stream outStr, AlgorithmIdentifier macAlgId, ICipherParameters cipherParameters, Asn1EncodableVector recipientInfos)
        {
            Stream result;

            try
            {
                BerSequenceGenerator berSequenceGenerator = new BerSequenceGenerator(outStr);
                berSequenceGenerator.AddObject(CmsObjectIdentifiers.AuthenticatedData);
                BerSequenceGenerator berSequenceGenerator2 = new BerSequenceGenerator(berSequenceGenerator.GetRawOutputStream(), 0, true);
                berSequenceGenerator2.AddObject(new DerInteger(AuthenticatedData.CalculateVersion(null)));
                Stream        rawOutputStream = berSequenceGenerator2.GetRawOutputStream();
                Asn1Generator asn1Generator   = this._berEncodeRecipientSet ? new BerSetGenerator(rawOutputStream) : new DerSetGenerator(rawOutputStream);
                foreach (Asn1Encodable obj in recipientInfos)
                {
                    asn1Generator.AddObject(obj);
                }
                asn1Generator.Close();
                berSequenceGenerator2.AddObject(macAlgId);
                BerSequenceGenerator berSequenceGenerator3 = new BerSequenceGenerator(rawOutputStream);
                berSequenceGenerator3.AddObject(CmsObjectIdentifiers.Data);
                Stream output = CmsUtilities.CreateBerOctetOutputStream(berSequenceGenerator3.GetRawOutputStream(), 0, false, this._bufferSize);
                IMac   mac    = MacUtilities.GetMac(macAlgId.ObjectID);
                mac.Init(cipherParameters);
                Stream macStream = new TeeOutputStream(output, new MacOutputStream(mac));
                result = new CmsAuthenticatedDataStreamGenerator.CmsAuthenticatedDataOutputStream(macStream, mac, berSequenceGenerator, berSequenceGenerator2, berSequenceGenerator3);
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e2)
            {
                throw new CmsException("key invalid in message.", e2);
            }
            catch (IOException e3)
            {
                throw new CmsException("exception decoding algorithm parameters.", e3);
            }
            return(result);
        }
Esempio n. 18
0
        static byte[] MFcrypt(byte[] P, byte[] S,
                              int cost, int blockSize, int parallel, int?maxThreads)
        {
            int MFLen = blockSize * 128;

            if (maxThreads == null)
            {
                maxThreads = int.MaxValue;
            }

            if (!BitMath.IsPositivePowerOf2(cost))
            {
                throw Exceptions.ArgumentOutOfRange("cost", "Cost must be a positive power of 2.");
            }
            Check.Range("blockSize", blockSize, 1, int.MaxValue / 128);
            Check.Range("parallel", parallel, 1, int.MaxValue / MFLen);
            Check.Range("maxThreads", (int)maxThreads, 1, int.MaxValue);

#if !USEBC
            byte[] B = Pbkdf2.ComputeDerivedKey(new HMACSHA256(P), S, 1, parallel * MFLen);
#else
            var mac = MacUtilities.GetMac("HMAC-SHA_256");
            mac.Init(new KeyParameter(P));
            byte[] B = Pbkdf2.ComputeDerivedKey(mac, S, 1, parallel * MFLen);
#endif
            uint[] B0 = new uint[B.Length / 4];
            for (int i = 0; i < B0.Length; i++)
            {
                B0[i] = BitPacking.UInt32FromLEBytes(B, i * 4);
            }             // code is easier with uint[]
            ThreadSMixCalls(B0, MFLen, cost, blockSize, parallel, (int)maxThreads);
            for (int i = 0; i < B0.Length; i++)
            {
                BitPacking.LEBytesFromUInt32(B0[i], B, i * 4);
            }
            Security.Clear(B0);

            return(B);
        }
Esempio n. 19
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);
        }
Esempio n. 20
0
 /**
  * Create an instance, using the specified hash function.
  * The name is used to obtain from the JVM an implementation
  * of the hash function and an implementation of HMAC.
  *
  * @param hashName   the hash function name
  * @throws IllegalArgumentException  on unsupported name
  */
 public DeterministicECDSA(String hashName)
 {
     try
     {
         dig = DigestUtilities.GetDigest(hashName);
     }
     catch (SecurityUtilityException nsae)
     {
         throw new ArgumentException("Invalid hash", "hashName", nsae);
     }
     if (hashName.IndexOf('-') < 0)
     {
         macName = "Hmac" + hashName;
     }
     else
     {
         StringBuilder sb = new StringBuilder();
         sb.Append("Hmac");
         int n = hashName.Length;
         for (int i = 0; i < n; i++)
         {
             char c = hashName[i];
             if (c != '-')
             {
                 sb.Append(c);
             }
         }
         macName = sb.ToString();
     }
     try
     {
         hmac = MacUtilities.GetMac(macName);
     }
     catch (SecurityUtilityException nsae)
     {
         throw new InvalidOperationException(nsae.Message, nsae);
     }
     holen = hmac.GetMacSize();
 }
Esempio n. 21
0
        public void TestCultureIndependence()
        {
            CultureInfo ci = CultureInfo.CurrentCulture;

            try
            {
                /*
                 * In Hungarian, the "CS" in "HMACSHA256" is linguistically a single character, so "HMAC" is not a prefix.
                 */
                CultureInfo.CurrentCulture = new CultureInfo("hu-HU");
                IMac mac = MacUtilities.GetMac("HMACSHA256");
                Assert.NotNull(mac);
            }
            catch (Exception e)
            {
                Assert.Fail("Culture-specific lookup failed: " + e.Message);
            }
            finally
            {
                CultureInfo.CurrentCulture = ci;
            }
        }
        private byte[] PerformMic(string appKey)
        {
            IMac mac = MacUtilities.GetMac("AESCMAC");

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

            mac.Init(key);
            var newDevEUI = DevEUI.ToArray();

            Array.Reverse(newDevEUI);

            var newAppEUI = AppEUI.ToArray();

            Array.Reverse(newAppEUI);
            var algoinput = Mhdr.ToArray().Concat(newAppEUI).Concat(newDevEUI).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());
        }
Esempio n. 23
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)));
        }
Esempio n. 24
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));
                }
            }
        }
Esempio n. 25
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));
            }
        }
Esempio n. 26
0
        /**
         * generate an enveloped object that contains an CMS Enveloped Data
         * object using the given provider and the passed in key generator.
         */
        private CmsAuthenticatedData Generate(
            CmsProcessable content,
            string macOid,
            CipherKeyGenerator keyGen)
        {
            AlgorithmIdentifier macAlgId;
            KeyParameter        encKey;
            Asn1OctetString     encContent;
            Asn1OctetString     macResult;

            try
            {
                // FIXME Will this work for macs?
                byte[] encKeyBytes = keyGen.GenerateKey();
                encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes);

                Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes);

                ICipherParameters cipherParameters;
                macAlgId = GetAlgorithmIdentifier(
                    macOid, encKey, asn1Params, out cipherParameters);

                IMac mac = MacUtilities.GetMac(macOid);
                // TODO Confirm no ParametersWithRandom needed
                // FIXME Only passing key at the moment
//	            mac.Init(cipherParameters);
                mac.Init(encKey);

                MemoryStream bOut = new MemoryStream();
                Stream       mOut = new TeeOutputStream(bOut, new MacOutputStream(mac));

                content.Write(mOut);

                mOut.Close();
                bOut.Close();

                encContent = new BerOctetString(bOut.ToArray());

                byte[] macOctets = MacUtilities.DoFinal(mac);
                macResult = new DerOctetString(macOctets);
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }

            Asn1EncodableVector recipientInfos = new Asn1EncodableVector();

            foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
            {
                try
                {
                    recipientInfos.Add(rig.Generate(encKey, rand));
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key inappropriate for algorithm.", e);
                }
                catch (GeneralSecurityException e)
                {
                    throw new CmsException("error making encrypted content.", e);
                }
            }

            ContentInfo eci = new ContentInfo(CmsObjectIdentifiers.Data, encContent);

            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.AuthenticatedData,
                new AuthenticatedData(null, new DerSet(recipientInfos), macAlgId, null, eci, null, macResult, null));

            return(new CmsAuthenticatedData(contentInfo));
        }
Esempio n. 27
0
            public CmsReadable GetReadable(KeyParameter sKey)
            {
                string macAlg = this.algorithm.Algorithm.Id;

//				Asn1Object sParams = this.algorithm.Parameters.ToAsn1Object();

                try
                {
                    this.mac = MacUtilities.GetMac(macAlg);

                    // FIXME Support for MAC algorithm parameters similar to cipher parameters
//						ASN1Object sParams = (ASN1Object)macAlg.getParameters();
//
//						if (sParams != null && !(sParams instanceof ASN1Null))
//						{
//							AlgorithmParameters params = CMSEnvelopedHelper.INSTANCE.createAlgorithmParameters(macAlg.getObjectId().getId(), provider);
//
//							params.init(sParams.getEncoded(), "ASN.1");
//
//							mac.init(sKey, params.getParameterSpec(IvParameterSpec.class));
//						}
//						else
                    {
                        mac.Init(sKey);
                    }

//						Asn1Object asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object();
//
//						ICipherParameters cipherParameters = sKey;
//
//						if (asn1Params != null && !(asn1Params is Asn1Null))
//						{
//							cipherParameters = ParameterUtilities.GetCipherParameters(
//							macAlg.Algorithm, cipherParameters, asn1Params);
//						}
//						else
//						{
//							string alg = macAlg.Algorithm.Id;
//							if (alg.Equals(CmsEnvelopedDataGenerator.DesEde3Cbc)
//								|| alg.Equals(CmsEnvelopedDataGenerator.IdeaCbc)
//								|| alg.Equals(CmsEnvelopedDataGenerator.Cast5Cbc))
//							{
//								cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
//							}
//						}
//
//						mac.Init(cipherParameters);
                }
                catch (SecurityUtilityException e)
                {
                    throw new CmsException("couldn't create cipher.", e);
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key invalid in message.", e);
                }
                catch (IOException e)
                {
                    throw new CmsException("error decoding algorithm parameters.", e);
                }

                try
                {
                    return(new CmsProcessableInputStream(
                               new TeeInputStream(
                                   readable.GetInputStream(),
                                   new MacOutputStream(this.mac))));
                }
                catch (IOException e)
                {
                    throw new CmsException("error reading content.", e);
                }
            }
Esempio n. 28
0
 public static byte[] CalculateHMAC(byte[] key, byte[] data)
 {
     return(MacUtilities.CalculateMac("HMAC-SHA256", new KeyParameter(key), data));
 }
Esempio n. 29
0
		protected Stream Open(
			Stream        			outStr,
			AlgorithmIdentifier		macAlgId,
			ICipherParameters		cipherParameters,
			Asn1EncodableVector		recipientInfos)
		{
			try
			{
				//
				// ContentInfo
				//
				BerSequenceGenerator cGen = new BerSequenceGenerator(outStr);

				cGen.AddObject(CmsObjectIdentifiers.AuthenticatedData);

				//
				// Authenticated Data
				//
				BerSequenceGenerator authGen = new BerSequenceGenerator(
					cGen.GetRawOutputStream(), 0, true);

				authGen.AddObject(new DerInteger(AuthenticatedData.CalculateVersion(null)));

				Stream authRaw = authGen.GetRawOutputStream();
				Asn1Generator recipGen = _berEncodeRecipientSet
					?	(Asn1Generator) new BerSetGenerator(authRaw)
					:	new DerSetGenerator(authRaw);

				foreach (Asn1Encodable ae in recipientInfos)
				{
					recipGen.AddObject(ae);
				}

				recipGen.Close();

				authGen.AddObject(macAlgId);

				BerSequenceGenerator eiGen = new BerSequenceGenerator(authRaw);
				eiGen.AddObject(CmsObjectIdentifiers.Data);

				Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream(
					eiGen.GetRawOutputStream(), 0, false, _bufferSize);

				IMac mac = MacUtilities.GetMac(macAlgId.ObjectID);
				// TODO Confirm no ParametersWithRandom needed
	            mac.Init(cipherParameters);
				Stream mOut = new TeeOutputStream(octetOutputStream, new MacOutputStream(mac));

				return new CmsAuthenticatedDataOutputStream(mOut, mac, cGen, authGen, eiGen);
			}
			catch (SecurityUtilityException e)
			{
				throw new CmsException("couldn't create cipher.", e);
			}
			catch (InvalidKeyException e)
			{
				throw new CmsException("key invalid in message.", e);
			}
			catch (IOException e)
			{
				throw new CmsException("exception decoding algorithm parameters.", e);
			}
		}
Esempio n. 30
0
        public override void PerformTest()
        {
            KeyParameter key = new DesParameters(keyBytes);
            IMac         mac = MacUtilities.GetMac("DESMac");

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

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

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

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

            //
            // mac with IV.
            //
            mac.Init(new ParametersWithIV(key, ivBytes));

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

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

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

            //
            // CFB mac with IV - 8 bit CFB mode
            //
            mac = MacUtilities.GetMac("DESMac/CFB8");

            mac.Init(new ParametersWithIV(key, ivBytes));

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

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

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

            //
            // ISO9797 algorithm 3 using DESEDE
            //
            key = new DesEdeParameters(keyBytesISO9797);

            mac = MacUtilities.GetMac("ISO9797ALG3");

            mac.Init(key);

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

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

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

            //
            // 64bit DESede Mac
            //
            key = new DesEdeParameters(keyBytesISO9797);

            mac = MacUtilities.GetMac("DESEDE64");

            mac.Init(key);

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

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

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

            aliasTest(
                ParameterUtilities.CreateKeyParameter("DESede", keyBytesISO9797),
                "DESedeMac64withISO7816-4Padding",
                "DESEDE64WITHISO7816-4PADDING",
                "DESEDEISO9797ALG1MACWITHISO7816-4PADDING",
                "DESEDEISO9797ALG1WITHISO7816-4PADDING");

            aliasTest(
                ParameterUtilities.CreateKeyParameter("DESede", keyBytesISO9797),
                "ISO9797ALG3WITHISO7816-4PADDING",
                "ISO9797ALG3MACWITHISO7816-4PADDING");
        }