Esempio n. 1
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. 2
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. 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
        public virtual BitString GHash(BitString h, BitString x)
        {
            //ThisLogger.Debug("GHash");
            if (h.BitLength != 128)
            {
                return(null);
            }
            if (x.BitLength % 128 != 0 || x.BitLength == 0)
            {
                ThisLogger.Debug(x.BitLength);
                return(null);
            }

            // Step 1: Let X1,...,Xm-1,Xm denote the unique sequence of blocks such that
            // X = X1 || X2 || ... || Xm-1 || Xm
            int m = x.BitLength / 128;

            // Step 2: Let Y0 be the "zero block" 0^128
            var y = BitString.Zeroes(128);

            // Step 3: For i = 1,...,m let Yi = (Yi-1 xor Xi) dot H
            for (int i = 0; i < m; ++i)
            {
                BitString xi     = x.Substring((m - i - 1) * 128, 128);
                BitString YxorXi = BitString.XOR(y, xi);
                y = BlockProduct(YxorXi, h);
            }

            return(y);
        }
Esempio n. 5
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. 6
0
        protected override DrbgStatus ReseedAlgorithm(BitString entropyInput, BitString additionalInput)
        {
            BitString seedMaterial;

            additionalInput = additionalInput.GetDeepCopy();

            if (!DrbgParameters.DerFuncEnabled)
            {
                // 1. temp = len(additional_input)
                int temp = additionalInput.BitLength;

                // 2. If (temp < seedlen) then additional_input =
                // additional_input || 0^(seedlen - temp)
                if (temp < CounterAttributes.SeedLength)
                {
                    additionalInput = additionalInput
                                      .ConcatenateBits(new BitString(CounterAttributes.SeedLength - temp)); // Concatenate with bitstring made up of 0s;
                }

                if (additionalInput.BitLength != CounterAttributes.SeedLength)
                {
                    ThisLogger.Debug($"{nameof(additionalInput.BitLength)} != {nameof(CounterAttributes.SeedLength)}");
                    return(DrbgStatus.Error);
                }

                // 3. seed_material = entropy_input xor additional_input
                seedMaterial = entropyInput.XOR(additionalInput);
            }
            else
            {
                // 1. seed_material = entropy_input || additional_input
                seedMaterial = entropyInput.ConcatenateBits(additionalInput);

                // 2. seed_material = Block_Cipher_df(seed_material, seedlen)
                var blockCipherDf = BlockCipherDf(seedMaterial, CounterAttributes.SeedLength);
                if (blockCipherDf.Success)
                {
                    seedMaterial = blockCipherDf.Bits;
                }
                else
                {
                    ThisLogger.Debug("blockCipherDf");
                    return(DrbgStatus.Error);
                }
            }

            // 3./4. (Key, V) = Update(seed_material, Key, V)
            Update(seedMaterial);

            // 4./5. reseed_counter = 1
            ReseedCounter = 1;

            // 5./6. Return V, Key, and reseed_counter as the new_working_state
            // NOTE: m_V, m_Key, and m_reseed_counter hold the new working state
            return(DrbgStatus.Success);
        }
Esempio n. 7
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. 9
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. 10
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. 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
        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. 13
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. 14
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. 15
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. 16
0
        private DrbgStatus InstantiateDf(BitString entropyInput, BitString nonce, BitString personalizationString)
        {
            Debug.Assert(personalizationString.BitLength <= Attributes.MaxPersonalizationStringLength);

            // 1. seed_material = entropy_input || nonce || personalization_string
            BitString seedMaterial = entropyInput
                                     .ConcatenateBits(nonce)
                                     .ConcatenateBits(personalizationString);

            // 2. seed_material = Block_Cipher_df(seed_material, seedlen)
            // Comment: Ensure that the length of the seed material is exactly seedlen
            // bits
            var blockCipherDf = BlockCipherDf(seedMaterial, CounterAttributes.SeedLength);

            if (blockCipherDf.Success)
            {
                seedMaterial = blockCipherDf.Bits;
            }
            else
            {
                ThisLogger.Debug("blockCipherDf");
                return(DrbgStatus.Error);
            }

            Debug.Assert(seedMaterial.BitLength == CounterAttributes.SeedLength);

            // 3. Key = 0^keylen
            // Comment: keylen bits of zeros
            Key = new BitString(CounterAttributes.KeyLength);

            // 4. V = 0^outlen
            // Comment: outlen bits of zeros
            V = new BitString(CounterAttributes.OutputLength);

            // 5. (Key, V) = Update(seed_material, Key, V)
            Update(seedMaterial);

            // 6. reseed_counter = 1
            ReseedCounter = 1;

            // 7. Return V, Key, and reseed_counter as the initial_working_state
            // V, Key, ReseedCounter hold the inital working state
            return(DrbgStatus.Success);
        }
Esempio n. 17
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. 18
0
        public DrbgStatus Instantiate(int requestedSecurityStrength, BitString personalizationString)
        {
            // 1. check security strength
            if (requestedSecurityStrength > Attributes.MaxSecurityStrength)
            {
                return(DrbgStatus.RequestedSecurityStrengthTooHigh);
            }

            // 3. personalization string
            if (personalizationString.BitLength > Attributes.MaxPersonalizationStringLength)
            {
                return(DrbgStatus.PersonalizationStringTooLong);
            }

            // 4. Set security_strength to the nearest security strength greater
            // than or equal to requested_instantiation_security_strength

            // 5. Using security_strength, select appropriate DRBG mechanism parameters
            // Depricated Null step for preserving numbering

            // 6. (status, entropy_input) = Get_entropy_input( ... )
            BitString entropyInput = EntropyProvider.GetEntropy(DrbgParameters.EntropyInputLen);

            DrbgState.LastEntropy = entropyInput;

            // 7. If an ERROR is returned in step 6, return a CATASTROPHIC_ERROR_FLAG
            if (entropyInput.BitLength != DrbgParameters.EntropyInputLen)
            {
                ThisLogger.Debug($"{nameof(entropyInput)} length != {nameof(DrbgParameters.EntropyInputLen)}");
                return(DrbgStatus.CatastrophicError);
            }

            // 8. Obtain a nonce
            // Comment: this step shall include any appropriate checks on the
            // acceptability of the nonce.  See Section 8.6.7 of SP 800-90
            BitString nonce = EntropyProvider.GetEntropy(DrbgParameters.NonceLen);

            DrbgState.LastNonce = nonce;

            // 9. Initial working state
            IsInstantiated = true;
            return(InstantiateAlgorithm(entropyInput, nonce, personalizationString));
        }
Esempio n. 19
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. 20
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. 21
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. 22
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. 23
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. 24
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. 25
0
        private DrbgResult GenerateAlgorithmDf(int requestedNumberOfBits, BitString additionalInput)
        {
            additionalInput = additionalInput.GetDeepCopy();

            // 1. If reseed_counter > reseed_interval, then return an indication that
            // a reseed is required
            if (ReseedCounter > Attributes.MaxNumberOfRequestsBetweenReseeds)
            {
                return(new DrbgResult(DrbgStatus.ReseedRequired));
            }

            // 2. If (additional_input != Null), then
            if (additionalInput.BitLength != 0)
            {
                // 2.1 additional_input = Block_Cipher_df(additional_input, seedlen)
                var blockCipherDf = BlockCipherDf(additionalInput, CounterAttributes.SeedLength);

                if (blockCipherDf.Success)
                {
                    additionalInput = blockCipherDf.Bits;
                }
                else
                {
                    ThisLogger.Debug("BlockCipherDf");
                    return(new DrbgResult(DrbgStatus.Error));
                }

                // 2.2 (Key, V) = Update(additional_input, Key, V)
                Update(additionalInput);
            }
            else
            {
                // 2 (cont) Else additional_input = 0^seedlen
                additionalInput = new BitString(CounterAttributes.SeedLength);
            }

            // 3. temp = Null
            BitString temp = new BitString(0);

            // 4. While (len(temp) < requested_number_of_bits) do:
            while (temp.BitLength < requestedNumberOfBits)
            {
                // 4.1 V = (V + 1) mod 2^outlen
                V = V.BitStringAddition(BitString.One()).GetLeastSignificantBits(CounterAttributes.OutputLength);

                // 4.2 output_block = Block_Encrypt(Key, V)
                BitString outputBlock = BlockEncrypt(Key, V);
                // 4.3 temp = temp || output_block
                temp = temp.ConcatenateBits(outputBlock);
            }

            // 5. returned_bits = Leftmost requested_number_of_bits of temp
            var returnedBits = temp.GetMostSignificantBits(requestedNumberOfBits);

            // 6. (Key, V) = Update(additional_input, Key, V)
            // Comment: Update for backtracking resistance
            Update(additionalInput);

            // 7. reseed_counter = reseed_counter + 1
            ++ReseedCounter;

            // 8. Return SUCCESS and returned bits; also return Key, V and
            // reseed_counter as the new_working_state
            // NOTE: returned_bits is a function parameter passed by non-const
            // value.  m_Key, m_V, and m_reseed_counter hold the new working state
            return(new DrbgResult(returnedBits));
        }
Esempio n. 26
0
        // Public for BlockCipherConditioningComponent
        public DrbgResult BlockCipherDf(BitString seedMaterial, int numberOfBitsToReturn)
        {
            int maxNumberOfBits = 512;

            // Check that input string is a multiple of 8 bits
            if (seedMaterial.BitLength % 8 != 0)
            {
                ThisLogger.Debug($"{nameof(seedMaterial)} not mod 8");
                return(new DrbgResult(DrbgStatus.Error));
            }

            // 1. If (no_of_bits_to_return > max_number_of_bits) then return
            // and ERROR_FLAG
            if (numberOfBitsToReturn > maxNumberOfBits)
            {
                ThisLogger.Debug($"{nameof(seedMaterial)} gt {nameof(maxNumberOfBits)}");
                return(new DrbgResult(DrbgStatus.Error));
            }

            // 2. L = len(input_string)/8
            // Comment: L is the bitstring representation of the integer resulting
            // from len(input_string)/8. L shall be represented as a 32-bit integer.
            //BitString l = new BitString(new BigInteger(seedMaterial.BitLength / 8)).GetLeastSignificantBits(4 * 8);
            BitString l = new BitString(BitConverter.GetBytes(seedMaterial.BitLength / 8).Reverse().ToArray());

            // 3. N = no_of_bits_to_return/8
            // Comment: N is the bitstring representation of the integer resulting
            // from number_of_bits_to_return/8.  N shall be represented as a 32-bit
            // integer
            //BitString n = new BitString(new BigInteger(numberOfBitsToReturn / 8)).GetLeastSignificantBits(4 * 8);
            BitString n = new BitString(BitConverter.GetBytes(numberOfBitsToReturn / 8).Reverse().ToArray());

            // 3. S = L || N || input_string || 0x80
            // Comment: Prepend the string length and the requested length of the
            // output to the input_string
            // NOTE: SP800-90 has step 3 twice
            BitString s = l
                          .ConcatenateBits(n)
                          .ConcatenateBits(seedMaterial)
                          .ConcatenateBits(new BitString("80"));

            // 4. While (len(S) mod outlen) != 0, S = S || 0x00
            // Comment: Pad S with zeros if necessary
            while ((s.BitLength % CounterAttributes.OutputLength) != 0)
            {
                s = s
                    .ConcatenateBits(BitString.Zero());
            }

            // 5. temp = the Null string
            // Comment: compute the starting value
            BitString temp = new BitString(0);

            // 6. i = 0
            // Comment: i shall be represented as a 32-bit integer, i.e., len(i) = 32
            int i = 0;

            byte[] bt = new byte[32];
            for (int iterator = 0; iterator < 32; iterator++)
            {
                bt[iterator] = (byte)iterator;
            }

            // 7. Key = leftmost keylen bits of 0x000102030405
            BitString k = new BitString(bt).GetMostSignificantBits(CounterAttributes.KeyLength);

            // 8. While len(temp)< keylen + outlen, do:
            while (temp.BitLength < (CounterAttributes.KeyLength + CounterAttributes.OutputLength))
            {
                // 8.1 IV = i || 0^(outlen - len(i))
                BitString iv = new BitString(BitConverter.GetBytes(i).Reverse().ToArray())
                               .ConcatenateBits(new BitString(CounterAttributes.OutputLength - 32));
                // 8.2 temp = temp || BCC(Key, (IV || S))
                temp = temp
                       .ConcatenateBits(BCC(k, iv.ConcatenateBits(s)));

                i++;
            }

            // 9. Key = Leftmost keylen bits of temp
            k = temp.GetMostSignificantBits(CounterAttributes.KeyLength);

            // 10. X = Next outlen bits of temp
            int       istart = temp.BitLength - CounterAttributes.KeyLength - CounterAttributes.OutputLength;
            BitString x      = temp.Substring(istart, CounterAttributes.OutputLength);

            // 11. temp = the Null string
            temp = new BitString(0);

            // 12. While len(temp) < number_of_bits_to_return, do:
            while (temp.BitLength < numberOfBitsToReturn)
            {
                // 12.1 X = Block_Encrypt(Key, X)
                x = BlockEncrypt(k, x);
                // 12.2 temp = temp || X
                temp = temp.ConcatenateBits(x);
            }

            // 13. requested_bits = Leftmost no_of_bits_to_return of temp
            return(new DrbgResult(temp.GetMostSignificantBits(numberOfBitsToReturn)));
        }
Esempio n. 27
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));
        }
Esempio n. 28
0
        public DrbgResult Generate(int requestedNumberOfBits, BitString additionalInput)
        {
            BitString EmptyBitString = new BitString(0);

            additionalInput = additionalInput.GetDeepCopy();

            // 1. Using state_handle, obtain current internal state for the
            // instantiation.  If state_handle indicates an invalid or unused
            // internal state, then return an ERROR_FLAG
            // NOTE: class member m_s hold internal state

            // 2. If requested_number_of_bits > max_number_of_bits_per_request, then
            // return an ERROR_FLAG
            if (requestedNumberOfBits > Attributes.MaxNumberOfBitsPerRequest)
            {
                ThisLogger.Debug($"{nameof(requestedNumberOfBits)} > {nameof(Attributes.MaxNumberOfBitsPerRequest)}");
                return(new DrbgResult(DrbgStatus.Error));
            }

            // 3. If requested_security_strength > security_strength indicated in the
            // internal state, then return an ERROR_FLAG
            // NOTE: this implementation does not support this paramter.  The securityMaxAdditionalInputLength
            // sterngth set at instantiation is what is used

            // 4. If the length of the additional_input > max_additional_input_length,
            // then return an ERROR_FLAG
            if (additionalInput.BitLength > Attributes.MaxAdditionalInputStringLength)
            {
                ThisLogger.Debug($"{nameof(additionalInput)} > {nameof(Attributes.MaxAdditionalInputStringLength)}");
                return(new DrbgResult(DrbgStatus.Error));
            }

            // 5. If prediction_resistance_request is set and
            // prediction_resistance_flag is not set, then return an ERROR_FLAG
            // No request parameter is passed into generate; the flag passed into
            // instantiate is stored in a class member
            // NOTE: all implementations support prediction resistance

            // 6. Clear the reseed_required_flag
            bool reseedRequired = false;

            while (true)
            {
                // 7. If reseed_required_flag is set, or if prediction_resistance_request
                // is set, then
                if (DrbgParameters.PredResistanceEnabled || reseedRequired)
                {
                    // 7.1 status = Reseed_function(additional_input)
                    // NOTE: we have two versions of reseed; one takes an entropy
                    // input passed in as a parameter for the purposes of testing
                    // and verification
                    var reseed = Reseed(additionalInput);

                    // 7.2 If status indicates an ERROR, then return status
                    if (reseed != DrbgStatus.Success)
                    {
                        ThisLogger.Debug("Reseed failed");
                        return(new DrbgResult(reseed));
                    }

                    // 7.3 Using state_handle, obtain the new internal state
                    // NOTE: internal state in class member m_s, updated in
                    // member function reseed
                    // 7.4 additional_input = the Null string
                    additionalInput = EmptyBitString.GetDeepCopy();
                    // 7.5 Clear the reseed_required_flag
                    reseedRequired = false;
                }

                // 8. (status, pseudorandom_bits, new_working_state) = Generate_algorithm(
                // working_state, requested_number_of_bits, additional_input)
                var result = GenerateAlgorithm(requestedNumberOfBits, additionalInput);

                // 9. If status indicates that a reseed is required before the requested
                // bits can be generated, then
                if (result.DrbgStatus == DrbgStatus.ReseedRequired)
                {
                    // 9.1 Set the reseed_required_flag
                    reseedRequired = true;
                    // 9.2 Go to step 7
                }
                else
                {
                    return(result);
                }
            }
        }
Esempio n. 29
0
        public virtual BitString GCTR(BitString icb, BitString x, BitString key)
        {
            // ICB must be 128 bits long
            // ThisLogger.Debug("GCTR");
            if (icb.BitLength != 128)
            {
                ThisLogger.Warn($"icbLen:{icb.BitLength}");
                return(null);
            }

            // Step 1: If X is the empty string, then return the empty string as Y
            if (x.BitLength == 0)
            {
                return(new BitString(0));
            }

            var ecb = _modeFactory.GetStandardCipher(
                _engineFactory.GetSymmetricCipherPrimitive(BlockCipherEngines.Aes),
                BlockCipherModesOfOperation.Ecb
                );

            // Step 2: Let n = ceil[ len(X)/128 ]
            int n = x.BitLength.CeilingDivide(128);

            // Step 3: Let X1,X2,...,Xn-1,Xn denote the unique sequence of bit
            // strings such that X = X1 || X2 || ... || Xn-1 || Xn*
            // X1, X2,...,Xn-1 are complete blocks
            // Xn* is either a complete block or a partial block

            // Step 4: Let CB1 = ICB
            // Step 5: For i = 2 to n, let CBi = inc32(CBi-1)
            // Step 6: For i = 1 to n-1, let Yi = Xi xor CIPH_K(CBi)

            BitString cbi = icb;
            BitString Y   = new BitString(0);
            int       sx  = x.BitLength - 128;

            for (int i = 1; i <= (n - 1); ++i, sx -= 128)
            {
                if (i > 1)
                {
                    cbi = inc_s(32, cbi);
                }
                BitString xi       = x.Substring(sx, 128);
                var       cbiParam = new ModeBlockCipherParameters(
                    BlockCipherDirections.Encrypt,
                    key,
                    cbi
                    );
                var       h  = ecb.ProcessPayload(cbiParam);
                BitString yi = BitString.XOR(xi, h.Result);
                Y = Y.ConcatenateBits(yi);    // This is part of Step 8
            }

            // Step 7: Let Yn* = Xn* xor MSB_len(Xn*) (CIPH_K(CBn))
            // i == n case:
            if (n > 1)
            {
                cbi = inc_s(32, cbi);
            }

            var xn        = x.Substring(0, 128 + sx);
            var cbiParam1 = new ModeBlockCipherParameters(
                BlockCipherDirections.Encrypt,
                key,
                cbi
                );
            var h1 = ecb.ProcessPayload(cbiParam1);

            var yn = xn.XOR(h1.Result.GetMostSignificantBits(xn.BitLength));

            Y = Y.ConcatenateBits(yn); // This is part of Step 8

            // Step 8: Let Y = Y1 || ... || Yn*

            // Step 9: Return Y
            return(Y);
        }