Esempio n. 1
0
        /// <summary>
        /// Gets the enum of type <see cref="T"/> matching the description.
        /// </summary>
        /// <typeparam name="T">The enum type to return/parse descriptions of.</typeparam>
        /// <param name="enumDescription">The description to search the enum for.</param>
        /// <param name="shouldThrow">Should the method throw if the enum is not found?</param>
        /// <returns></returns>
        public static T GetEnumFromEnumDescription <T>(string enumDescription, bool shouldThrow = true)
            where T : struct
        {
            if (!typeof(T).IsEnum)
            {
                throw new InvalidOperationException("Type is not an enum");
            }

            try
            {
                return((T)typeof(T)
                       .GetFields()
                       .First(
                           f => f.GetCustomAttributes <EnumMemberAttribute>()
                           .Any(a => a.Value.Equals(enumDescription, StringComparison.OrdinalIgnoreCase))
                           )
                       .GetValue(null));
            }
            catch (Exception)
            {
                if (shouldThrow)
                {
                    ThisLogger.Error($"Couldn't find an {typeof(T)} matching {nameof(enumDescription)} of \"{enumDescription}\"");
                    throw;
                }

                return(default(T));
            }
        }
Esempio n. 2
0
        public MacResult Verify(BitString keyBits, BitString message, BitString macToVerify)
        {
            try
            {
                var mac = Generate(keyBits, message, macToVerify.BitLength);

                if (!mac.Success)
                {
                    return(new MacResult(mac.ErrorMessage));
                }

                if (mac.Mac.Equals(macToVerify))
                {
                    return(new MacResult(mac.Mac));
                }

                return(new MacResult("CMAC did not match."));
            }
            catch (Exception ex)
            {
                ThisLogger.Debug($"keyLen:{keyBits.BitLength}; dataLen:{message.BitLength}");
                ThisLogger.Error(ex);
                return(new MacResult(ex.Message));
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 从队列中获取消息, 默认3秒超时
        /// </summary>
        /// <returns></returns>
        protected virtual Message TryReceiveMesssage()
        {
            try
            {
                MessageQueue mqServer = new MessageQueue(MyConfig.Address);

                return(mqServer.Receive(TimeSpan.FromSeconds(MyConfig.TimeoutSecond)));
            }
            catch (MessageQueueException mqe)
            {
                switch (mqe.MessageQueueErrorCode)
                {
                case MessageQueueErrorCode.IOTimeout:
                    return(null);

                default:
                    if (Convert.ToInt32(mqe.MessageQueueErrorCode) == -2147023170)
                    {
                        return(null);
                    }
                    break;

                case MessageQueueErrorCode.QueueNotFound:
                    throw;
                }

                ThisLogger.Error(mqe, MyConfig.Address, mqe.ErrorCode, mqe.MessageQueueErrorCode);
                Thread.Sleep(1000);
                return(null);
            }
        }
Esempio n. 4
0
        /*
         * INPUT: The initial Msg of 256 bits long
         *        LmsParams
         *        SEED
         *        RootI
         *
         * {
         *     lmsKeyPair = GenerateLmsKeyPair(SEED, RootI, Params);
         *     Output0 = Msg;
         *     for (j=0; j<100; j++) {
         *         for (i=1; i<(isSample ? 101 : 1001); i++) {
         *             M[i] = leftmost bits indexed from 96 to 352;
         *             if (lmsKeyPair is expired) {
         *                 lmsKeyPair = GenerateLmsKeyPair(M[i], 128 left most bits of M[i], Params);
         *             }
         *             Output[i] = LmsSignature(M[i],lmsKeyPair);
         *             lmsKeyPair = UpdateLmsKeyPair(lmsKeyPair);
         *         }
         *         Output[j] = Output[1000];
         *         OUTPUT: Output[j]
         *     }
         * }
         */
        #endregion MonteCarloAlgorithm Pseudocode

        public async Task <MCTResult <AlgoArrayResponse> > MCTHashAsync(LmsType[] lmsTypes, LmotsType[] lmotsTypes,
                                                                        BitString seed, BitString rootI, BitString message, bool isSample)
        {
            var hss = _hssFactory.GetInstance(lmsTypes.Length, lmsTypes, lmotsTypes, EntropyProviderTypes.Testable, seed, rootI);

            var keyPair = await hss.GenerateHssKeyPairAsync();

            if (isSample)
            {
                NUM_OF_RESPONSES = 3;
            }

            var responses = new List <AlgoArrayResponse>();
            var i         = 0;
            var j         = 0;

            var innerMessage = message.GetDeepCopy();

            try
            {
                for (i = 0; i < NUM_OF_RESPONSES; i++)
                {
                    var innerSignature    = new BitString(0);
                    var iterationResponse = new AlgoArrayResponse()
                    {
                    };
                    iterationResponse.Message = innerMessage;

                    for (j = 0; j < (isSample ? 100 : 1000); j++)
                    {
                        if (keyPair.Expired)
                        {
                            hss = _hssFactory.GetInstance(lmsTypes.Length, lmsTypes, lmotsTypes,
                                                          EntropyProviderTypes.Testable, innerMessage, innerMessage.MSBSubstring(0, 128));
                            keyPair = await hss.GenerateHssKeyPairAsync();
                        }

                        innerSignature = (await hss.GenerateHssSignatureAsync(innerMessage, keyPair)).Signature;

                        keyPair = await hss.UpdateKeyPairOneStepAsync(keyPair);

                        innerMessage = innerSignature.MSBSubstring(96, 256);
                    }

                    iterationResponse.Signature = innerSignature.GetDeepCopy();
                    responses.Add(iterationResponse);
                }
            }
            catch (Exception ex)
            {
                ThisLogger.Debug($"i count {i}, j count {j}");
                ThisLogger.Error(ex);
                return(new MCTResult <AlgoArrayResponse>($"{ex.Message}"));
            }

            return(new MCTResult <AlgoArrayResponse>(responses));
        }
Esempio n. 5
0
        private MCTResult <AlgoArrayResponse> Encrypt(IModeBlockCipherParameters param)
        {
            var responses = new List <AlgoArrayResponse>();

            var i = 0;
            var j = 0;

            try
            {
                for (i = 0; i < 100; i++)
                {
                    var iIterationResponse = new AlgoArrayResponse
                    {
                        IV        = param.Iv,
                        Key       = param.Key,
                        PlainText = param.Payload
                    };

                    BitString jCipherText            = null;
                    BitString previousCipherText     = null;
                    BitString copyPreviousCipherText = null;
                    var       ivCopiedBytes          = iIterationResponse.IV.ToBytes();
                    param.Iv = new BitString(ivCopiedBytes);

                    for (j = 0; j < 1000; j++)
                    {
                        var jResult = _algo.ProcessPayload(param);
                        jCipherText = jResult.Result;

                        if (j == 0)
                        {
                            previousCipherText = iIterationResponse.IV;
                        }

                        param.Payload          = previousCipherText;
                        copyPreviousCipherText = previousCipherText;
                        previousCipherText     = jCipherText;
                    }

                    iIterationResponse.CipherText = jCipherText;
                    responses.Add(iIterationResponse);

                    param.Key = _keyMaker.MixKeys(param.Key, previousCipherText, copyPreviousCipherText);
                    param.Iv  = previousCipherText;
                }
            }
            catch (Exception ex)
            {
                ThisLogger.Debug($"i count {i}, j count {j}");
                ThisLogger.Error(ex);
                return(new MCTResult <AlgoArrayResponse>(ex.Message));
            }

            return(new MCTResult <AlgoArrayResponse>(responses));
        }
        private MCTResult <AlgoArrayResponse> Decrypt(IModeBlockCipherParameters param)
        {
            List <AlgoArrayResponse> responses = new List <AlgoArrayResponse>();

            int i = 0;
            int j = 0;

            try
            {
                for (i = 0; i < 100; i++)
                {
                    AlgoArrayResponse iIterationResponse = new AlgoArrayResponse()
                    {
                        IV         = param.Iv,
                        Key        = param.Key,
                        CipherText = param.Payload
                    };

                    BitString jPlainText            = null;
                    BitString previousPlainText     = null;
                    BitString copyPreviousPlainText = null;
                    var       ivCopiedBytes         = iIterationResponse.IV.ToBytes();
                    param.Iv = new BitString(ivCopiedBytes);
                    for (j = 0; j < 1000; j++)
                    {
                        var jResult = _algo.ProcessPayload(param);
                        jPlainText = jResult.Result;

                        if (j == 0)
                        {
                            previousPlainText = iIterationResponse.IV.ConcatenateBits(jPlainText.GetMostSignificantBits(param.Payload.BitLength - param.Iv.BitLength));
                        }

                        param.Payload         = previousPlainText;
                        copyPreviousPlainText = previousPlainText;
                        previousPlainText     = jPlainText;
                    }

                    iIterationResponse.PlainText = jPlainText;
                    responses.Add(iIterationResponse);

                    param.Key = _keyMaker.MixKeys(param.Key, previousPlainText, copyPreviousPlainText);
                    param.Iv  = previousPlainText.GetMostSignificantBits(param.Iv.BitLength);
                }
            }
            catch (Exception ex)
            {
                ThisLogger.Debug($"i count {i}, j count {j}");
                ThisLogger.Error(ex);
                return(new MCTResult <AlgoArrayResponse>(ex.Message));
            }

            return(new MCTResult <AlgoArrayResponse>(responses));
        }
Esempio n. 7
0
        private MCTResult <AlgoArrayResponse> Decrypt(IModeBlockCipherParameters param)
        {
            List <AlgoArrayResponse> responses = new List <AlgoArrayResponse>();

            int i = 0;
            int j = 0;

            try
            {
                for (i = 0; i < _OUTPUT_ITERATIONS; i++)
                {
                    AlgoArrayResponse iIterationResponse = new AlgoArrayResponse()
                    {
                        IV         = param.Iv,
                        Key        = param.Key,
                        CipherText = param.Payload
                    };
                    responses.Add(iIterationResponse);

                    List <BitString> previousPlainTexts = new List <BitString>();
                    param.Iv      = param.Iv.GetDeepCopy();
                    param.Payload = param.Payload.GetDeepCopy();
                    for (j = 0; j < _INNER_ITERATIONS_PER_OUTPUT; j++)
                    {
                        var jResult    = _algo.ProcessPayload(param);
                        var jPlainText = jResult.Result.GetDeepCopy();
                        previousPlainTexts.Add(jPlainText);
                        iIterationResponse.PlainText = jPlainText;

                        param.Payload = GetNextPayload(j, iIterationResponse.IV, previousPlainTexts);

                        BitString iv      = param.Iv.GetDeepCopy();
                        BitString key     = param.Key.GetDeepCopy();
                        BitString payload = param.Payload.GetDeepCopy();
                        SetupNextOuterLoopValues(ref iv, ref key, ref payload, j, previousPlainTexts);
                        param.Iv      = iv.GetDeepCopy();
                        param.Key     = key.GetDeepCopy();
                        param.Payload = payload.GetDeepCopy();
                    }
                }
            }
            catch (Exception ex)
            {
                ThisLogger.Debug($"i count {i}, j count {j}");
                ThisLogger.Error(ex);
                return(new MCTResult <AlgoArrayResponse>(ex.Message));
            }

            return(new MCTResult <AlgoArrayResponse>(responses));
        }
Esempio n. 8
0
        /// <summary>
        /// 将获取到的消息重新发送到队列中, 根据配置, 可以转发到其他MQ队列, 也可以执行重试计数
        /// </summary>
        protected void ReSendMQ()
        {
            if (CurrentMessage == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(MyConfig.RetryAddress) == false)
            {
                //失败转发
                try
                {
                    MessageQueueTools.SendMessage(MyConfig.RetryAddress, CurrentMessage);
                }
                catch (Exception ex)
                {
                    ThisLogger.Error(ex, MyConfig.RetryAddress, CurrentMessage.Body);
                }
            }
            else if (MyConfig.RetryCount > 0)
            {
                //失败重试
                int TryTimes = 0;

                try
                {
                    if (string.IsNullOrEmpty(CurrentMessage.Label) || int.TryParse(CurrentMessage.Label, out TryTimes) == false)
                    {
                        TryTimes = 0;
                    }

                    if (TryTimes < MyConfig.RetryCount)
                    {
                        TryTimes = TryTimes + 1;

                        CurrentMessage.Label = Convert.ToString(TryTimes);

                        MessageQueueTools.SendMessage(MyConfig.Address, CurrentMessage);
                    }
                    else
                    {
                        ThisLogger.Warn(new LogInfo("{0}超过重试计数({1})", CurrentMessage.Body, TryTimes));
                    }
                }
                catch (Exception ex)
                {
                    ThisLogger.Error(ex, MyConfig.Address, CurrentMessage.Label);
                }
            }
        }
Esempio n. 9
0
        public HashResult HashMessage(HashFunction hashFunction, IEnumerable <BitString> tuple, BitString customizationHex)
        {
            try
            {
                var tupleHash = _iTupleHashFactory.GetTupleHash(hashFunction);
                var digest    = tupleHash.HashMessage(tuple, hashFunction.DigestLength, hashFunction.Capacity, hashFunction.XOF, customizationHex);

                return(new HashResult(digest));
            }
            catch (Exception ex)
            {
                ThisLogger.Error(ex);
                return(new HashResult(ex.Message));
            }
        }
Esempio n. 10
0
        public HashResult HashMessage(HashFunction hashFunction, BitString message, int blockSize, BitString customizationHex)
        {
            try
            {
                var parallelHash = _iParallelHashFactory.GetParallelHash(hashFunction);
                var digest       = parallelHash.HashMessage(message, hashFunction.DigestLength, hashFunction.Capacity, blockSize, hashFunction.XOF, customizationHex);

                return(new HashResult(digest));
            }
            catch (Exception ex)
            {
                ThisLogger.Error(ex);
                return(new HashResult(ex.Message));
            }
        }
Esempio n. 11
0
        public HashResult HashMessage(HashFunction hashFunction, BitString message, BitString customization, string functionName = "")
        {
            try
            {
                var sha    = _iCSHAKEFactory.GetCSHAKE(hashFunction);
                var digest = sha.HashMessage(message, hashFunction.DigestLength, hashFunction.Capacity, customization, functionName);

                return(new HashResult(digest));
            }
            catch (Exception ex)
            {
                ThisLogger.Error(ex);
                return(new HashResult(ex.Message));
            }
        }
Esempio n. 12
0
        private MCTResult <AlgoArrayResponse> Decrypt(IModeBlockCipherParameters param)
        {
            List <AlgoArrayResponse> responses = new List <AlgoArrayResponse>();

            int i = 0;
            int j = 0;

            try
            {
                for (i = 0; i < 100; i++)
                {
                    AlgoArrayResponse iIterationResponse = new AlgoArrayResponse()
                    {
                        Key        = param.Key,
                        CipherText = param.Payload
                    };

                    BitString jPlainText            = null;
                    BitString previousPlainText     = null;
                    BitString copyPreviousPlainText = null;
                    for (j = 0; j < 1000; j++)
                    {
                        var jResult = _algo.ProcessPayload(param);
                        jPlainText = jResult.Result;

                        param.Payload         = jPlainText;
                        copyPreviousPlainText = previousPlainText;
                        previousPlainText     = jPlainText;
                    }

                    iIterationResponse.PlainText = jPlainText;
                    responses.Add(iIterationResponse);

                    param.Key = _keyMaker.MixKeys(param.Key, previousPlainText, copyPreviousPlainText);
                }
            }
            catch (Exception ex)
            {
                ThisLogger.Debug($"i count {i}, j count {j}");
                ThisLogger.Error(ex);
                return(new MCTResult <AlgoArrayResponse>(ex.Message));
            }

            return(new MCTResult <AlgoArrayResponse>(responses));
        }
Esempio n. 13
0
        /*
         * Seed = random n bits, where n is digest size.
         *
         * For 100 iterations (j = 0)
         *     MD[0] = MD[1] = MD[2] = Seed
         *
         *     For 1000 iterations (i = 3)
         *         M[i] = MD[i-3] || MD[i-2] || MD[i-1]
         *         MD[i] = SHA(M[i])
         *
         *     MD[j] = Seed = MD[1002]      (last MD from inner loop)
         */
        #endregion MonteCarloAlgorithm Pseudocode

        public MctResult <AlgoArrayResponse> MctHash(BitString message, MathDomain domain = null, bool isSample = false)
        {
            if (isSample)
            {
                NUM_OF_RESPONSES = 3;
            }

            var responses = new List <AlgoArrayResponse>();
            var i         = 0;
            var j         = 0;

            try
            {
                for (i = 0; i < NUM_OF_RESPONSES; i++)
                {
                    BitString innerMessage = ResetDigestList(message);
                    BitString innerDigest  = null;

                    var iterationResponse = new AlgoArrayResponse
                    {
                        Message = innerMessage
                    };

                    for (j = 0; j < 1000; j++)
                    {
                        var innerResult = _sha.HashMessage(innerMessage);
                        innerDigest = innerResult.Digest;
                        AddDigestToList(innerDigest);
                        innerMessage = GetNextMessage();
                    }

                    iterationResponse.Digest = innerDigest;
                    responses.Add(iterationResponse);
                    message = innerDigest;
                }
            }
            catch (Exception ex)
            {
                ThisLogger.Debug($"i count {i}, j count {j}");
                ThisLogger.Error(ex);
                return(new MctResult <AlgoArrayResponse>(ex.Message));
            }

            return(new MctResult <AlgoArrayResponse>(responses));
        }
Esempio n. 14
0
        /// <summary>
        /// 线程轮询
        /// </summary>
        protected override void Execute()
        {
            ThisLogger.Debug(InternalThread.Name + "正在执行");

            while (!IsStop)
            {
                State = ZThreadState.SLEEP;

                bool CurrentExecute = CheckNeedRun();

                if (CurrentExecute == true && IsExecuting == false)
                {
                    IsExecuting = true;

                    State = ZThreadState.RUNNING;
                    //开始执行
                    CurrentExecuteTime = DateTime.Now;
                    try
                    {
                        Run(null);
                    }
                    catch (Exception ex)
                    {
                        ThisLogger.Error(ex);
                    }
                    finally
                    {
                        LastExecuteTime = CurrentExecuteTime;
                    }
                }
                else
                {
                    if (CurrentExecute == false)
                    {
                        IsExecuting = false;
                    }
                    Thread.Sleep(MyConfig.SleepTimeMillisecond);
                }
            }

            ThisLogger.Debug(Thread.CurrentThread.Name + "已停止");
            State = ZThreadState.STOP;
        }
Esempio n. 15
0
        /// <summary>
        /// Execute
        /// </summary>
        protected override void Execute()
        {
            ThisLogger.Debug(InternalThread.Name + "正在执行");

            while (!IsStop)
            {
                State = ZThreadState.SLEEP;

                if (DateTime.Now >= NextExecuteTime)
                {
                    State = ZThreadState.RUNNING;
                    //开始执行
                    CurrentExecuteTime = DateTime.Now;
                    try
                    {
                        Run(null);
                    }
                    catch (Exception ex)
                    {
                        ThisLogger.Error(ex);
                    }
                    finally
                    {
                        LastExecuteTime = CurrentExecuteTime;
                        NextExecuteTime = DateTime.Now.AddSeconds(MyConfig.ExecuteTimeSecond);
                    }
                }
                else
                {
                    Thread.Sleep(MyConfig.SleepTimeMillisecond);
                }
            }

            ThisLogger.Debug(Thread.CurrentThread.Name + "已停止");
            State = ZThreadState.STOP;
        }
Esempio n. 16
0
        /*
         *  INPUT: The initial Msg is the length of the digest size
         *
         *  MCT(Msg, MaxOutLen, MinOutLen, OutLenIncrement, MaxBlockSize, MinBlockSize)
         *  {
         *    Range = (MaxOutLen – MinOutLen + 1);
         *    OutputLen = MaxOutLen;
         *    BlockRange = (MaxBlockSize – MinBlockSize + 1);
         *    BlockSize = MinBlockSize;
         *    Customization = "";
         *
         *    Output[0] = Msg;
         *    for (j = 0; j < 100; j++)
         *    {
         *      for (i = 1; i < 1001; i++)
         *      {
         *        InnerMsg = Left(Output[i-1] || ZeroBits(128), 128);
         *        Output[i] = ParallelHash(InnerMsg, OutputLen, BlockSize, FunctionName, Customization);
         *        Rightmost_Output_bits = Right(Output[i], 16);
         *        OutputLen = MinOutLen + (floor((Rightmost_Output_bits % Range) / OutLenIncrement) * OutLenIncrement);
         *        BlockSize = MinBlockSize + Right(Rightmost_Output_bits, 8) % BlockRange;
         *        Customization = BitsToString(InnerMsg || Rightmost_Output_bits);
         *      }
         *
         *      OutputJ[j] = Output[1000];
         *    }
         *
         *    return OutputJ;
         *  }
         */
        #endregion MonteCarloAlgorithm Pseudocode

        public MctResult <AlgoArrayResponseWithCustomization> MCTHash(HashFunction function, BitString message, MathDomain outputLength, MathDomain blockSizeDomain, bool hexCustomization, bool isSample)
        {
            _hexCustomization = hexCustomization;
            if (isSample)
            {
                NUM_OF_RESPONSES = 3;
            }

            var responses    = new List <AlgoArrayResponseWithCustomization>();
            var i            = 0;
            var j            = 0;
            var min          = outputLength.GetDomainMinMax().Minimum;
            var max          = outputLength.GetDomainMinMax().Maximum;
            var increment    = outputLength.GetDomainMinMax().Increment;
            var minBlockSize = blockSizeDomain.GetDomainMinMax().Minimum;
            var maxBlockSize = blockSizeDomain.GetDomainMinMax().Maximum;

            var outputLen      = max;
            var blockSize      = minBlockSize;
            var blockSizeRange = (maxBlockSize - minBlockSize) + 1;
            var customization  = "";
            var range          = (max - min) + 1;
            var innerMessage   = message.GetDeepCopy();

            try
            {
                for (i = 0; i < NUM_OF_RESPONSES; i++)
                {
                    var innerDigest       = new BitString(0);
                    var iterationResponse = new AlgoArrayResponseWithCustomization()
                    {
                    };
                    iterationResponse.Message       = innerMessage;
                    iterationResponse.Customization = customization;
                    iterationResponse.BlockSize     = blockSize;

                    for (j = 0; j < 1000; j++)
                    {
                        // Might not have 128 bits to pull from so we pad with 0
                        innerMessage = BitString.ConcatenateBits(innerMessage, BitString.Zeroes(128))
                                       .GetMostSignificantBits(128);

                        function.DigestLength = outputLen;

                        var innerResult = _iParallelHash.HashMessage(function, innerMessage, blockSize, customization);
                        innerDigest = innerResult.Digest.GetDeepCopy();

                        // Will always have 16 bits to pull from
                        var rightmostBitString = innerDigest.GetLeastSignificantBits(16);

                        var rightmostBits = rightmostBitString.Bits;

                        outputLen     = min + (int)System.Math.Floor((double)(rightmostBits.ToInt() % range) / increment) * increment;
                        blockSize     = minBlockSize + rightmostBitString.GetLeastSignificantBits(8).Bits.ToInt() % blockSizeRange;
                        customization = GetStringFromBytes(BitString.ConcatenateBits(innerMessage, rightmostBitString).ToBytes());

                        innerMessage = innerDigest.GetDeepCopy();
                    }

                    iterationResponse.Digest = innerDigest.GetDeepCopy();
                    responses.Add(iterationResponse);
                }
            }
            catch (Exception ex)
            {
                ThisLogger.Debug($"i count {i}, j count {j}");
                ThisLogger.Error(ex);
                return(new MctResult <AlgoArrayResponseWithCustomization>($"{ex.Message}; {outputLen}"));
            }

            return(new MctResult <AlgoArrayResponseWithCustomization>(responses));
        }
Esempio n. 17
0
        /*
         * INPUT: The initial Msg of 128 bits long
         *
         * Initial Outputlen = (floor(maxoutlen/8) )*8
         * //makes maxoutlen a multiple of 8 and remains within the range specified.
         *
         * {
         *     Output0 = Msg;
         *     for (j=0; j<100; j++) {
         *         for (i=1; i<1001; i++) {
         *             M[i] = 128 leftmost bits of Output[i-1];
         *             Output[i] = SHAKE(M[i],Outputlen);
         *             If (i == 1000){
         *                 Outputlen[j] = Outputlen;
         *             }
         *             Rightmost_Output_bits = rightmost 16 bits of Output[i];
         *             Range = (maxoutbytes – minoutbytes + 1);
         *             Outputlen = minoutbytes + (Rightmost_Output_bits mod Range);
         *         }
         *         Output[j] = Output[1000];
         *         OUTPUT: Outputlen[j], Output[j]
         *     }
         * }
         */
        #endregion MonteCarloAlgorithm Pseudocode

        public MctResult <AlgoArrayResponse> MctHash(BitString message, MathDomain domain, bool isSample = false)
        {
            if (isSample)
            {
                NUM_OF_RESPONSES = 3;
            }

            var responses = new List <AlgoArrayResponse>();
            var i         = 0;
            var j         = 0;
            var min       = domain.GetDomainMinMax().Minimum;
            var max       = domain.GetDomainMinMax().Maximum;
            var minBytes  = min / 8;
            var maxBytes  = max / 8;

            var outputLen = (int)System.Math.Floor((double)max / 8) * 8;
            var range     = (max - min) + 8;
            //var range = (max - min) + min;

            var innerMessage = message.GetDeepCopy();

            // Might not have 128 bits to pull from so we pad with 0
            innerMessage = BitString.ConcatenateBits(innerMessage, BitString.Zeroes(128));
            innerMessage = BitString.MSBSubstring(innerMessage, 0, 128);

            try
            {
                for (i = 0; i < NUM_OF_RESPONSES; i++)
                {
                    var innerDigest       = new BitString(0);
                    var iterationResponse = new AlgoArrayResponse()
                    {
                    };
                    iterationResponse.Message = innerMessage;

                    for (j = 0; j < 1000; j++)
                    {
                        var innerResult = _sha.HashMessage(innerMessage, outputLen);
                        innerDigest = innerResult.Digest.GetDeepCopy();

                        // Will always have 16 bits to pull from
                        var rightmostBits = BitString.Substring(innerDigest, 0, 16).Bits;

                        outputLen = min + (8 * GetIntFromBits(rightmostBits)) % range;

                        innerMessage = innerDigest.GetDeepCopy();
                        // Might not have 128 bits to pull from so we pad with 0
                        innerMessage = BitString.ConcatenateBits(innerMessage, BitString.Zeroes(128));
                        innerMessage = BitString.MSBSubstring(innerMessage, 0, 128);
                    }

                    iterationResponse.Digest = innerDigest.GetDeepCopy();
                    responses.Add(iterationResponse);
                }
            }
            catch (Exception ex)
            {
                ThisLogger.Debug($"i count {i}, j count {j}");
                ThisLogger.Error(ex);
                return(new MctResult <AlgoArrayResponse>($"{ex.Message}; {outputLen}"));
            }

            return(new MctResult <AlgoArrayResponse>(responses));
        }
Esempio n. 18
0
        /// <summary>
        /// Execute
        /// </summary>
        protected override void Execute()
        {
            ThisLogger.Debug(InternalThread.Name + "已启动");
            State = ZThreadState.START;
            try
            {
                BinaryMessageFormatter formater = new BinaryMessageFormatter();

                while (!IsStop)
                {
                    State          = ZThreadState.SLEEP;
                    CurrentMessage = null;
                    CurrentMessage = TryReceiveMesssage();

                    try
                    {
                        if (CurrentMessage != null)
                        {
                            State = ZThreadState.RUNNING;
                            CurrentMessage.Formatter = formater;

                            if (CurrentMessage.Body != null)
                            {
                                CurrentExecuteTime = DateTime.Now;
                                try
                                {
                                    Run(CurrentMessage.Body);
                                }
                                catch (Exception ex)
                                {
                                    ThisLogger.Error(ex, MyConfig.Address, CurrentMessage.Body);

                                    //失败重发, 根据配置执行转发或者重试计数
                                    ReSendMQ();
                                }
                                finally
                                {
                                    LastExecuteTime = CurrentExecuteTime;
                                }
                            }
                            else
                            {
                                if (IsStop)
                                {
                                    break;
                                }
                                Thread.Sleep(MyConfig.SleepMilliSecond);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ThisLogger.Error(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                ThisLogger.Error(ex, MyConfig.Address);
            }

            ThisLogger.Debug(InternalThread.Name + "已停止");
            State = ZThreadState.STOP;
        }
Esempio n. 19
0
        /*
         *  INPUT: The initial Msg is the length of the digest size
         *
         *  MCT(Msg, MaxOutLen, MinOutLen, OutLenIncrement)
         *  {
         *    Range = (MaxOutLen – MinOutLen + 1);
         *    OutputLen = MaxOutLen;
         *    FunctionName = "";
         *    Customization = "";
         *
         *    Output[0] = Msg;
         *    for (j = 0; j < 100; j++)
         *    {
         *      for (i = 1; i < 1001; i++)
         *      {
         *        InnerMsg = Left(Output[i-1] || ZeroBits(128), 128);
         *        Output[i] = CSHAKE(InnerMsg, OutputLen, FunctionName, Customization);
         *        Rightmost_Output_bits = Right(Output[i], 16);
         *        OutputLen = MinOutLen + (floor((Rightmost_Output_bits % Range) / OutLenIncrement) * OutLenIncrement);
         *        Customization = BitsToString(InnerMsg || Rightmost_Output_bits);
         *      }
         *
         *      OutputJ[j] = Output[1000];
         *    }
         *
         *    return OutputJ;
         *  }
         */
        #endregion MonteCarloAlgorithm Pseudocode

        public MctResult <AlgoArrayResponseWithCustomization> MCTHash(HashFunction function, BitString message, MathDomain domain, bool customizationHex, bool isSample)
        {
            _customizationHex = customizationHex;

            if (isSample)
            {
                NUM_OF_RESPONSES = 3;
            }

            var responses = new List <AlgoArrayResponseWithCustomization>();
            var i         = 0;
            var j         = 0;
            var min       = domain.GetDomainMinMax().Minimum;
            var max       = domain.GetDomainMinMax().Maximum;
            var increment = domain.GetDomainMinMax().Increment;

            //var outputLen = (int)System.Math.Floor((double)max / 8) * 8;
            var outputLen     = max;
            var customization = "";
            var functionName  = "";
            var range         = (max - min) + 1;
            var innerMessage  = message.GetDeepCopy();

            try
            {
                for (i = 0; i < NUM_OF_RESPONSES; i++)
                {
                    var innerDigest       = new BitString(0);
                    var iterationResponse = new AlgoArrayResponseWithCustomization()
                    {
                    };
                    iterationResponse.Message       = innerMessage;
                    iterationResponse.Customization = customization;

                    for (j = 0; j < 1000; j++)
                    {
                        // Might not have 128 bits to pull from so we pad with 0
                        innerMessage          = BitString.ConcatenateBits(innerMessage, BitString.Zeroes(128));
                        innerMessage          = BitString.MSBSubstring(innerMessage, 0, 128);
                        function.DigestLength = outputLen;

                        var innerResult = _iCSHAKE.HashMessage(function, innerMessage, customization, functionName);
                        innerDigest = innerResult.Digest.GetDeepCopy();

                        // Will always have 16 bits to pull from
                        var rightmostBitString = BitString.Substring(innerDigest, 0, 16);
                        var rightmostBits      = rightmostBitString.Bits;

                        //outputLen = min + (8 * rightmostBits.ToInt()) % range;
                        outputLen     = min + (int)System.Math.Floor((double)(rightmostBits.ToInt() % range) / increment) * increment;
                        customization = GetStringFromBytes(BitString.ConcatenateBits(innerMessage, rightmostBitString).ToBytes());

                        innerMessage = innerDigest.GetDeepCopy();
                    }

                    iterationResponse.Digest = innerDigest.GetDeepCopy();
                    responses.Add(iterationResponse);
                }
            }
            catch (Exception ex)
            {
                ThisLogger.Debug($"i count {i}, j count {j}");
                ThisLogger.Error(ex);
                return(new MctResult <AlgoArrayResponseWithCustomization>($"{ex.Message}; {outputLen}"));
            }

            return(new MctResult <AlgoArrayResponseWithCustomization>(responses));
        }
Esempio n. 20
0
        private void PopulateSchedule(byte[,] keyData)
        {
            try
            {
                byte[,] tempKeyData = new byte[4, KeyCount];
                Schedule            = new byte[Rounds + 1, 4, BlockCount];
                for (int j = 0; j < KeyCount; j++)
                {
                    for (int i = 0; i < 4; i++)
                    {
                        tempKeyData[i, j] = keyData[i, j];
                    }
                }
                int t = 0;
                for (int j = 0; (j < KeyCount) && (t < (Rounds + 1) * BlockCount); j++, t++)
                {
                    for (int i = 0; i < 4; i++)
                    {
                        Schedule[t / BlockCount, i, t % BlockCount] = tempKeyData[i, j];
                    }
                }

                int rconpointer = 0;
                while (t < (Rounds + 1) * BlockCount)
                {
                    /* calculate new values */
                    for (int i = 0; i < 4; i++)
                    {
                        //XOR
                        tempKeyData[i, 0] ^= RijndaelBoxes.S[tempKeyData[(i + 1) % 4, KeyCount - 1]];
                    }
                    tempKeyData[0, 0] ^= RijndaelBoxes.rcon[rconpointer++];

                    if (KeyCount != 8)
                    {
                        for (int j = 1; j < KeyCount; j++)
                        {
                            for (int i = 0; i < 4; i++)
                            {
                                tempKeyData[i, j] ^= tempKeyData[i, j - 1];
                            }
                        }
                    }
                    else
                    {
                        for (int j = 1; j < KeyCount / 2; j++)
                        {
                            for (int i = 0; i < 4; i++)
                            {
                                tempKeyData[i, j] ^= tempKeyData[i, j - 1];
                            }
                        }

                        for (int i = 0; i < 4; i++)
                        {
                            tempKeyData[i, KeyCount / 2] ^= RijndaelBoxes.S[tempKeyData[i, KeyCount / 2 - 1]];
                        }

                        for (int j = KeyCount / 2 + 1; j < KeyCount; j++)
                        {
                            for (int i = 0; i < 4; i++)
                            {
                                tempKeyData[i, j] ^= tempKeyData[i, j - 1];
                            }
                        }
                    }
                    /* copy values into the schedule*/
                    for (int j = 0; (j < KeyCount) && (t < (Rounds + 1) * BlockCount); j++, t++)
                    {
                        for (int i = 0; i < 4; i++)
                        {
                            Schedule[t / BlockCount, i, t % BlockCount] = tempKeyData[i, j];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ThisLogger.Error(ex);
                ErrorMessage = ex.Message;
            }
        }
Esempio n. 21
0
        /*
         *  INPUT: The initial Single-Tuple of a random length between 0 and 65536 bits.
         *
         *  MCT(Tuple, MaxOutLen, MinOutLen, OutLenIncrement)
         *  {
         *    Range = (MaxOutLen – MinOutLen + 1);
         *    OutputLen = MaxOutLen;
         *    Customization = "";
         *
         *    T[0][0] = Tuple;
         *
         *    for (j = 0; j < 100; j++)
         *    {
         *      for (i = 1; i < 1001; i++)
         *      {
         *        workingBits = Left(T[i-1][0] || ZeroBits(288), 288);
         *        tupleSize = Left(workingBits, 3) % 4 + 1; // never more than 4 tuples to a round
         *        for (k = 0; k < tupleSize; k++)
         *        {
         *          T[i][k] = Substring of workingBits from (k * 288 / tupleSize) to ((k+1) * 288 / tupleSize - 1);
         *        }
         *        Output[i] = TupleHash(T[i], OutputLen, Customization);
         *        Rightmost_Output_bits = Right(Output[i], 16);
         *        OutputLen = MinOutLen + (floor((Rightmost_Output_bits % Range) / OutLenIncrement) * OutLenIncrement);
         *        Customization = BitsToString(T[i][0] || Rightmost_Output_bits);
         *      }
         *
         *      OutputJ[j] = Output[1000];
         *    }
         *
         *    return OutputJ;
         *  }
         */
        #endregion MonteCarloAlgorithm Pseudocode

        public MCTResultTuple <AlgoArrayResponse> MCTHash(HashFunction function, IEnumerable <BitString> tuple, MathDomain domain, bool hexCustomization, bool isSample)
        {
            _hexCustomization = hexCustomization;
            if (isSample)
            {
                NUM_OF_RESPONSES = 3;
            }

            var responses = new List <AlgoArrayResponse>();
            var i         = 0;
            var j         = 0;
            var min       = domain.GetDomainMinMax().Minimum;
            var max       = domain.GetDomainMinMax().Maximum;
            var increment = domain.GetDomainMinMax().Increment;
            var minBytes  = min / 8;
            var maxBytes  = max / 8;

            var outputLen     = max;
            var customization = "";
            var range         = (max - min) + 1;
            var innerTuple    = GetDeepCopy(tuple);

            try
            {
                for (i = 0; i < NUM_OF_RESPONSES; i++)
                {
                    var innerDigest       = new BitString(0);
                    var iterationResponse = new AlgoArrayResponse()
                    {
                    };
                    iterationResponse.Tuple         = innerTuple;
                    iterationResponse.Customization = customization;

                    for (j = 0; j < 1000; j++)
                    {
                        // Might not have 144 bits to pull from so we pad with 0
                        var innerBitString = BitString.ConcatenateBits(innerTuple.ElementAt(0), BitString.Zeroes(288))
                                             .GetMostSignificantBits(288);
                        var innerTupleSize = innerBitString.GetMostSignificantBits(3).Bits.ToInt() % 4 + 1;
                        innerTuple = new List <BitString>();
                        for (int k = 0; k < innerTupleSize; k++)
                        {
                            innerTuple.Add(BitString.MSBSubstring(innerBitString, k * 288 / innerTupleSize, 288 / innerTupleSize));
                        }

                        function.DigestLength = outputLen;

                        var innerResult = _iTupleHash.HashMessage(function, innerTuple, customization);
                        innerDigest = innerResult.Digest.GetDeepCopy();

                        // Will always have 16 bits to pull from
                        var rightmostBitString = BitString.Substring(innerDigest, 0, 16);
                        var rightmostBits      = rightmostBitString.Bits;

                        outputLen     = min + (int)System.Math.Floor((double)(rightmostBits.ToInt() % range) / increment) * increment;
                        customization = GetStringFromBytes(BitString.ConcatenateBits(innerTuple.ElementAt(0), rightmostBitString).ToBytes());

                        innerTuple = new List <BitString>();
                        innerTuple.Add(innerDigest.GetDeepCopy());
                    }

                    iterationResponse.Digest = innerDigest.GetDeepCopy();
                    responses.Add(iterationResponse);
                }
            }
            catch (Exception ex)
            {
                ThisLogger.Debug($"i count {i}, j count {j}");
                ThisLogger.Error(ex);
                return(new MCTResultTuple <AlgoArrayResponse>($"{ex.Message}; {outputLen}"));
            }

            return(new MCTResultTuple <AlgoArrayResponse>(responses));
        }