Beispiel #1
0
        public void Cryptography()
        {
            SHA1      sha1      = SHA1.Create();
            SHA256    sha256    = SHA256.Create();
            RIPEMD160 ripemd160 = RIPEMD160.Create();

            byte[] data = { 0x0A, 0x0B, 0x0C, 0x0D, 0x0E };

            Script sha1Script = new Script(data.Length, data, Op.SHA1);

            sha1Script.Execute();
            Assert.AreEqual(sha1.ComputeHash(data), sha1Script.Main.Pop());

            Script sha256Script = new Script(data.Length, data, Op.SHA256);

            sha256Script.Execute();
            Assert.AreEqual(sha256.ComputeHash(data), sha256Script.Main.Pop());

            Script ripemd160Script = new Script(data.Length, data, Op.RIPEMD160);

            ripemd160Script.Execute();
            Assert.AreEqual(ripemd160.ComputeHash(data), ripemd160Script.Main.Pop());

            Script hash160Script = new Script(data.Length, data, Op.Hash160);

            hash160Script.Execute();
            Assert.AreEqual(ripemd160.ComputeHash(sha256.ComputeHash(data)), hash160Script.Main.Pop());

            Script hash256Script = new Script(data.Length, data, Op.Hash256);

            hash256Script.Execute();
            Assert.AreEqual(sha256.ComputeHash(sha256.ComputeHash(data)), hash256Script.Main.Pop());
        }
Beispiel #2
0
        private void CreateUser(string name, string password)
        {
            var cs = ConfigurationManager.AppSettings["UDB"];

            using (var UDB = new UserDataContext(cs))
                using (var PDB = new PasswordDataContext(cs))
                    using (var UserRolesDB = new UserRolesDataContext(cs))
                        using (var RolesDB = new RolesDataContext(cs))
                        {
                            var users     = UDB.UserInfos.ToList();
                            var passwords = PDB.Passwords.ToList();
                            int?newID;

                            if (users.Any())
                            {
                                var UserWithTheSameName = (from u in users
                                                           where u.Username == name
                                                           select u);
                                if (UserWithTheSameName.Any())
                                {
                                    Response.Write("User with this username already exists!</br>");
                                    return;
                                }

                                var lastRecord = (from u in users
                                                  orderby u.ID descending
                                                  select u).First();
                                newID = lastRecord.ID + 1;
                                UDB.ExecuteCommand("INSERT INTO UserCatalog.dbo.UserInfo (ID, Username)" +
                                                   "VALUES ({0}, {1})", newID, name);
                            }

                            else // If there are no users, new ID must be equal to 1
                            {
                                newID = 1;
                                UDB.ExecuteCommand("INSERT INTO UserCatalog.dbo.UserInfo (ID, Username)" +
                                                   "VALUES ({0}, {1})", newID, name);
                            }

                            int       Iterations = 10;
                            RIPEMD160 ripemd160  = RIPEMD160.Create();
                            string    Salt       = RandomString(15);

                            byte[] PasswordBytes     = System.Text.Encoding.ASCII.GetBytes(password + Salt);
                            byte[] EncryptedBites    = ripemd160.ComputeHash(PasswordBytes);
                            string EncryptedPassword = System.Text.Encoding.ASCII.GetString(EncryptedBites);
                            for (int i = 2; i <= Iterations; i++)
                            {
                                EncryptedBites    = ripemd160.ComputeHash(System.Text.Encoding.ASCII.GetBytes(EncryptedPassword));
                                EncryptedPassword = System.Text.Encoding.ASCII.GetString(EncryptedBites);
                            }

                            PDB.ExecuteCommand("INSERT INTO UserCatalog.dbo.Password (ID, Salt, Value, Iterations, Date)" +
                                               "VALUES ({0}, {1}, {2}, {3}, {4})", newID, Salt, EncryptedPassword, Iterations,
                                               DateTime.Now);
                            Roles.AddUserToRole(name, "User");
                        }
        }
Beispiel #3
0
        public static string RIPEMD160(string input)
        {
            byte[] data = ripemd160.ComputeHash(Encoding.UTF8.GetBytes(input));
            sb.Length = 0;

            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data [i].ToString(X2));
            }

            return(sb.ToString());
        }
Beispiel #4
0
        /// <summary>	Calculates the bitshares address from a bitcoin public key. </summary>
        ///
        /// <remarks>	Paul, 08/12/2014. </remarks>
        ///
        /// <param name="compressedBtcPubKey">	The compressed btc pub key. </param>
        /// <param name="ripe">				    The ripe. </param>
        ///
        /// <returns>	The calculated bitshares address from btc pub key bytes. </returns>
        static public byte[] ComputeBitsharesAddressFromBtcPubKey(byte[] compressedBtcPubKey, RIPEMD160 ripe)
        {
            byte[] sha512 = Crypto.ComputeSha512(compressedBtcPubKey);
            byte[] addr   = ripe.ComputeHash(sha512);
            byte[] check  = ripe.ComputeHash(addr);

            byte[] addrFinal = new byte[20 + 4];
            addr.CopyTo(addrFinal, 0);

            Buffer.BlockCopy(check, 0, addrFinal, 20, 4);
            return(addrFinal);
        }
Beispiel #5
0
        public void test_1()
        {
            var data         = new byte[0]; // ""
            var expectedHash = ByteExtensions.HexToByteArray("9c1185a5c5e9fc54612808977ee8f548b2258d31");

            var actualHash = _hashAlgorithm.ComputeHash(data);

            Assert.Equal(expectedHash, actualHash);
        }
Beispiel #6
0
        public static string GenerateWalletAddress(string openkey, bool typeNetwork) //Метод для генерации адреса (openkey -открытый ключ в виде hex строки,typeNetwork true для основной сети и false для тестовой)
        {
            SHA256    sha       = SHA256Managed.Create();
            RIPEMD160 riPEMD160 = RIPEMD160Managed.Create();// Создаем экземпляры классов реализаций хеш алгоритмов

            byte[] byteOpenKey = StringToByteArray(openkey);
            // 1 шаг - применить к открытому ключу SHA-256
            byte[] firstStepRes = sha.ComputeHash(byteOpenKey);
            // 2 шаг - применить к результату шага 1 RIPEMD160
            byte[] secondStepRes = riPEMD160.ComputeHash(firstStepRes);
            // 3 шаг - добавить к результату шага 2 версионный бит(00 для основной сети и 6f для тестовой)
            byte[] thirdStepRes = new byte[secondStepRes.Length + 1];
            thirdStepRes[0] = typeNetwork ? (byte)0 : (byte)0x6F;
            secondStepRes.CopyTo(thirdStepRes, 1);
            // 4 шаг - два раза применить SHA-256 к результату шага 3
            byte[] fourthStepRes = sha.ComputeHash(sha.ComputeHash(thirdStepRes));
            // 5 шаг - взять первые четыре байта из шага 4(проверочная сумма адреса) и добавить их в конец результата шага 3
            byte[] fifthStepRes = new byte[thirdStepRes.Length + 4];
            thirdStepRes.CopyTo(fifthStepRes, 0);
            for (int i = 0; i < 4; i++)
            {
                fifthStepRes[fifthStepRes.Length - 4 + i] = fourthStepRes[i];
            }
            return(ByteToBase58(fifthStepRes));//возвращаем ключ в base58 кодировке
        }
        private string processFile(string file, ref string fileHash)
        {
            string     fullPath   = null;
            FileStream fileStream = File.Open(file, FileMode.Open);

            fileStream.Position = 0;
            //Calculate hash.
            RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
            var       _hash       = fileHash = Hash.GetMd5Hash(myRIPEMD160.ComputeHash(fileStream));

            fileStream.Dispose();
            //Check If exist already exist file in Database with the same hash
            var existFile = Session.Advanced.DocumentQuery <Document>().Any(p => p.FileHash == _hash && p.Canceled == null);

            if (!existFile)
            {
                fullPath = SaveFile(file);
            }
            else
            {
                var existingFileName = Session.Query <Document>().Where(d => d.FileHash == _hash && d.Canceled == null).FirstOrDefault().OriginalName;
                logMessage(string.Format("The file {0} already exist in the repository with name {1}", Path.GetFileName(file), existingFileName));
            }

            return(fullPath);
        }
Beispiel #8
0
        public static byte[] HashAndDispose(this RIPEMD160 ripemd160, byte[] buffer)
        {
            var hash = ripemd160.ComputeHash(buffer);

            (ripemd160 as IDisposable).Dispose();
            return(hash);
        }
Beispiel #9
0
        static byte[] GetRMD160Hash(byte[] myByte)
        {
            RIPEMD160 _r160 = RIPEMD160Managed.Create();

            byte[] _encrypted = _r160.ComputeHash(myByte);
            ; return(_encrypted);
        }
Beispiel #10
0
        /// <summary>
        /// Computes the Hash160 of the public key upon demand.
        /// </summary>
        protected override byte[] ComputeHash160()
        {
            byte[]    shaofpubkey = Util.ComputeSha256(PublicKeyBytes);
            RIPEMD160 rip         = System.Security.Cryptography.RIPEMD160.Create();

            return(rip.ComputeHash(shaofpubkey));
        }
Beispiel #11
0
        private byte[] ComputeHash160()
        {
            byte[]    shaofpubkey = ComputeSha256(pubaddr);
            RIPEMD160 rip         = System.Security.Cryptography.RIPEMD160.Create();

            return(rip.ComputeHash(shaofpubkey));
        }
Beispiel #12
0
        /// <summary>
        /// Get the Public Addres from the key.
        /// </summary>
        /// <param name="publicKey">
        /// The public key.
        /// </param>
        /// <param name="version">
        /// The version of the Blockchain.
        /// </param>
        /// <returns>
        /// The Public Address as a <see cref="string"/>.
        /// </returns>
        public static string GetAddress(byte[] publicKey, byte version)
        {
            var keyHash = Ripemd160.ComputeHash(publicKey, 0, publicKey.Length);
            var address = new BCAVersionedChecksummedBytes(version, keyHash);

            return(address.ToString());
        }
Beispiel #13
0
 private byte[] CalcRipMid160(string filename)
 {
     using (FileStream stream = File.OpenRead(filename))
     {
         return(RipMid160.ComputeHash(stream));
     }
 }
Beispiel #14
0
 // :$$$.контрольнаясумма
 public static byte[] MD160(byte[] toHash)
 {
     using (RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create())
     {
         return(myRIPEMD160.ComputeHash(toHash));
     }
 }
Beispiel #15
0
        private string GetAddressFromPublicKey(string publicKey)
        {
            SHA256    sha256    = SHA256.Create();
            RIPEMD160 ripemd160 = RIPEMD160.Create();

            // Stage one hash algorithm - 0 byte + RIPEMD160(SHA256(publicKey))
            List <byte> stageOneHashList = new List <byte>();

            stageOneHashList.Add(0);                                                                                    // The first stage hash is prepended with a zero byte
            stageOneHashList.AddRange(ripemd160.ComputeHash(sha256.ComputeHash(Util.HexStringToByteArray(publicKey)))); // Body of first stage hash
            byte[] stageOneHash = stageOneHashList.ToArray();

            // Stage 2 hash algorithm - SHA256(SHA256(stageOneHash))
            byte[] stageTwoHash = sha256.ComputeHash(sha256.ComputeHash(stageOneHash));

            // Address bytes algorithm - stageOneHash + last 4 bytes of stageTwoHash
            List <byte> addressBytes = new List <byte>();

            addressBytes.AddRange(stageOneHash);
            addressBytes.AddRange(stageTwoHash.Take(4));

            // Convert address to Base58
            string base58Address = Base58Check.Base58CheckEncoding.EncodePlain(addressBytes.ToArray());

            return(base58Address);
        }
        static void Main(string[] args)
        {
            if (args == null || args.Count() != 1)
            {
                Console.WriteLine("USAGE: CreateFileHash 'Filename.mp3'");
            }
            else
            {
                if (File.Exists(args[0].ToString()))
                {
                    RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
                    byte[]    hashVal;
                    using (FileStream stream = File.Open(args[0].ToString(), FileMode.Open))
                    {
                        stream.Position = 0;
                        hashVal         = myRIPEMD160.ComputeHash(stream);
                        string hashValueString = CreateStringFromByteArray(hashVal);
                        Console.WriteLine("The hash for this file is: {0}", hashValueString);
                        Console.WriteLine("The hash length is {0}", hashValueString.Length);
                    }
                }
                else
                {
                    Console.WriteLine("File not found!");
                }

                Console.WriteLine("Press enter to continue");
                Console.ReadLine();
            }
        }
 public static byte[] Ripemd160(byte[] data)
 {
     using (RIPEMD160 hash = RIPEMD160.Create())
     {
         return(hash.ComputeHash(data));
     }
 }
Beispiel #18
0
 private static byte[] ComputeRipeMdHash(byte[] data)
 {
     using (RIPEMD160 ripemd160 = RIPEMD160Managed.Create())
     {
         return(ripemd160.ComputeHash(data));
     }
 }
Beispiel #19
0
    public static void Main(String[] args)
    {
        string directory = "";

        if (args.Length < 1)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            DialogResult        dr  = fbd.ShowDialog();
            if (dr == DialogResult.OK)
            {
                directory = fbd.SelectedPath;
            }
            else
            {
                Console.WriteLine("No directory selected.");
                return;
            }
        }
        else
        {
            directory = args[0];
        }

        try
        {
            // Create a DirectoryInfo object representing the specified directory.
            DirectoryInfo dir = new DirectoryInfo(directory);
            // Get the FileInfo objects for every file in the directory.
            FileInfo[] files = dir.GetFiles();
            // Initialize a RIPE160 hash object.
            RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
            byte[]    hashValue;
            // Compute and print the hash values for each file in directory.
            foreach (FileInfo fInfo in files)
            {
                // Create a fileStream for the file.
                FileStream fileStream = fInfo.Open(FileMode.Open);
                // Be sure it's positioned to the beginning of the stream.
                fileStream.Position = 0;
                // Compute the hash of the fileStream.
                hashValue = myRIPEMD160.ComputeHash(fileStream);
                // Write the name of the file to the Console.
                Console.Write(fInfo.Name + ": ");
                // Write the hash value to the Console.
                PrintByteArray(hashValue);
                // Close the file.
                fileStream.Close();
            }
            return;
        }
        catch (DirectoryNotFoundException)
        {
            Console.WriteLine("Error: The directory specified could not be found.");
        }
        catch (IOException)
        {
            Console.WriteLine("Error: A file in the directory could not be accessed.");
        }
    }
Beispiel #20
0
        public static string FromString(string input, HashType hashtype)
        {
            Byte[] clearBytes;
            Byte[] hashedBytes;
            string output = String.Empty;

            switch (hashtype)
            {
            case HashType.RIPEMD160:
                clearBytes = new UTF8Encoding().GetBytes(input);
                RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
                hashedBytes = myRIPEMD160.ComputeHash(clearBytes);
                output      = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                break;

            case HashType.MD5:
                clearBytes  = new UTF8Encoding().GetBytes(input);
                hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
                output      = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                break;

            case HashType.SHA1:
                clearBytes = Encoding.UTF8.GetBytes(input);
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                sha1.ComputeHash(clearBytes);
                hashedBytes = sha1.Hash;
                sha1.Clear();
                output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                break;

            case HashType.SHA256:
                clearBytes = Encoding.UTF8.GetBytes(input);
                SHA256 sha256 = new SHA256Managed();
                sha256.ComputeHash(clearBytes);
                hashedBytes = sha256.Hash;
                sha256.Clear();
                output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                break;

            case HashType.SHA384:
                clearBytes = Encoding.UTF8.GetBytes(input);
                SHA384 sha384 = new SHA384Managed();
                sha384.ComputeHash(clearBytes);
                hashedBytes = sha384.Hash;
                sha384.Clear();
                output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                break;

            case HashType.SHA512:
                clearBytes = Encoding.UTF8.GetBytes(input);
                SHA512 sha512 = new SHA512Managed();
                sha512.ComputeHash(clearBytes);
                hashedBytes = sha512.Hash;
                sha512.Clear();
                output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                break;
            }
            return(output);
        }
Beispiel #21
0
        public static string Encrypt(this string text)
        {
            // Create a hash of current nickname to use as the Cryptographic Key
            RIPEMD160 hash = RIPEMD160.Create();

            byte[] hasher = hash.ComputeHash(Encoding.Unicode.GetBytes(Prefs.Username));
            return(Cryptor.Encrypt(text, BitConverter.ToString(hasher)));
        }
Beispiel #22
0
 public void RIPEMD160_b(string testName, RIPEMD160 hash, byte[] input, byte[] result)
 {
     byte[] output = hash.ComputeHash(input, 0, input.Length);
     AssertEquals(testName + ".b.1", result, output);
     AssertEquals(testName + ".b.2", result, hash.Hash);
     // required or next operation will still return old hash
     hash.Initialize();
 }
Beispiel #23
0
        public static string Decrypt(this string text)
        {
            RIPEMD160 hash = RIPEMD160.Create();

            byte[] hasher = hash.ComputeHash(Encoding.Unicode.GetBytes(Prefs.Username));
            text = Cryptor.Decrypt(text, BitConverter.ToString(hasher));
            return(text);
        }
Beispiel #24
0
        public static string Encrypt(this string text)
        {
            RIPEMD160 hash = RIPEMD160.Create();
            var       un   = (Prefs.Username ?? string.Empty).Clone() as string;

            byte[] hasher = hash.ComputeHash(Encoding.Unicode.GetBytes(un));
            return(Cryptor.Encrypt(text, BitConverter.ToString(hasher)));
        }
Beispiel #25
0
 public static List <byte> DoubleHash(byte[] publicKey)
 {
     using (SHA256 sha256 = SHA256.Create()) {
         using (RIPEMD160 ripemd160 = RIPEMD160.Create()) {
             return(new List <byte>(ripemd160.ComputeHash(sha256.ComputeHash(publicKey))));
         }
     }
 }
Beispiel #26
0
        public static byte[] PublicKeyHash(byte[] bytes)
        {
            var hash  = SHA256.Create();
            var riper = new RIPEMD160();

            bytes = hash.ComputeHash(bytes, 0, bytes.Length);
            return(riper.ComputeHash(bytes, 0, bytes.Length));
        }
Beispiel #27
0
 /// <summary>	Calculates the bitshares pubilc key from bitcoin public key. </summary>
 ///
 /// <remarks>	Paul, 08/12/2014. </remarks>
 ///
 /// <param name="compressedBtcPubKey">	The compressed btc pub key. </param>
 /// <param name="ripe">				    The ripe. </param>
 ///
 /// <returns>	The calculated bitshares pub key from btc pub key bytes. </returns>
 static public byte[] ComputeBitsharesPubKeyFromBtcPubKey(byte[] compressedBtcPubKey, RIPEMD160 ripe)
 {
     byte[] pubkeyCheck = ripe.ComputeHash(compressedBtcPubKey);
     byte[] pubkeyFinal = new byte[37];
     compressedBtcPubKey.CopyTo(pubkeyFinal, 0);
     Buffer.BlockCopy(pubkeyCheck, 0, pubkeyFinal, 37 - 4, 4);
     return(pubkeyFinal);
 }
Beispiel #28
0
        private void Check(string name, string password)
        {
            var cs = ConfigurationManager.AppSettings["UDB"];

            using (var UDB = new UserDataContext(cs))
                using (var PDB = new PasswordDataContext(cs))
                {
                    var users     = UDB.UserInfos.ToList();
                    var passwords = PDB.Passwords.ToList();
                    var id        = (from u in users
                                     where u.Username == name
                                     select u.ID);
                    if (id.Any())
                    {
                        RIPEMD160 ripemd160 = RIPEMD160.Create();

                        var salt = (from p in passwords
                                    where p.ID == id.First()
                                    select p.Salt);
                        var iterations = (from p in passwords
                                          where p.ID == id.First()
                                          select p.Iterations);
                        var userPassword = (from p in passwords
                                            where p.ID == id.First()
                                            select p.Value);
                        byte[] PasswordBytes     = System.Text.Encoding.ASCII.GetBytes(password + salt.First());
                        byte[] EncryptedBites    = ripemd160.ComputeHash(PasswordBytes);
                        string EncryptedPassword = System.Text.Encoding.ASCII.GetString(EncryptedBites);
                        for (int i = 2; i <= iterations.First(); i++)
                        {
                            EncryptedBites    = ripemd160.ComputeHash(System.Text.Encoding.ASCII.GetBytes(EncryptedPassword));
                            EncryptedPassword = System.Text.Encoding.ASCII.GetString(EncryptedBites);
                        }
                        Response.Write(EncryptedPassword);
                        Response.Write("<br/>");
                        Response.Write(userPassword.First());
                        Response.Write("<br/>");
                        if (EncryptedPassword == userPassword.First())
                        {
                            Response.Write("TRUE");
                        }
                    }
                    Response.Write("FALSE");
                }
        }
Beispiel #29
0
        public static byte[] Hash160(this byte[] hex)
        {
            SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider();

            byte[]    shaofpubkey = sha256.ComputeHash(hex);
            RIPEMD160 rip         = System.Security.Cryptography.RIPEMD160.Create();

            return(rip.ComputeHash(shaofpubkey));
        }
        /// <summary>
        ///     Gets the hash of a file
        /// </summary>
        /// <param name="filename">File path.</param>
        public static byte[] File(string filename)
        {
            RIPEMD160  localRipemd160Provider = RIPEMD160.Create();
            FileStream fileStream             = new FileStream(filename, FileMode.Open);

            byte[] result = localRipemd160Provider.ComputeHash(fileStream);
            fileStream.Close();
            return(result);
        }