示例#1
0
 public void Decrypt()
 {
     try
     {
         if (m_vType == 10101)
         {
             byte[] cipherText = m_vData;
             Client.CPublicKey = cipherText.Take(32).ToArray();
             Hasher b = Blake2B.Create(new Blake2BConfig
             {
                 OutputSizeInBytes = 24
             });
             b.Init();
             b.Update(Client.CPublicKey);
             b.Update(Key.Crypto.PublicKey);
             Client.CRNonce     = b.Finish();
             cipherText         = CustomNaCl.OpenPublicBox(cipherText.Skip(32).ToArray(), Client.CRNonce, Key.Crypto.PrivateKey, Client.CPublicKey);
             Client.CSharedKey  = Client.CPublicKey;
             Client.CSessionKey = cipherText.Take(24).ToArray();
             Client.CSNonce     = cipherText.Skip(24).Take(24).ToArray();
             Client.CState      = 1;
             SetData(cipherText.Skip(48).ToArray());
         }
         else if (m_vType != 10100)
         {
             Client.CSNonce.Increment();
             SetData(CustomNaCl.OpenSecretBox(new byte[16].Concat(m_vData).ToArray(), Client.CSNonce, Client.CSharedKey));
         }
     }
     catch (Exception ex)
     {
         Client.CState = 0;
     }
 }
示例#2
0
        public bool ValidateAddress(string address)
        {
            if (address.Length != 64 && !address.StartsWith("xrb_"))
            {
                return(false);
            }
            var pk32 = address.Substring(4, 52);
            var pk   = Base32withPadding.Decode(pk32, _base32Alphabet, 4);

            var checksum        = address.Substring(56);
            var checksumDecoded = Base32withPadding.Decode(checksum, _base32Alphabet, 0);

            checksumDecoded = checksumDecoded.Reverse().ToArray();

            var blake2bConfig = new Blake2BConfig
            {
                OutputSizeInBytes = 5
            };
            var hasher = Blake2B.Create(blake2bConfig);

            hasher.Update(pk);
            var pkChecksum = hasher.Finish();

            return(pkChecksum.SequenceEqual(checksumDecoded));
        }
        /// <summary>
        /// Hashes the specified payload.
        /// </summary>
        /// <param name="payload">The payload.</param>
        /// <param name="size">The size.</param>
        /// <returns>System.Byte[].</returns>
        public byte[] Hash(byte[] payload, int size)
        {
            var nKey = new byte[size];

            //using (var random = new RNGCryptoServiceProvider())
            //    random.GetBytes(nKey);

            RandomNumberGenerator.Create().GetBytes(nKey);

            // Using Paseto Cryptography library
            using (var hash = new Blake2B())
                return(hash.ComputeHash(nKey));

            /*
             * Using NSec library
             *
             * var algo = new Blake2bMac();
             * using (var key = Key.Import(algo, nKey, KeyBlobFormat.RawSymmetricKey))
             *  return algo.Mac(key, payload, size);
             */

            // Using Sodium Core library
            //var hash = new GenericHash.GenericHashAlgorithm(nKey, size);
            //return hash.ComputeHash(GetBytes(payload));
        }
示例#4
0
        public static string HashStateBlock(string accountAddress, string previousHash, string balance, string representativeAccount, string link)
        {
            var representativePublicKey = AddressToPublicKey(representativeAccount);
            var accountPublicKey        = AddressToPublicKey(accountAddress);
            var previousBytes           = HexStringToByteArray(previousHash);

            var balanceHex = BigInteger.Parse(balance).ToString("X");

            if (balanceHex.Length % 2 == 1)
            {
                balanceHex = "0" + balanceHex;
            }
            byte[] balanceBytes = HexStringToByteArray(balanceHex.PadLeft(32, '0'));
            var    linkBytes    = HexStringToByteArray(link);
            var    preamble     = HexStringToByteArray("0000000000000000000000000000000000000000000000000000000000000006");

            var blake = Blake2B.Create(new Blake2BConfig()
            {
                OutputSizeInBytes = 32
            });

            blake.Init();
            blake.Update(preamble);
            blake.Update(accountPublicKey);
            blake.Update(previousBytes);
            blake.Update(representativePublicKey);
            blake.Update(balanceBytes);
            blake.Update(linkBytes);

            var hashBytes = blake.Finish();

            return(ByteArrayToHex(hashBytes));
        }
示例#5
0
        private static Blake2B MakeBlake2BInstanceAndInitialize(int hashSize)
        {
            var hashInstance = new Blake2B(new Blake2BConfig(hashSize));

            hashInstance.Initialize();
            return(hashInstance);
        }
        public static void crypto_sign_keypair(byte[] pk, int pkoffset, byte[] sk, int skoffset, byte[] seed, int seedoffset)
        {
            GroupElementP3 A;
            int            i;

            Array.Copy(seed, seedoffset, sk, skoffset, 32);

            var blake2bConfig = new Blake2BConfig
            {
                OutputSizeInBytes = 64
            };
            var hasher = Blake2B.Create(blake2bConfig);

            hasher.Update(sk, skoffset, 32);
            byte[] h = hasher.Finish();
            //byte[] h = Sha512.Hash(sk, skoffset, 32);//ToDo: Remove alloc
            ScalarOperations.sc_clamp(h, 0);

            GroupOperations.ge_scalarmult_base(out A, h, 0);
            GroupOperations.ge_p3_tobytes(pk, pkoffset, ref A);

            for (i = 0; i < 32; ++i)
            {
                sk[skoffset + 32 + i] = pk[pkoffset + i];
            }
            CryptoBytes.Wipe(h);
        }
示例#7
0
        public void Decrypt()
        {
            try
            {
                if (Constants.IsRc4)
                {
                    Client.Decrypt(m_vData);
                    if (m_vType == 10101)
                    {
                        Client.State = ClientState.Login;
                    }

                    // No need since the decryption occurs on same buffer.
                    //SetData(m_vData);
                }
                else
                {
                    if (m_vType == 10101)
                    {
                        var cipherText = m_vData;
                        Client.CPublicKey = cipherText.Take(32).ToArray();

                        var blake = Blake2B.Create(new Blake2BConfig
                        {
                            OutputSizeInBytes = 24
                        });
                        blake.Init();
                        blake.Update(Client.CPublicKey);
                        blake.Update(Key.Crypto.PublicKey);

                        Client.CRNonce = blake.Finish();

                        cipherText = CustomNaCl.OpenPublicBox(cipherText.Skip(32).ToArray(), Client.CRNonce, Key.Crypto.PrivateKey, Client.CPublicKey);

                        Client.CSharedKey  = Client.CPublicKey;
                        Client.CSessionKey = cipherText.Take(24).ToArray();
                        Client.CSNonce     = cipherText.Skip(24).Take(24).ToArray();
                        Client.State       = ClientState.Login;

                        SetData(cipherText.Skip(48).ToArray());
                    }
                    else
                    {
                        if (m_vType != 10100)
                        {
                            if (Client.State == ClientState.LoginSuccess)
                            {
                                Client.CSNonce.Increment();
                                SetData(CustomNaCl.OpenSecretBox(new byte[16].Concat(m_vData).ToArray(), Client.CSNonce, Client.CSharedKey));
                            }
                        }
                    }
                }
            }
            catch
            {
                Client.State = ClientState.Exception;
                throw;
            }
        }
        public string EncodeAccount(UInt256 account)
        {
            var hasher = Blake2B.Create(new Blake2BConfig
            {
                OutputSizeInBytes = 5
            });

            var bytes = account.ToByteArray().Reverse().ToArray();

            hasher.Update(bytes);
            byte[] checkBytes = hasher.Finish();
            Array.Resize(ref checkBytes, 8);
            UInt64     check  = BitConverter.ToUInt64(checkBytes, 0);
            BigInteger number = Number(bytes);

            number <<= 40;
            number  |= new BigInteger(check);
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < 60; i++)
            {
                var r = number.ToByteArray()[0] & 0x1f;
                number >>= 5;
                sb.Append(AccountLookup[r]);
            }
            sb.Append("_brx");
            var addrReverse = sb.ToString();
            var arr         = addrReverse.ToCharArray();

            Array.Reverse(arr);
            return(new string(arr));
        }
示例#9
0
 public void Encrypt(byte[] plainText)
 {
     try
     {
         if (GetMessageType() == 20104 || GetMessageType() == 20103)
         {
             Hasher b = Blake2B.Create(new Blake2BConfig
             {
                 OutputSizeInBytes = 24
             });
             b.Init();
             b.Update(Client.CSNonce);
             b.Update(Client.CPublicKey);
             b.Update(Key.Crypto.PublicKey);
             SetData(CustomNaCl.CreatePublicBox(Client.CRNonce.Concat(Client.CSharedKey).Concat(plainText).ToArray(), b.Finish(), Key.Crypto.PrivateKey, Client.CPublicKey));
             if (GetMessageType() == 20104)
             {
                 Client.CState = 2;
             }
         }
         else
         {
             Client.CRNonce.Increment();
             SetData(CustomNaCl.CreateSecretBox(plainText, Client.CRNonce, Client.CSharedKey).Skip(16).ToArray());
         }
     }
     catch (Exception)
     {
         Client.CState = 0;
     }
 }
示例#10
0
        /*
         * bool Proof::Test()
         * {
         *  uint32_t input[SEED_LENGTH + 2];
         *  for (unsigned i = 0; i < SEED_LENGTH; ++i)
         *      input[i] = seed[i];
         *  input[SEED_LENGTH] = nonce;
         *  input[SEED_LENGTH + 1] = 0;
         *  uint32_t buf[MAX_N / 4];
         *  std::vector<uint32_t> blocks(k + 1, 0);
         *  for (unsigned i = 0; i < inputs.size(); ++i)
         *  {
         *      input[SEED_LENGTH + 1] = inputs[i];
         *      blake2b((uint8_t*)buf, &input, NULL, sizeof(buf), sizeof(input), 0);
         *      for (unsigned j = 0; j < (k + 1); ++j)
         *      {
         *          //select j-th block of n/(k+1) bits
         *          blocks[j] ^= buf[j] >> (32 - n / (k + 1));
         *      }
         *  }
         *  bool b = true;
         *  for (unsigned j = 0; j < (k + 1); ++j)
         *  {
         *      b &= (blocks[j] == 0);
         *  }
         *  if (b && inputs.size() != 0)
         *  {
         *      printf("Solution found:\n");
         *      for (unsigned i = 0; i < inputs.size(); ++i)
         *      {
         *          printf(" %x ", inputs[i]);
         *      }
         *      printf("\n");
         *  }
         *  return b;
         * }
         */
        public bool Test()
        {
            uint[] input = new uint[Equihash.SEED_LENGTH + 2];
            for (uint i = 0; i < Equihash.SEED_LENGTH; ++i)
            {
                input[i] = seed[i];
            }
            input[Equihash.SEED_LENGTH]     = nonce;
            input[Equihash.SEED_LENGTH + 1] = 0;
            uint[]      buf    = new uint[Equihash.MAX_N / 4];
            List <uint> blocks = new List <uint>(); for (int i = 0; i < k + 1; i++)

            {
                blocks.Add(0);
            }

            for (int i = 0; i < inputs.Count; ++i)
            {
                input[Equihash.SEED_LENGTH + 1] = inputs[i];
                byte[] inputBytes;
                using (MemoryStream ms = new MemoryStream())
                {
                    for (int x = 0; x < input.Length; x++)
                    {
                        ms.Write(BitConverter.GetBytes(input[x]), 0, 4);
                    }

                    inputBytes = ms.ToArray();
                }

                Blake2B blake2b = new Blake2B(256);
                byte[]  result  = blake2b.ComputeHash(inputBytes);
                for (int x = 0; x < buf.Length; x++)
                {
                    buf[x] = BitConverter.ToUInt32(result, x * 4);
                }
                for (int j = 0; j < (k + 1); ++j)
                {
                    //select j-th block of n/(k+1) bits
                    blocks[j] = blocks[j] ^ (buf[j] >> (int)(32 - n / (k + 1)));
                }
            }
            bool b = true;

            for (int j = 0; j < (k + 1); ++j)
            {
                b = (blocks[j] == 0);
            }
            if (b && inputs.Count != 0)
            {
                Console.WriteLine("Solution found:");
                for (int i = 0; i < inputs.Count; ++i)
                {
                    Console.Write($" {inputs[i]} ");
                }
                Console.WriteLine("");
            }
            return(b);
        }
        /// <summary>Blake2 hashed with bytes concated at the end.</summary>
        /// <param name="bytes">The bytes.</param>
        /// <param name="size">The size.</param>
        /// <returns>
        ///   <br />
        /// </returns>
        public static byte[] Blake2Concat(byte[] bytes, int size = 128)
        {
            var config = new Blake2BConfig {
                OutputSizeInBits = size, Key = null
            };

            return(Blake2B.ComputeHash(bytes, config).Concat(bytes).ToArray());
        }
        /// <summary>Blake2 hashed the specified bytes.</summary>
        /// <param name="bytes">The bytes.</param>
        /// <param name="size">The size.</param>
        /// <param name="key">The key.</param>
        /// <returns>
        ///   <br />
        /// </returns>
        public static byte[] Blake2(byte[] bytes, int size = 128, IReadOnlyList <byte> key = null)
        {
            var config = new Blake2BConfig {
                OutputSizeInBits = size, Key = null
            };

            return(Blake2B.ComputeHash(bytes, config));
        }
示例#13
0
        public byte[] Blake2b(byte[] input)
        {
            var blakeConfig = new Blake2BConfig {
                OutputSizeInBits = 256
            };

            return(Blake2B.ComputeHash(input, 0, input.Count(), blakeConfig));
        }
示例#14
0
        public static byte[] FastHash(byte[] message, int offset, int length)
        {
            var blakeConfig = new Blake2BConfig {
                OutputSizeInBits = 256
            };

            return(Blake2B.ComputeHash(message, offset, length, blakeConfig));
        }
示例#15
0
        public string CalculateMessageNetworkId()
        {
            var networkIdBytes = Blake2B.ComputeHash(Encoding.ASCII.GetBytes(this.NetworkId), new Blake2BConfig {
                OutputSizeInBytes = 32
            }, null);

            return(BitConverter.ToInt64(networkIdBytes.Take(8).ToArray(), 0).ToString());
        }
示例#16
0
        public static byte[] SecureHash(byte[] message, int offset, int lenght)
        {
            var blakeConfig = new Blake2BConfig {
                OutputSizeInBits = 256
            };
            var blake2B = Blake2B.ComputeHash(message, offset, lenght, blakeConfig);

            return(Hash(blake2B, 0, blake2B.Length, Keccak256));
        }
示例#17
0
        private static byte[] CalculateBlake2StrongSum(byte[] block)
        {
            //IL_0001: Unknown result type (might be due to invalid IL or missing references)
            //IL_0006: Unknown result type (might be due to invalid IL or missing references)
            //IL_0013: Expected O, but got Unknown
            Blake2BConfig val = new Blake2BConfig();

            val.set_OutputSizeInBytes(32);
            return(Blake2B.ComputeHash(block, val));
        }
        // Generate blake2b nonce with clientkey(pk) and serverkey.
        private static byte[] GenerateBlake2BNonce(byte[] clientKey, byte[] serverKey)
        {
            var hashBuffer = new byte[clientKey.Length + serverKey.Length];

            Buffer.BlockCopy(clientKey, 0, hashBuffer, 0, clientKey.Length);
            Buffer.BlockCopy(serverKey, 0, hashBuffer, PublicKeyBox.PublicKeyLength, serverKey.Length);

            using (var blake = new Blake2B(24))
                return(blake.ComputeHash(hashBuffer));
        }
示例#19
0
 protected BLAKE2B(int bits)
     : base(GetHashType(bits), GetName(bits), bits / 8)
 {
     _factory = () =>
     {
         var algo = new Blake2B(bits);
         algo.Initialize();
         return(algo);
     };
 }
示例#20
0
        static readonly byte[] personalization = new byte[] { 99, 107, 98, 45, 100, 101, 102, 97, 117, 108, 116, 45, 104, 97, 115, 104 }; // ckb-default-hash

        public static byte[] ComputeHash(byte[] data)
        {
            Blake2BConfig config = new Blake2BConfig
            {
                Personalization   = personalization,
                OutputSizeInBytes = 32
            };
            SecureArrayCall secureArrayCall = default;

            return(Blake2B.ComputeHash(data, config, secureArrayCall));
        }
示例#21
0
        /// <inheritdoc />
        public long DoPow(byte[] message, int targetScore)
        {
            var relevantMessagePart = message.Take(message.Length - 8).ToArray();

            var digest = Blake2B.ComputeHash(relevantMessagePart, new Blake2BConfig {
                OutputSizeInBytes = 32
            }, null);
            var targetZeros = (int)Math.Ceiling(Math.Log((relevantMessagePart.Length + 8) * targetScore) / this.LN3);

            return(this.DoWork(digest, targetZeros));
        }
        public void Hash(Blake2BConfig config, byte[] message)
        {
            var hasher = Blake2B.Create(new Blake2BConfig()
            {
                OutputSizeInBytes = 64
            });

            hasher.Init();
            hasher.Update(Previous.ToByteArray());
            hasher.Update(Source.ToByteArray());
        }
示例#23
0
        /// <summary>
        /// get the Blake2b-512 encrypt
        /// </summary>
        /// <param name="byteArrayToEncrypt">Byte array to encrypt</param>
        /// <returns></returns>
        public static string Blake2b_512Hash(this byte[] byteArrayToEncrypt)
        {
            StringBuilder sBuilder = new StringBuilder();

            foreach (var encryptedByte in Blake2B.ComputeHash(byteArrayToEncrypt))
            {
                sBuilder.Append(encryptedByte.ToString("x2"));
            }

            return(sBuilder.ToString());
        }
示例#24
0
        public static byte[] Hash(byte[] data, int size)
        {
            var hasher = Blake2B.Create(new Blake2BConfig
            {
                OutputSizeInBytes = size,
            });

            hasher.Init();
            hasher.Update(data);
            return(hasher.Finish());
        }
 public void CheckTestVectors()
 {
     for (int len = 0; len < TestVectors.UnkeyedBlake2B.Length; len++)
     {
         var    input    = Enumerable.Range(0, len).Select(i => (byte)i).ToArray();
         var    hash     = Blake2B.ComputeHash(input);
         string actual   = BitConverter.ToString(hash).Replace("-", "");
         string expected = TestVectors.UnkeyedBlake2B[len];
         Assert.AreEqual(expected, actual);
     }
 }
示例#26
0
        public void Hash(Blake2BConfig config, byte[] message)
        {
            var hasher = Blake2B.Create(new Blake2BConfig()
            {
                OutputSizeInBytes = 64
            });

            hasher.Init();
            hasher.Update(Source.ToByteArray());
            hasher.Update(Representative.ToByteArray());
            hasher.Update(Account.ToByteArray());
        }
        public static Ed25519Address FromPublicKey(byte[] publicKey)
        {
            var addressHash = Blake2B.ComputeHash(publicKey, new Blake2BConfig {
                OutputSizeInBytes = 32
            }, null);

            return(new Ed25519Address
            {
                Address = addressHash.ToHex(),
                PublicKey = publicKey
            });
        }
示例#28
0
 private static void AddByteString(Blake2B hashInstance, byte[] octets)
 {
     if (octets.Length > 0)
     {
         AddIntToLittleEndian(hashInstance, octets.Length);
         hashInstance.TransformBytes(octets, 0, octets.Length);
     }
     else
     {
         AddIntToLittleEndian(hashInstance, 0);
     }
 }
示例#29
0
        public static string HashB64EncodedSalt(string password, string salt)
        {
            if (String.IsNullOrEmpty(password) || String.IsNullOrEmpty(salt))
            {
                throw new InvalidOperationException();
            }
            Blake2B blake2B = new Blake2B();

            blake2B.Salt = EncodingUtils.Base64Decode(salt);
            blake2B.Key  = StringUtils.GetBytes(password);
            byte[] data = blake2B.Final();
            return(EncodingUtils.Base64Encode(data));
        }
示例#30
0
        // Original crypto_sign_open, for reference only

        /*public static int crypto_sign_open(
         * byte[] m, out int mlen,
         * byte[] sm, int smlen,
         * byte[] pk)
         * {
         *  byte[] h = new byte[64];
         *  byte[] checkr = new byte[32];
         *  GroupElementP3 A;
         *  GroupElementP2 R;
         *  int i;
         *
         *  mlen = -1;
         *  if (smlen < 64) return -1;
         *  if ((sm[63] & 224) != 0) return -1;
         *  if (GroupOperations.ge_frombytes_negate_vartime(out A, pk, 0) != 0) return -1;
         *
         *  for (i = 0; i < smlen; ++i) m[i] = sm[i];
         *  for (i = 0; i < 32; ++i) m[32 + i] = pk[i];
         *  Sha512BclWrapper.crypto_hash_sha512(h, m, 0, smlen);
         *  ScalarOperations.sc_reduce(h);
         *
         *  var sm32 = new byte[32];
         *  Array.Copy(sm, 32, sm32, 0, 32);
         *  GroupOperations.ge_double_scalarmult_vartime(out R, h, ref A, sm32);
         *  GroupOperations.ge_tobytes(checkr, 0, ref R);
         *  if (Helpers.crypto_verify_32(checkr, sm) != 0)
         *  {
         *      for (i = 0; i < smlen; ++i)
         *          m[i] = 0;
         *      return -1;
         *  }
         *
         *  for (i = 0; i < smlen - 64; ++i)
         *      m[i] = sm[64 + i];
         *  for (i = smlen - 64; i < smlen; ++i)
         *      m[i] = 0;
         *  mlen = smlen - 64;
         *  return 0;
         * }*/

        public static bool crypto_sign_verify(
            byte[] sig, int sigoffset,
            byte[] m, int moffset, int mlen,
            byte[] pk, int pkoffset)
        {
            byte[]         h;
            byte[]         checkr = new byte[32];
            GroupElementP3 A;
            GroupElementP2 R;

            if ((sig[sigoffset + 63] & 224) != 0)
            {
                return(false);
            }
            if (GroupOperations.ge_frombytes_negate_vartime(out A, pk, pkoffset) != 0)
            {
                return(false);
            }

            var blake2bConfig = new Blake2BConfig
            {
                OutputSizeInBytes = 64
            };
            var hasher = Blake2B.Create(blake2bConfig);

            hasher.Update(sig, sigoffset, 32);
            hasher.Update(pk, pkoffset, 32);
            hasher.Update(m, moffset, mlen);
            h = hasher.Finish();

            /*
             * var hasher = new Sha512();
             * hasher.Update(sig, sigoffset, 32);
             * hasher.Update(pk, pkoffset, 32);
             * hasher.Update(m, moffset, mlen);
             * h = hasher.Finish();
             */

            ScalarOperations.sc_reduce(h);

            var sm32 = new byte[32];//todo: remove allocation

            Array.Copy(sig, sigoffset + 32, sm32, 0, 32);
            GroupOperations.ge_double_scalarmult_vartime(out R, h, ref A, sm32);
            GroupOperations.ge_tobytes(checkr, 0, ref R);
            var result = CryptoBytes.ConstantTimeEquals(checkr, 0, sig, sigoffset, 32);

            CryptoBytes.Wipe(h);
            CryptoBytes.Wipe(checkr);
            return(result);
        }