Beispiel #1
0
        public static string printBytes(BytesBuilder bb, bool masked)
        {
            var sb = new StringBuilder();

            var bytes = bb.getBytes();

            if (masked)
            {
                for (int i = 0; i < bytes.LongLength; i += 2)
                {
                    if (bytes[i] != 13 && bytes[i] != 10)
                        #if forLinux
                    { sb.Append("*"); }
                        #else
                    { sb.Append(/*"•"*//*"®"*/ "●"); }
                        #endif
                    else
                    if (bytes[i] == 10)
                    {
                        sb.Append("\r");
                    }

                    /*else
                     *  sb.Append("\n");*/
                }
Beispiel #2
0
        private static void GetKeyByPassword(int regime, byte[] bytes, out byte[] key)
        {
            SHA3 sha = new SHA3(bytes.Length);

            if (regime < 10)
            {
                sha.useOldDuplex = true;
            }

            int pc  = 4;
            var oiv = regime >= 20 ?
                      Convert.FromBase64String("dm1gZGxLOObGEsQBBg09Nuhi1dnMdzue40B2cvfvff10nVbQQ7JwSvhtZfiJbnFoCG492Us7jPAMnWvYl5RYCsQSUS5TIZ8+7p3chQ7/SpclDR7MGHqCl6T/6LN7ikfVngdI1vZlCrQHDNB4yBynQwRLlMk0puvedDKJLOOcfu40R6/QezEIW3WpPU9qeVYzgwvhbfRrc6wP7WxWMR09Nh97ciY2io+FZ0fsQpCno25ptAIH1dzb1w2DbVLaqF03qz873LLBaHyNdH+4PN92sG9iJ+pOmAQGF/+Jq+TtOdO2TwnAv33rspm6aFpDaKQh4MpNPIhOZct8OhFIQs5r/L5kTNL+McswrZZXPUrWddmrETjMh7ZZ5SeudyfUvJT1MLOUO/K6b6YtGb0pq9VZ4W3K0vhlQBxzSh6ghoFzWCYkG+yNj6vF5iyBjW9R2PCy03lHNbfIy4X8LzAuMjCfxE4Rq7XiT4JcYRHRYXX+NDN2hQtaerzor4FzHJZGyvabz4Ob9+7lCHffL/DysHW660VcmiyZzoxsdM18/JnebllOmKBqJwR/GSci8hTuXca8eZ4TDnL/wJOPA5UOB8yqQ7uGFnfjHIY2Jq7Pyvfd9DingIMe0lkQMG+r6lPVjzxxwjyQ/xXXI7EYyAsD0HllrlcoACwWbLMLnQ3pe36Nl8RbEY3eftn9I7HwdtgfAsmTaxc7NAl2yetAHdf/iUZBUJ6mjKm8/2LeQZI1bxVVygVUZsTEDW1QZrXXEooIeTepxJaZSI8EMKLI9QTu3AEydto35MsD6DKN17jZnWoNXpC/USddnas25ZgtOZrNepPpSHzm+yociIf8sh8R6GwJjueapXP6HfvYQD+8rVOeVwDnjIKEZU2sV/PpQqrm7JgfT0MqehhxCSm8hvooCqW6WfNnCvUVFDRC4F/KD7douOooh3cGVjt2i2NZASBTSWZvXqimf9/MVDgP61L3JbpBlh7sWtBj4kL5PRoIxqqqiXp53gQumuV6Qtw8f0ryMQwrfLoXkFbMBcOaAv8nlBVpJzVBNnolJ1K7WxwTTWk51+cdN2oIazHGvgl9ccKgVBqZsg7dtlycu45mi/auhVNoAAVcw+wIwhH2jGmB79bnus7s+bDIdoW3+5oIPrb+bwJ8Hcz9nlQxjyifMuVOpNxH7gosBYBiqtGI5UI0SFygjMS7VLjICEJ025pNMypkxTVINbbBY2ouUoEU0K9X5OdM5b61Q+hB10h3+QtB44BlOW0jAVLVsVv0Y8BbZ8fkbZBdnv/aewwdEW7fsNA8bNqNAa212Ep/4m9n+f+LLOo1MXo4sGP8m0NqorIVrj3D3As4pF60l9Sc724P0t+y+yTuiqxG/20aHIxITSLY7St2AoucD7kKzq+ELAZ91uH4wQM/xfzg4SouaLXL/OU11ScmphAS0t5oK/Q6qW+b0Cz/6ucute1dYFoJ9eMw8zkRcUwEIk4nARBRPo+8Z1jDf0dyb/+NJHhvZHcY+WjaXBliN456SdXJjqZxAUh8qFMkoDoczAlFwBeZVvSQQWLxuCZigvvuFGtNJXt26TrhHSbUpK9SH9CthzK30kUMWQJIwXdImGjaN6NgU/TN23QEtjE2/7H2Cu6iheeV5w/5ampxoH4NXL0nAt+ZxI8z1pTYwiGHfXhcVS2AHktmBykTauJx1PpomAQODDq5kYat3+amO7knkoVWibRdIXEWzCf5x/5kusom2IY7j3foxnvrixRoLJmgVWgM07gb44iE3vAFvvJyYRWdikLyQMvyImu3+9Me5sungowXt96PS/IlNELAOWjKf3Il4eyuAGe6O2nbphOT+n22ftSIWsRiyXfbTRMmJcPg4ADu+wPej06nSjIa9mu28SYg9JtEZcyGV4LBnNRayuqBKqKwFS2NGl+yjEPN54LRom/dQd4YFzww9pdlU7NqF+D2123wtpDEZmOEeeg8YqDwSgeH2UYpXBkpv9gkqGinZ9MpZGJ3l8PClppQegEqg9lMxbxFEBoXxlmNA/P3vUCbGDc1gbOuDvhlYmeqddZwHAW6b1wqO93/E9SO7Isi/ngVlgEq5F9jQRPo/MrQdvAlJ4d9+Gq0ANqSTVU7mO08tmVhpTaVf0kxTs3pmfcPFvBsmg+7QXltsNl3xtHcfoPa0+RNC8UJO8WVVck+hJlproNtr/KcUCkfWY/CkkorBaCLrD9Wo0WTy2O3wCfJrcLLT8Rdkl4nk6B3FncfdBWfRyjMpocbxaVieCO5sFnCibTZIuYxxVRsd+NBBTBXifrVSkrYrHBidWgnnyMvNuRyTNodLO1AWEcX9QK2l2xlJPlvAFkQhYAv4ef+XDttRf09MjmJP44k7tIolOV3gGTFGgRToKXk5nlSXvXy8q0R42YOjhvzvOQ7AeYoI/bQ38p9cK3qu/5Di4Spjqn+B+oBoXai74LgQEmA5BdgyVC/hfdhfv47AclCoHbXIWZ+HDIUpRtQzIY9YoHtZaic/ern68niLVe0sOzeX7c2LrUsBIf6QhwZIlU5GSuoSl5m+zCGh6p3xflwd/gNd08QlIgmbE4G6aOqYB09uDjGho7VfY3Gy8qjzMjCzTSdeRc/ahbreVZUBGMqhS2TgdBoJu5u1+gnY5B320b44Ni61RFn1fKCaHMbYCJ4xusy8VzkcXmJFPqgY+0unSM3GXg5RQUx0DhOb+sdy7/7ocf+TpmOJFYSQYPsqsuqrfj27xDWiKjfRV/YyRC2BOsdItZn")
                                    : new UTF8Encoding().GetBytes("passwordJjVjRyjcWwo7761qPBQUb3Sx8DACNpassword");
            var dk = 1024;

            if (regime >= 20)
            {
                dk = regime >= 30 ? 16 : 24;
                if (regime >= 34)
                {
                    dk = 8;
                }
            }
            key = sha.getDerivatoKey(bytes, oiv, dk, ref pc, regime >= 20 ? bytes.Length << 1 : bytes.Length, regime / 10);

            sha.Clear(true);
            sha = null;
            BytesBuilder.ToNull(bytes);
        }
Beispiel #3
0
        /// <summary>
        /// Очень плохая гамма!
        /// </summary>
        /// <param name="key"></param>
        /// <param name="len"></param>
        /// <param name="stateLen"></param>
        /// <param name="notCopy"></param>
        /// <returns></returns>
        public static byte[] getGamma(byte[] key, int len, out int stateLen, bool notCopy = false)
        {
            if (key.Length > 65536)
            {
                throw new ArgumentOutOfRangeException();
            }

            var result = new byte[len];

            var kl = key.Length;
            var sl = 256;

            stateLen = sl;

            var k = key;
            var s = new byte[sl];
            var t = new byte[sl > kl ? sl : kl];

            if (!notCopy)
            {
                k = BytesBuilder.CloneBytes(key, 0, kl);
            }

            int C = kl >> 10;

            if (C < 2)
            {
                C = 2;
            }

            int kbit = 0;

            fixed(byte *kp = k, sp = s, tp = t, r = result)
            {
                for (int i = 0; i < sl; i++)
                {
                    sp[i] = (byte)i;
                }

                for (int i = 0; i < 4; i++)
                {
                    for (int j = 0; j < C; j++)
                    {
                        kbit = step(kl, sl, kbit, kp, sp, tp);
                    }
                }

                for (int i = 0; i < result.Length; i++)
                {
                    for (int j = 0; j < C; j++)
                    {
                        kbit = step(kl, sl, kbit, kp, sp, tp);
                    }

                    r[i] = getMask(sp, sl, sp[0]);
                }
            }

            return(result);
        }
Beispiel #4
0
 private static void fillKey(int CK, int i, ref byte[] key)
 {
     for (int j = 0; j < key.Length - 4; j += 2)
     {
         BytesBuilder.UIntToBytes((uint)i, ref key, j);
     }
 }
Beispiel #5
0
        public static int permutationMergeBytes(byte *key, int keyLen, byte *target, byte *tmp, int len, ref int kl, bool repeatKey = false)
        {
            if (len <= 1)
            {
                throw new ArgumentOutOfRangeException("len", "len <= 1");
            }

            byte *a1 = tmp, a2 = target;
            int   ended   = 0;
            int   counter = 0;

            for (int i = 1; i < len; i <<= 1)
            {
                counter += permutationMergeBytes_Iteration(i, a2, a1, len, key, keyLen, ref kl, ref ended, repeatKey);
                ended    = 0;

                byte *a = a1;
                a1 = a2;
                a2 = a;
            }

            if (a2 != target)
            {
                BytesBuilder.CopyTo(len, len, a2, a1);
            }

            return(counter);
        }
Beispiel #6
0
        public static byte[] getHash(byte[] value, int count)
        {
            var result = new byte[count];

            var kl = value.Length;
            var sl = 256;
            var s = new byte[sl];
            var t = new byte[sl];
            var n = new byte[0];
            int kbit = 0, kn = 0;

            fixed(byte *kp = value, sp = s, tp = t, np = n)
            {
                for (int i = 0; i < sl; i++)
                {
                    sp[i] = (byte)i;
                }

                for (int i = 0; i < count; i++)
                {
                    permutationMergeBytes(kp, kl, sp, tp, sl, ref kbit, true);
                    permutationMergeBytes(kp, kl, sp, tp, sl, ref kbit, true);
                    permutationMergeBytes(kp, kl, sp, tp, sl, ref kbit, true);
                    permutationMergeBytes(kp, kl, sp, tp, sl, ref kbit, true);

                    permutationMergeBytes(np, 0, sp, tp, sl, ref kn);
                    result[i] = sp[0];
                }

                BytesBuilder.ToNull(sl, tp);
                BytesBuilder.ToNull(sl, sp);
            }

            return(result);
        }
Beispiel #7
0
        public void recordsToFile()
        {
            StringBuilder sb = new StringBuilder();

            foreach (var record in records)
            {
                sb.AppendLine(record.Value.mainTag);
                sb.AppendLine(record.Value.crypt);
                sb.AppendLine(record.Value.pwd);
                foreach (var tag in record.Value.tags)
                {
                    sb.AppendLine(tag);
                }

                sb.AppendLine();
            }

            var content = sb.ToString();

            sb.Clear();

            var curKey = key.getObjectValue();
            var sha    = new SHA3(content.Length);
            var bytes  = sha.multiCryptLZMA(new UTF32Encoding().GetBytes(content), curKey, null, 22, false, 0, SHA3.getHashCountForMultiHash() - 8);

            File.WriteAllBytes(fileName, bytes);

            BytesBuilder.ClearString(content);
            BytesBuilder.ToNull(curKey);
            BytesBuilder.ToNull(bytes);
        }
Beispiel #8
0
 public void clearResultText()
 {
     if (String.IsNullOrEmpty(resultText))
     {
         BytesBuilder.ClearString(resultText);
     }
 }
Beispiel #9
0
Datei: Node.cs Projekt: fdsc/old
        static public byte[] getNewNodeID()
        {
            var  result = new byte[20 + 12];
            uint cn;

            lock (syncObject)
            {
                cyclicNumber++;
                if (cyclicNumber == 0 || cyclicNumber == unchecked ((uint)-1))  // для повышения надёжности двойная проверка на смену сессии
                {
                    newSessionGuid();
                    cyclicNumber++;
                }

                cn = unchecked (cyclicNumber + cyclicBase);

                BytesBuilder.CopyTo(sessionGuid, result);
            }

            byte[] target = null;
            BytesBuilder.ULongToBytes((ulong)DateTime.Now.Ticks, ref target);
            BytesBuilder.CopyTo(target, result, 20);

            target = null;
            BytesBuilder.UIntToBytes(cn, ref target);
            BytesBuilder.CopyTo(target, result, 28);


            return(result);
        }
            public static IEnumerable <SourceTask> GetIterator()
            {
                ulong size = 2048;

                for (ulong val = 0; val < (ulong)(size << 3); val++)
                {
                    var b1 = new byte[size];
                    BytesBuilder.ToNull(b1, 0xFFFF_FFFF__FFFF_FFFF);
                    BitToBytes.resetBit(b1, val);

                    var b2 = new byte[size];
                    BytesBuilder.ToNull(b2);
                    BitToBytes.setBit(b2, val);

                    yield return(new SourceTask()
                    {
                        Key = "Setted bits with val = " + val, Value = b1
                    });

                    yield return(new SourceTask()
                    {
                        Key = "Resetted bits with set bit #" + val, Value = b2
                    });
                }

                yield break;
            }
Beispiel #11
0
        private static bool checkDuplexModByHash(SHA3 sha3)
        {
            byte[] m1 = new byte[72 * 8 - 1];
            byte[] m2 = new byte[72 * 8 - 1];
            byte[] m  = new byte[m1.Length + m2.Length + 1];

            var rnd = new Random(98732796);

            for (int i = 0; i < m.Length; i++)
            {
                if (m.Length - i == 72)
                {
                    m[i] = 0x81;
                }
                else
                {
                    m[i] = (byte)rnd.Next(0, 255);
                }
            }

            rnd = new Random(98732796);
            for (int i = 0, j = 0, k = 0; i < m.Length - 1; i++)
            {
                if (i % 144 >= 72 || k >= m2.Length)
                {
                    m1[j++] = (byte)rnd.Next(0, 255);
                }
                else
                {
                    m2[k++] = (byte)rnd.Next(0, 255);
                }
            }

            byte[] hash  = sha3.getHash512(m);
            byte[] gamma = sha3.getDuplexMod(m1, m2);
            byte[] tmp   = new byte[64];
            BytesBuilder.CopyTo(gamma, tmp, 0, -1, 72 * 7);

            bool errorFlag = false;

            for (int i = 0; i < hash.Length; i++)
            {
                if (hash[i] != tmp[i])
                {
                    errorFlag = true;
                }
            }

            if (errorFlag)
            {
                Console.WriteLine("DuplexMod and hash unequal, duplexMod is incorrect");
            }
            else
            {
                Console.WriteLine("Well. DuplexMod and hash equal, duplexMod is correct.");
            }

            return(!errorFlag);
        }
Beispiel #12
0
        private static bool checkInitDuplex(SHA3 sha3)
        {
            byte[] keyAndMessage = new byte[72 * 8 - 1];

            var rnd = new Random(98732796);

            for (int i = 0; i < 64; i++)
            {
                keyAndMessage[i] = (byte)rnd.Next(0, 255);
            }

            keyAndMessage[64] = 0x01;
            keyAndMessage[71] = 0x80;

            for (int i = 72; i < keyAndMessage.Length; i++)
            {
                keyAndMessage[i] = (byte)rnd.Next(0, 255);
            }

            var kam1 = new byte[64];
            var kam2 = new byte[keyAndMessage.Length - 72];

            BytesBuilder.CopyTo(keyAndMessage, kam1);
            BytesBuilder.CopyTo(keyAndMessage, kam2, 0, -1, 72);

            byte[] dupi1 = sha3.getDuplex(kam1);
            byte[] dupi2 = sha3.getDuplex(kam2, true);
            byte[] dupe  = sha3.getDuplex(keyAndMessage);

            bool errorFlag = false;
            int  k;

            for (k = 0; k < dupi1.Length; k++)
            {
                if (dupi1[k] != dupe[k])
                {
                    errorFlag = true;
                }
            }
            for (int j = 0; j < dupi2.Length /* && k < dupe.Length*/; k++, j++)
            {
                if (dupi2[j] != dupe[k])
                {
                    errorFlag = true;
                }
            }

            if (errorFlag)
            {
                Console.WriteLine("Duplex and init duplex unequal, duplex is incorrect");
            }
            else
            {
                Console.WriteLine("Well. Duplex and init duplex equal, duplex is correct.");
            }

            return(!errorFlag);
        }
Beispiel #13
0
        /// <summary>
        /// Подготовить вызов функции getGamma
        /// </summary>
        /// <param name="key"></param>
        /// <param name="syncro"></param>
        /// <param name="SBox"></param>
        /// <param name="SBox2"></param>
        /// <param name="errorCipher">Этот параметр всегда должен быть false. Требуется для совместимости со старыми версиями шифра. GOST5 в getGamma должен быть установлен в false</param>
        public void prepareGamma(byte[] key, byte[] syncro, byte[] SBox, byte[] SBox2, byte[] SBox3 = null, byte[] SBox4 = null, byte[] SBox5 = null, byte[] SBox6 = null, bool errorCipher = false)
        {
            int k = SBox6 == null ? 4 : 5;

            if (key.Length < 256 * k / 8)
            {
                throw new ArgumentException("key must be 256*" + k + " bits size (or greater, but will use 256*k bits)");
            }

            workingKey = new int[k][];
            if (errorCipher && SBox6 == null)
            {
                for (int i = 0; i < k; i++)
                {
                    workingKey[i] = generateWorkingKey(key, i << 3);
                }
            }
            else
            {
                for (int i = 0; i < k; i++)
                {
                    workingKey[i] = generateWorkingKey(key, i << 5);
                }

                workingKeyA = new byte[32 * 5];
                BytesBuilder.CopyTo(key, workingKeyA);
            }

            BytesBuilder.CopyTo(syncro, N1, 0, 4);
            BytesBuilder.CopyTo(syncro, N2, 0, 4, 4);

            snc = syncro;

            currentSBox  = SBox;
            currentSBox2 = SBox2;
            currentSBox3 = SBox3;
            currentSBox4 = SBox4;
            currentSBox5 = SBox5;
            currentSBox6 = SBox6;

            if (currentSBox3 == null)
            {
                currentSBox3 = Sbox_Default;
            }
            if (currentSBox4 == null)
            {
                currentSBox4 = ESbox_D;
            }
            if (currentSBox5 == null)
            {
                currentSBox5 = ESbox_B;
            }
            if (currentSBox6 == null)
            {
                currentSBox6 = ESbox_C;
            }
        }
Beispiel #14
0
        /// <summary>
        /// Метод получения данных от клиента.
        /// </summary>
        /// <exception cref="SocketException"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="SecurityException"></exception>
        private void Listener()
        {
            while (true)
            {
                try
                {
                    // Получение клиентского сокета
                    Socket Client = _server.Accept();

                    #region Получение входящих данных (Способ №1)

                    //// Получение входящих данных
                    //BytesBuilder Bytes = new BytesBuilder();
                    //while (Client.Available > 0)
                    //{
                    //    Byte[] Buffer = new Byte[50000];
                    //    Int32 Length = Client.Receive(Buffer);

                    //    Bytes.Append(Buffer, Length, false);
                    //}

                    #endregion

                    #region Получение входящих данных (Способ №2)

                    // Получение входящих данных
                    BytesBuilder Bytes  = new BytesBuilder();
                    Byte[]       Buffer = new Byte[1024];
                    Int32        Length = 0;
                    while ((Length = Client.Receive(Buffer)) > 0)
                    {
                        Bytes.Append(Buffer, Length, false);
                    }

                    #endregion

                    // Обработка события при получении данных
                    Receiver?.Invoke(this, new TcpReceiverEventArgs(Client, Bytes.ToArray(), Bytes.ToArray().Length));
                    Bytes.Dispose();

                    if (_data != null)
                    {
                        // Отправка данных клиенту
                        Client.Send(_data);
                    }

                    // Закрытие клиентского сокета
                    Client.Shutdown(SocketShutdown.Both);
                    Client.Close();
                }
                catch (Exception Exception)
                {
                    // Обработка события при возникновении ошибок в работе сервера
                    Error?.Invoke(this, new TcpErrorEventArgs(Exception));
                }
            }
        }
        private static void DoPermutation(byte *msg, ushort[] table, byte *buff)
        {
            for (int i = 0; i < 2048; i++)
            {
                buff[i] = msg[table[i]];
            }

            BytesBuilder.CopyTo(2048, 2048, buff, msg);
        }
Beispiel #16
0
        public override byte[] prepareKey(long variant)
        {
            var k = base.prepareKey(variant);

            var key = new byte[256 * 5];

            BytesBuilder.ToNull(key);
            BytesBuilder.CopyTo(k, key);

            return(key);
        }
Beispiel #17
0
        private static byte[] GostGammaMod(int len, byte[] inData)
        {
            byte[] result;
            var    dt = new byte[64 * 5];

            BytesBuilder.CopyTo(inData, dt);
            var g = new Gost28147Modified();

            g.prepareGamma(dt, new byte[160], Gost28147Modified.CryptoProA, Gost28147Modified.CryptoProC, Gost28147Modified.Sbox_Default, Gost28147Modified.ESbox_A, Gost28147Modified.ESbox_B, Gost28147Modified.ESbox_C);
            result = g.getGamma(len, 40);
            return(result);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            P_CMD_Request           req  = new P_CMD_Request();
            OnlineUsersQueryRequest info = new OnlineUsersQueryRequest();
            var          data            = ESHelper.Pack(ref req, 1);
            BytesBuilder bb = new BytesBuilder();

            bb.Append(data
                      ).Append(ESHelper.Pack(ref info));

            this.SendMessage(bb.ToBytes());
        }
Beispiel #19
0
        public override byte[] prepareOIV(long variant)
        {
            lock (sync)
            {
                if (nullBytes == null)
                {
                    nullBytes = new byte[1];
                    BytesBuilder.ToNull(nullBytes);
                }
            }

            return(nullBytes);
        }
Beispiel #20
0
        public virtual byte[] prepareOIV(long variant)
        {
            lock (sync)
            {
                if (nullBytes == null)
                {
                    nullBytes = new byte[64];
                    BytesBuilder.ToNull(nullBytes);
                }
            }

            return(nullBytes);
        }
        public unsafe void StartTests()
        {
            GenerateTables();

            var failTestCount  = 0;
            var fail5TestCount = 0;

            Parallel.ForEach
            (
                sources,
                delegate(SourceTask task)
            {
                var S         = BytesBuilder.CloneBytes(task.Value);
                fixed(byte *s = S)
                {
                    Permutation(s, S.LongLength);

                    for (int i = 0; i < S.LongLength - 2; i++)
                    {
                        if (/*s[i] == 0 && */ s[i] == s[i + 1] && s[i] == s[i + 2] /* && s[i] == s[i + 3] && s[i] == s[i + 4]*/)
                        {
                            Interlocked.Increment(ref failTestCount);

                            if (i + 4 < S.LongLength)
                            {
                                if (/*s[i] == 0 && */ s[i] == s[i + 1] && s[i] == s[i + 2] && s[i] == s[i + 3] && s[i] == s[i + 4])
                                {
                                    Interlocked.Increment(ref fail5TestCount);
                                    i += 2;
                                }
                            }

                            i += 2;
                        }
                    }
                }
            }
            );

            // Совпадений по три должно быть примерно
            // Т.к. для любого встреченного n, вероятность того, что следующие два за ним тоже будут n равна 256*256
            // Всего встречено будет (2048-2) байтов на 32768 тестов, то есть (2048-2)*32768//65536=1024
            // Учитывая SkippedBlock всё ещё нужно домножить на 11
            if (failTestCount > 0)
            {
                this.task.error.Add(new Error()
                {
                    Message = TableName + " test 3: " + failTestCount + " [right 11253], test 5: " + fail5TestCount + "  [right 0]"
                });
            }
        }
Beispiel #22
0
        public override byte[] prepareKey(long variant)
        {
            var k = new byte[2];

            k[0] = (byte)variant;
            k[1] = (byte)(variant >> 8);

            var key = new byte[64];

            BytesBuilder.ToNull(key);
            BytesBuilder.CopyTo(k, key);

            return(key);
        }
Beispiel #23
0
        public static int permutationMergeBytes(byte[] key, byte[] target, bool repeatKey = false)
        {
            int result;
            var tmp = new byte[target.Length];
            int kl  = 0;

            fixed(byte *k = key, t = target, _tmp = tmp)
            {
                result = permutationMergeBytes(k, key.Length, t, _tmp, target.Length, ref kl, repeatKey);
                BytesBuilder.ToNull(tmp.Length, _tmp);
            }

            return(result);
        }
Beispiel #24
0
Datei: Node.cs Projekt: fdsc/old
        protected static void newSessionGuid()
        {
            lock (syncObject)
            {
                var    bb     = new BytesBuilder();
                byte[] target = null;

                BytesBuilder.ULongToBytes((ulong)DateTime.Now.Ticks, ref target);
                bb.add(target);
                bb.add(staticBytes);

                sessionGuid = SHA3.generateRandomPwd(bb.getBytes(), 20);
            }
        }
Beispiel #25
0
            public void clear(bool notTagsClear = false)
            {
                BytesBuilder.ClearString(mainTag);
                BytesBuilder.ClearString(pwd);
                BytesBuilder.ClearString(crypt);

                if (!notTagsClear)
                {
                    foreach (var tag in tags)
                    {
                        BytesBuilder.ClearString(tag);
                    }
                    tags.Clear();
                }
            }
Beispiel #26
0
        private static void UdpClientSendAndClose(IPEndPoint source, IPEndPoint target, string UTF8String)
        {
            using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                // client.Ttl = 128;
                client.DontFragment        = true;
                client.ExclusiveAddressUse = true;
                client.Bind(source);

                var bb = new BytesBuilder();
                bb.add(UTF8String);

                client.SendTo(bb.getBytes(), target);
            }
        }
Beispiel #27
0
        private static bool testForBits_getMultiHash40(ref int pc, int hc, SHA3 sha)
        {
            var size  = 32;
            var sizeb = size << 3;

            byte[] result = null;
            byte[] inData = new byte[size];

            int[,] counts = new int[sizeb, sizeb];

            BytesBuilder.ToNull(inData);
            for (int i = 0; i < sizeb; i++)
            {
                setBitInArray(inData, i);

                for (int j = 0; j < sizeb; j++)
                {
                    if (i == j)
                    {
                        continue;
                    }

                    setBitInArray(inData, j);

                    SHA3.getMultiHash40(inData, out result, ref pc, hc, sha, size);
                    //SHA3.getMultiHash20(inData, out result, ref pc, hc, sha, size);
                    //result = sha.getHash512(inData);
                    //result = new testCiphers.RC4(inData).getGamma(size);
                    toResult(sizeb, i, j, result, counts);

                    setBitInArray(inData, j, false);
                }

                setBitInArray(inData, i, false);
            }

            double суммарнаяВероятность, минимальнаяВероятность, множительВероятностей, отклонениеОтЭталона, отклонениеОтЭталонаВниз, отклонениеОтЭталонаВверх;

            double[,] вероятность;
            getCountsResult(sizeb, counts, out вероятность, out минимальнаяВероятность, out множительВероятностей, out суммарнаяВероятность, out отклонениеОтЭталона, out отклонениеОтЭталонаВниз, out отклонениеОтЭталонаВверх);

            if (множительВероятностей > 1.01 || суммарнаяВероятность < 0.01 || отклонениеОтЭталонаВниз > 0.10 || отклонениеОтЭталонаВверх > 0.10 || минимальнаяВероятность < 0.001)
            {
                return(false);
            }

            return(true);
        }
Beispiel #28
0
        public static byte[] getHash(byte[] data, bool is512bit = true)
        {
            byte[] m;
            byte[] N0    = new byte[64];
            byte[] N512  = new byte[64];
            byte[] N     = new byte[64];
            byte[] h     = new byte[64];
            byte[] Sigma = new byte[64];

            if (!is512bit)
            {
                for (int i = 0; i < h.Length; i++)
                {
                    h[i] = 1;
                }
            }

            LongToBytes(N512, 64 - 8, 512);

            var D = data;
            var L = data.LongLength;

            while (L >= 64)
            {
                m = new byte[64];
                BytesBuilder.CopyTo(data, m, 0, -1, L - 64);

                h = g(h, m, N);
                add(N, N512);
                add(Sigma, m);

                L -= 64;
            }

            m = new byte[64];
            var NM = new byte[64];

            BytesBuilder.CopyTo(data, m, 64 - L, L, 0);
            LongToBytes(NM, 64 - 8, (ulong)L * 8);

            m[64 - L - 1] = 1;
            h             = g(h, m, N);
            add(N, NM);
            add(Sigma, m);
            h = g(h, N, N0);

            return(g(h, Sigma, N0));
        }
Beispiel #29
0
        private static void GetPasswordAndDecryptFile(FileInfo fi, out byte[] bt, DoublePasswordForm pwdForm1)
        {
            byte[] key;
            int    regime;

            using (var file = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                file.Position = 1;
                regime        = file.ReadByte();
            }

            GetKeyByPassword(pwdForm1, out key, regime);

/*
 #warning INSECURE
 * File.AppendAllText("unsecure.log", "key: " + BitConverter.ToString(key).Replace("-", "") + "\r\n");
 */
            pwdForm1.clearResultText();

            var sha = new SHA3(fi.Length);

            if (regime < 10)
            {
                sha.useOldDuplex = true;
            }

            var cbt = File.ReadAllBytes(fi.FullName);

            try
            {
                bt = sha.multiDecryptLZMA(cbt, key);
            }
            catch (Exception e)
            {
                MessageBox.Show("Расшифрование не удалось, возможно файл не является файлом программы rtbd. " + e.Message, "Расшифрование не удалось", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                bt = null;
                return;
            }
            finally
            {
                sha.Clear(true);
                BytesBuilder.ToNull(key);
                BytesBuilder.ToNull(cbt);
                cbt = null;
                key = null;
            }
        }
Beispiel #30
0
        public string decrypt(string base64str, PasswordSecure pwd = null)
        {
            if (pwd == null)
            {
                pwd = key;
            }

            var sha     = new SHA3(base64str.Length);
            var openKey = pwd.getObjectValue();
            var crypted = sha.multiDecryptLZMA(Convert.FromBase64String(base64str), openKey);

            BytesBuilder.BytesToNull(openKey);

            var result = new UTF32Encoding().GetString(crypted); //Convert.ToBase64String(crypted);

            BytesBuilder.ToNull(crypted);
            return(result);
        }