Example #1
0
            public CmsReadable GetReadable(KeyParameter sKey)
            {
                string id = this.algorithm.ObjectID.Id;

                try
                {
                    this.mac = MacUtilities.GetMac(id);
                    this.mac.Init(sKey);
                }
                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("error decoding algorithm parameters.", e3);
                }
                CmsReadable result;

                try
                {
                    result = new CmsProcessableInputStream(new TeeInputStream(this.readable.GetInputStream(), new MacOutputStream(this.mac)));
                }
                catch (IOException e4)
                {
                    throw new CmsException("error reading content.", e4);
                }
                return(result);
            }
Example #2
0
        private 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 = MacUtilities.DoFinal(mac);

            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);

            key = new KeyParameter(kGen.GenerateKey());
            mac.Init(key); // hmacName
            mac.BlockUpdate(message, 0, message.Length);
            outBytes = MacUtilities.DoFinal(mac);
        }
Example #3
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 NET35
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return(Convert.ToBase64String(hashmessage).Replace('+', '-').Replace('/', '_'));
            }
#else
            //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('/', '_'));
#endif
        }
Example #4
0
        private void DoTestHMac(string hmacName, int defKeySize, 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 = MacUtilities.DoFinal(mac);

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

            CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(hmacName);

            key = new KeyParameter(kGen.GenerateKey());
            mac.Init(key); // hmacName
            mac.BlockUpdate(message, 0, message.Length);
            outBytes = MacUtilities.DoFinal(mac);

            IsTrue("default key wrong length", key.GetKey().Length == (defKeySize / 8));
        }
        public override byte[] CalculateMic(string appKey)
        {
            IMac         mac = MacUtilities.GetMac("AESCMAC");
            KeyParameter key = new KeyParameter(StringToByteArray(appKey));

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

            var algoinput = mhdr.Concat(appNonce).Concat(netID).Concat(devAddr).Concat(rfu).Concat(rxDelay).ToArray();

            if (cfList != null)
            {
                algoinput = algoinput.Concat(cfList).ToArray();
            }
            byte[] msgLength = BitConverter.GetBytes(algoinput.Length);

            byte direction = 0x01;

            byte[] aBlock = { 0x49,                          0x00,            0x00, 0x00, 0x00, direction, (byte)(devAddr[3]), (byte)(devAddr[2]), (byte)(devAddr[1]),
                              (byte)(devAddr[0]), (byte)(fcnt[0]), (byte)(fcnt[1]), 0x00, 0x00,      0x00, msgLength[0] };
            algoinput = aBlock.Concat(algoinput).ToArray();
            byte[] result = new byte[16];
            mac.BlockUpdate(algoinput, 0, algoinput.Length);
            result = MacUtilities.DoFinal(mac);
            mic    = result.Take(4).ToArray();
            return(mic);
        }
        private byte[] PerformMic(string appKey)
        {
            IMac mac = MacUtilities.GetMac("AESCMAC");

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

            mac.Init(key);
            var algoInputBytes = new byte[19];
            var algoInput      = new Memory <byte>(algoInputBytes);

            var offset = 0;

            this.Mhdr.CopyTo(algoInput);
            offset += this.Mhdr.Length;
            this.AppEUI.CopyTo(algoInput.Slice(offset));
            offset += this.AppEUI.Length;
            this.DevEUI.CopyTo(algoInput.Slice(offset));
            offset += this.DevEUI.Length;
            this.DevNonce.CopyTo(algoInput.Slice(offset));

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

            var result = MacUtilities.DoFinal(mac);

            return(result.Take(4).ToArray());
        }
            public CmsReadable GetReadable(KeyParameter sKey)
            {
                //IL_0046: Expected O, but got Unknown
                //IL_0078: Expected O, but got Unknown
                string id = algorithm.Algorithm.Id;

                try
                {
                    mac = MacUtilities.GetMac(id);
                    mac.Init(sKey);
                }
                catch (SecurityUtilityException e)
                {
                    throw new CmsException("couldn't create cipher.", e);
                }
                catch (InvalidKeyException e2)
                {
                    throw new CmsException("key invalid in message.", e2);
                }
                catch (IOException val)
                {
                    IOException e3 = val;
                    throw new CmsException("error decoding algorithm parameters.", (global::System.Exception)(object) e3);
                }
                try
                {
                    return(new CmsProcessableInputStream((Stream)(object)new TeeInputStream(readable.GetInputStream(), (Stream)(object)new MacOutputStream(mac))));
                }
                catch (IOException val2)
                {
                    IOException e4 = val2;
                    throw new CmsException("error reading content.", (global::System.Exception)(object) e4);
                }
            }
    public static object CreateEngine(string algorithm)
    {
        string text = (string)algorithms[Platform.ToUpperInvariant(algorithm)];

        if (Platform.StartsWith(text, "PBEwithHmac"))
        {
            string str = text.Substring("PBEwithHmac".Length);
            return(MacUtilities.GetMac("HMAC/" + str));
        }
        if (Platform.StartsWith(text, "PBEwithMD2") || Platform.StartsWith(text, "PBEwithMD5") || Platform.StartsWith(text, "PBEwithSHA-1") || Platform.StartsWith(text, "PBEwithSHA-256"))
        {
            if (Platform.EndsWith(text, "AES-CBC-BC") || Platform.EndsWith(text, "AES-CBC-OPENSSL"))
            {
                return(CipherUtilities.GetCipher("AES/CBC"));
            }
            if (Platform.EndsWith(text, "DES-CBC"))
            {
                return(CipherUtilities.GetCipher("DES/CBC"));
            }
            if (Platform.EndsWith(text, "DESEDE-CBC"))
            {
                return(CipherUtilities.GetCipher("DESEDE/CBC"));
            }
            if (Platform.EndsWith(text, "RC2-CBC"))
            {
                return(CipherUtilities.GetCipher("RC2/CBC"));
            }
            if (Platform.EndsWith(text, "RC4"))
            {
                return(CipherUtilities.GetCipher("RC4"));
            }
        }
        return(null);
    }
Example #9
0
        public virtual IStreamCalculator CreateCalculator()
        {
            IMac mac = MacUtilities.GetMac(parameters.Mac.Algorithm);

            mac.Init(new KeyParameter(key));
            return(new PKMacStreamCalculator(mac));
        }
    private CmsAuthenticatedData Generate(CmsProcessable content, string macOid, CipherKeyGenerator keyGen)
    {
        KeyParameter        keyParameter;
        AlgorithmIdentifier algorithmIdentifier;
        Asn1OctetString     content2;
        Asn1OctetString     mac2;

        try
        {
            byte[] array = keyGen.GenerateKey();
            keyParameter = ParameterUtilities.CreateKeyParameter(macOid, array);
            Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, array);
            algorithmIdentifier = GetAlgorithmIdentifier(macOid, keyParameter, asn1Params, out ICipherParameters _);
            IMac mac = MacUtilities.GetMac(macOid);
            mac.Init(keyParameter);
            MemoryStream memoryStream = new MemoryStream();
            Stream       stream       = new TeeOutputStream(memoryStream, new MacOutputStream(mac));
            content.Write(stream);
            Platform.Dispose(stream);
            content2 = new BerOctetString(memoryStream.ToArray());
            byte[] str = MacUtilities.DoFinal(mac);
            mac2 = new DerOctetString(str);
        }
        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);
        }
        Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

        foreach (RecipientInfoGenerator recipientInfoGenerator in recipientInfoGenerators)
        {
            try
            {
                asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, rand));
            }
            catch (InvalidKeyException e4)
            {
                throw new CmsException("key inappropriate for algorithm.", e4);
            }
            catch (GeneralSecurityException e5)
            {
                throw new CmsException("error making encrypted content.", e5);
            }
        }
        ContentInfo encapsulatedContent = new ContentInfo(CmsObjectIdentifiers.Data, content2);
        ContentInfo contentInfo         = new ContentInfo(CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(asn1EncodableVector), algorithmIdentifier, null, encapsulatedContent, null, mac2, null));

        return(new CmsAuthenticatedData(contentInfo));
    }
Example #11
0
        public static byte[] HMACSHA512(byte[] key, byte[] data)
        {
            var mac = MacUtilities.GetMac("HMAC-SHA_512");

            mac.Init(new KeyParameter(key));
            mac.Update(data);
            byte[] result = new byte[mac.GetMacSize()];
            mac.DoFinal(result, 0);
            return(result);
        }
        public static IMac CreatePrf(Vector config)
        {
            string type = config.HeaderAsString("PRF");

            if (type == null)
            {
                throw new ArgumentException("PRF field was null.");
            }

            return(MacUtilities.GetMac(GetMacForPrf(type)));
        }
Example #13
0
        public static Pbkdf2 GetStream(byte[] key, byte[] salt,
                                       int cost, int blockSize, int parallel, int?maxThreads)
        {
            byte[] B   = GetEffectivePbkdf2Salt(key, salt, cost, blockSize, parallel, maxThreads);
            var    mac = MacUtilities.GetMac("HMAC-SHA_256");

            mac.Init(new KeyParameter(key));
            Pbkdf2 kdf = new Pbkdf2(mac, B, 1);

            Security.Clear(B);
            return(kdf);
        }
 protected Stream Open(Stream outStr, AlgorithmIdentifier macAlgId, ICipherParameters cipherParameters, Asn1EncodableVector recipientInfos)
 {
     //IL_011d: Expected O, but got Unknown
     try
     {
         BerSequenceGenerator berSequenceGenerator = new BerSequenceGenerator(outStr);
         berSequenceGenerator.AddObject(CmsObjectIdentifiers.AuthenticatedData);
         BerSequenceGenerator berSequenceGenerator2 = new BerSequenceGenerator(berSequenceGenerator.GetRawOutputStream(), 0, isExplicit: true);
         berSequenceGenerator2.AddObject(new DerInteger(AuthenticatedData.CalculateVersion(null)));
         Stream        rawOutputStream = berSequenceGenerator2.GetRawOutputStream();
         Asn1Generator asn1Generator   = (_berEncodeRecipientSet ? ((Asn1Generator) new BerSetGenerator(rawOutputStream)) : ((Asn1Generator) new DerSetGenerator(rawOutputStream)));
         global::System.Collections.IEnumerator enumerator = recipientInfos.GetEnumerator();
         try
         {
             while (enumerator.MoveNext())
             {
                 Asn1Encodable obj = (Asn1Encodable)enumerator.get_Current();
                 asn1Generator.AddObject(obj);
             }
         }
         finally
         {
             global::System.IDisposable disposable = enumerator as global::System.IDisposable;
             if (disposable != null)
             {
                 disposable.Dispose();
             }
         }
         asn1Generator.Close();
         berSequenceGenerator2.AddObject(macAlgId);
         BerSequenceGenerator berSequenceGenerator3 = new BerSequenceGenerator(rawOutputStream);
         berSequenceGenerator3.AddObject(CmsObjectIdentifiers.Data);
         Stream output = CmsUtilities.CreateBerOctetOutputStream(berSequenceGenerator3.GetRawOutputStream(), 0, isExplicit: false, _bufferSize);
         IMac   mac    = MacUtilities.GetMac(macAlgId.Algorithm);
         mac.Init(cipherParameters);
         Stream macStream = (Stream)(object)new TeeOutputStream(output, (Stream)(object)new MacOutputStream(mac));
         return((Stream)(object)new 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 val)
     {
         IOException e3 = val;
         throw new CmsException("exception decoding algorithm parameters.", (global::System.Exception)(object) e3);
     }
 }
Example #15
0
        private void doTestPbeHMac(
            string hmacName,
            byte[]  output)
        {
            ICipherParameters key = null;

            byte[] outBytes;
            IMac   mac = null;

            try
            {
//				SecretKeyFactory fact = SecretKeyFactory.getInstance(hmacName);
//
//				key = fact.generateSecret(new PBEKeySpec("hello".ToCharArray()));

                Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(
                    hmacName, new byte[20], 100);
                key = PbeUtilities.GenerateCipherParameters(
                    hmacName, "hello".ToCharArray(), algParams);
                mac = MacUtilities.GetMac(hmacName);
            }
            catch (Exception e)
            {
                Fail("Failed - exception " + e.ToString(), e);
            }

            try
            {
//				mac.Init(key, new PBEParameterSpec(new byte[20], 100));
                mac.Init(key);
            }
            catch (Exception e)
            {
                Fail("Failed - exception " + e.ToString(), e);
            }

            mac.Reset();

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

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

            if (!AreEqual(outBytes, output))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output) + " got "
                     + Hex.ToHexString(outBytes));
            }
        }
        private byte[] GetDecryptionKey(string pin, VipNetContainer defence)
        {
            var passwordData = Encoding.ASCII.GetBytes(pin ?? "");

            if (DefenceKeyInfo.KeyClass.Value.IntValue == 64 && DefenceKeyInfo.KeyType.Value.IntValue == 24622)
            {
                // Контейнер зашифрован ключом, лежащим в ещё одном контейнере
                if (defence == null)
                {
                    throw new CryptographicException("Закрытый ключ зашифрован секретным ключом, расположенным в отдельном вспомогательном контейнере. Используйте опцию --defence");
                }
                return(defence.Entries[0].GetProtectionKey(pin));
            }
            if (DefenceKeyInfo.Algorithm != null &&
                DefenceKeyInfo.Algorithm.Algorithm.Equals(PkcsObjectIdentifiers.IdPbkdf2))
            {
                // PBKDF2 используется в контейнерах ViPNet Jcrypto SDK
                // Самое смешное, что сам десктопный ViPNet CSP не понимает такие контейнеры
                // А мы понимаем!
                var p = Pbkdf2Params.GetInstance(DefenceKeyInfo.Algorithm.Parameters);
                return(PBKDF2(
                           MacUtilities.GetMac(p.Prf.Algorithm),
                           passwordData,
                           p.GetSalt(),
                           p.IterationCount.IntValue,
                           p.KeyLength.IntValue
                           ));
            }
            var digest        = new Gost3411Digest();
            var keyData       = new byte[digest.GetDigestSize()];
            var unwrappingKey = new byte[digest.GetDigestSize()];

            digest.BlockUpdate(passwordData, 0, passwordData.Length);
            digest.DoFinal(keyData, 0);
            digest.Reset();

            var secodeData = passwordData.Concat(keyData).ToArray();

            digest.BlockUpdate(secodeData, 0, secodeData.Length);
            digest.DoFinal(unwrappingKey, 0);

            var tmp = new int[keyData.Length / 4];

            for (int i = 0; i < keyData.Length; i += 4)
            {
                tmp[i / 4] = BitConverter.ToInt32(keyData, i) - BitConverter.ToInt32(unwrappingKey, i);
            }

            return(tmp.SelectMany(x => BitConverter.GetBytes(x)).ToArray());
        }
Example #17
0
        private 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(1);
            byte[] result = MacUtilities.DoFinal(prkGen);
            if (result.Length > len)
            {
                Array.Resize(ref result, len);
            }
            return(result);
        }
        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);
        }
Example #19
0
        public byte[] DeriveSeed(string passphrase = null)
        {
            passphrase = passphrase ?? "";
            var salt  = Concat(Encoding.UTF8.GetBytes("mnemonic"), Normalize(passphrase));
            var bytes = Normalize(_Mnemonic);

#if !USEBC
            return(Pbkdf2.ComputeDerivedKey(new HMACSHA512(bytes), salt, 2048, 64));
#else
            var mac = MacUtilities.GetMac("HMAC-SHA_512");
            mac.Init(new KeyParameter(bytes));
            return(Pbkdf2.ComputeDerivedKey(mac, salt, 2048, 64));
#endif
        }
        private static MacStream CreateMacStream(
            AlgorithmIdentifier macAlg,
            KeyParameter sKey,
            Stream inStream)
//		throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException, InvalidParameterSpecException
        {
            IMac mac = MacUtilities.GetMac(macAlg.ObjectID);

            // 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);
            }

//			Asn1Encodable asn1Enc = macAlg.Parameters;
//			Asn1Object asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object();
//
//			ICipherParameters cipherParameters = sKey;
//
//			if (asn1Params != null && !(asn1Params is Asn1Null))
//			{
//				cipherParameters = ParameterUtilities.GetCipherParameters(
//					macAlg.ObjectID, cipherParameters, asn1Params);
//			}
//			else
//			{
//				string alg = macAlg.ObjectID.Id;
//				if (alg.Equals(CmsEnvelopedDataGenerator.DesEde3Cbc)
//					|| alg.Equals(CmsEnvelopedDataGenerator.IdeaCbc)
//					|| alg.Equals(CmsEnvelopedDataGenerator.Cast5Cbc))
//				{
//					cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
//				}
//			}
//
//			mac.Init(cipherParameters);

            return(new MacStream(inStream, mac, null));
        }
        /// <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());
        }
Example #22
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, byte[] key, string algorithm)
        {
            if (string.IsNullOrEmpty(data))
            {
                throw new ArgumentNullException(nameof(data));
            }

            var keyParameter = new Org.BouncyCastle.Crypto.Parameters.KeyParameter(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));
        }
        /// <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()));
        }
Example #24
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();
        }
Example #25
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)
Example #26
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());
        }
Example #27
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()));
        }
        // https://tc26.ru/standard/rs/%D0%A0%2050.1.111-2016.pdf
        protected static byte[] PBKDF2(byte[] p, byte[] s, int c, int dkLen)
        {
            int n    = dkLen / 64;
            var u    = new byte[c][];
            var t    = new byte[n][];
            var hmac = MacUtilities.GetMac(RosstandartObjectIdentifiers.id_tc26_hmac_gost_3411_12_512);
            int sz   = hmac.GetMacSize();

            for (int i = 0; i < n; ++i)
            {
                for (int j = 0; j < c; ++j)
                {
                    u[j] = new byte[sz];
                    var data = j == 0 ? s.Concat(BitConverter.GetBytes(i + 1).Reverse()).ToArray() : u[j - 1];
                    hmac.Reset();
                    hmac.Init(new KeyParameter(p));
                    hmac.BlockUpdate(data, 0, data.Length);
                    hmac.DoFinal(u[j], 0);
                }
                t[i] = new byte[sz];
                Array.Copy(u[0], t[i], sz);
                for (int j = 1; j < c; ++j)
                {
                    for (int k = 0; k < sz; ++k)
                    {
                        t[i][k] ^= u[j][k];
                    }
                }
            }

            var result = new byte[dkLen];

            for (int i = 0, j = 0; i < dkLen; ++i)
            {
                result[i] = t[j][i % sz];
                if (i % sz == sz - 1)
                {
                    j++;
                }
            }

            return(result);
        }
Example #29
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
//			}
        }
Example #30
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);
        }