Пример #1
0
        private static HashAlgorithm DetermineHasher(HashType h)
        {
            HashAlgorithm ha = null;

            switch (h)
            {
            case HashType.Sha1:
                ha = new SHA1CryptoServiceProvider();
                break;

            case HashType.Sha256:
                ha = new SHA256Managed();
                break;

            case HashType.Sha384:
                ha = new SHA384Managed();
                break;

            case HashType.Sha512:
                ha = new SHA512Managed();
                break;

            case HashType.Md5:
                ha = new MD5CryptoServiceProvider();
                break;

            case HashType.Ripemd160:
                ha = new RIPEMD160Managed();
                break;
            }

            return(ha);
        }
Пример #2
0
        /// <summary>
        /// Gets the MID.
        /// </summary>
        /// <returns></returns>
        /// <remarks>Documented by Dev08, 2009-02-12</remarks>
        public static string GetMID()
        {
            lock (mid)
            {
                if (mid != string.Empty)
                {
                    return(mid);
                }

                string value;
                try
                {
                    value = Identifier("Win32_BaseBoard", "SerialNumber") + Identifier("Win32_Processor", "ProcessorId");
                }
                catch (MachineIDGenerationException mex)
                {
                    value = getOsMID();
                    if (value == null)
                    {
                        throw mex;
                    }
                }

                HashAlgorithm hashObject = new RIPEMD160Managed();
                byte[]        hash       = hashObject.ComputeHash(Encoding.ASCII.GetBytes(value));

                mid = ByteArrayToCompressedArrayString(hash).Substring(13, 8);
                return(mid);
            }
        }
Пример #3
0
        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();
            }
        }
Пример #4
0
 private static byte[] ComputeRipeMdHash(byte[] data)
 {
     using (RIPEMD160 ripemd160 = RIPEMD160Managed.Create())
     {
         return(ripemd160.ComputeHash(data));
     }
 }
Пример #5
0
        /// <summary>
        /// Create a hash value from a byte array's content.
        /// </summary>
        /// <param name="content">the literal content to evaluate for the hash.</param>
        /// <param name="method">The HashMethod enumeration for the evaluation</param>
        /// <returns>A hex-encoded value of the hash value</returns>
        public static string GetHash(byte[] content, HashMethod method)
        {
            HashAlgorithm hashString = new SHA1Managed();

            switch (method)
            {
            case HashMethod.SHA1:
                break;

            case HashMethod.SHA256:
                hashString = new SHA256Managed();
                break;

            case HashMethod.SHA384:
                hashString = new SHA384Managed();
                break;

            case HashMethod.SHA512:
                hashString = new SHA512Managed();
                break;

            case HashMethod.MD5:
                hashString = new MD5CryptoServiceProvider();
                break;

            case HashMethod.RIPEMD:
                hashString = new RIPEMD160Managed();
                break;

            default:
                throw new ArgumentException("Unrecognized hash encoding: " + method.ToString());
            }
            return(ByteArrayToHex(hashString.ComputeHash(content)));
        }
Пример #6
0
        public void TestScriptHash()
        {
            using (var script = new ScriptBuilder
                                (
                       EVMOpCode.PUSH0,
                       EVMOpCode.RET
                                ))
                using (var engine = CreateEngine(null))
                {
                    // Load script

                    engine.LoadScript(script);

                    // First check

                    Assert.AreEqual(1, engine.InvocationStack.Count);

                    // Check

                    byte[] realHash;
                    using (var sha = SHA256.Create())
                        using (var ripe = new RIPEMD160Managed())
                        {
                            realHash = sha.ComputeHash(script);
                            realHash = ripe.ComputeHash(realHash);
                        }

                    using (var context = engine.EntryContext)
                    {
                        Assert.IsTrue(context.ScriptHash.SequenceEqual(realHash));
                    }
                }
        }
Пример #7
0
        public static Address GenerateAddress(string _privateKey = "", bool _mainNet = true)
        {
            _privateKey = _privateKey == "" ? RandomPlus.RandomHex(64) : _privateKey;

            BigInteger _privateInt = BigInteger.Parse("0" + _privateKey, System.Globalization.NumberStyles.HexNumber);

            byte[] _publicKey = Secp256k1.PrivateKeyToPublicKey(_privateInt);

            SHA256Managed    _sha256 = new SHA256Managed();
            RIPEMD160Managed _ripemd = new RIPEMD160Managed();

            byte[] _ripemdHashed = _ripemd.ComputeHash(_sha256.ComputeHash(_publicKey));
            byte[] _addedVersion = new byte[_ripemdHashed.Length + 1];
            _addedVersion[0] = (byte)(_mainNet ? 0x00 : 0x6f);
            Array.Copy(_ripemdHashed, 0, _addedVersion, 1, _ripemdHashed.Length);

            byte[] _shaHashed = _sha256.ComputeHash(_sha256.ComputeHash(_addedVersion));
            Array.Resize(ref _shaHashed, 4);

            byte[] _result = new byte[_addedVersion.Length + _shaHashed.Length];
            Array.Copy(_addedVersion, 0, _result, 0, _addedVersion.Length);
            Array.Copy(_shaHashed, 0, _result, _addedVersion.Length, _shaHashed.Length);

            string _key1 = string.Join("", (_mainNet ? "80" : "ef"), _privateKey);
            string _key2 = HexPlus.ByteArrayToHexString(SHA.EncodeSHA256(SHA.EncodeSHA256(HexPlus.HexStringToByteArray(_key1))).Take(4).ToArray());

            Address _address = new Address();

            _address.Text       = Base58.Encode(_result);
            _address.PublicKey  = HexPlus.ByteArrayToHexString(_publicKey);
            _address.PrivateKey = Base58.Encode(_key1 + _key2);
            _address.Text       = (_mainNet ? (_address.Text.StartsWith("1") ? "" : "1") : "") + _address.Text;
            return(_address);
        }
Пример #8
0
        public Address(Byte[] data, Byte version = PUBKEY)
        {
            SHA256    sha256    = new SHA256Managed();
            RIPEMD160 ripemd160 = new RIPEMD160Managed();

            switch (version)
            {
            case PUBKEY:
                pubKeyHash = ripemd160.ComputeHash(sha256.ComputeHash(data));
                version    = PUBKEYHASH;
                break;

            case SCRIPT:
                scriptHash = ripemd160.ComputeHash(sha256.ComputeHash(data));
                version    = SCRIPTHASH;
                break;

            case PUBKEYHASH:
                pubKeyHash = data;
                break;

            case SCRIPTHASH:
                scriptHash = data;
                break;
            }
            this.type = version;
        }
Пример #9
0
 public static Hash RipeMD160(Hash data)
 {
     using (RIPEMD160Managed rp = new RIPEMD160Managed())
     {
         return(rp.ComputeHash(data));
     }
 }
Пример #10
0
 public HMACRIPEMD160 (byte[] key) {
     m_hashName = "RIPEMD160";
     m_hash1 = new RIPEMD160Managed();
     m_hash2 = new RIPEMD160Managed();
     HashSizeValue = 160;
     base.InitializeKey(key);
 }
Пример #11
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 кодировке
        }
Пример #12
0
 // :$$$.контрольнаясумма
 public static byte[] MD160(byte[] toHash)
 {
     using (RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create())
     {
         return(myRIPEMD160.ComputeHash(toHash));
     }
 }
Пример #13
0
        void DoHash(string expectedHex, string textInput)
        {
            var hashAlgo = new RIPEMD160Managed();
            var res      = hashAlgo.ComputeHash(Encoding.ASCII.GetBytes(textInput));

            Assert.Equal(expectedHex, res.ToHexString(), ignoreCase: true);
        }
        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);
        }
Пример #15
0
        static byte[] GetRMD160Hash(byte[] myByte)
        {
            RIPEMD160 _r160 = RIPEMD160Managed.Create();

            byte[] _encrypted = _r160.ComputeHash(myByte);
            ; return(_encrypted);
        }
Пример #16
0
        public void HASH160()
        {
            InternalTestBigInteger(EVMOpCode.HASH160, (engine, a, cancel) =>
            {
                byte[] hash;

                try
                {
                    using (var sha = System.Security.Cryptography.SHA256.Create())
                        using (var ripe = new RIPEMD160Managed())
                        {
                            hash = sha.ComputeHash(a == 0 ? new byte[] { } : a.ToByteArray());
                            hash = ripe.ComputeHash(hash);
                        }
                }
                catch
                {
                    Assert.AreEqual(engine.State, EVMState.Fault);
                    cancel.Cancel = true;
                    return;
                }

                Assert.IsTrue(engine.ResultStack.Pop <ByteArrayStackItem>().Value.SequenceEqual(hash));
            });
        }
Пример #17
0
        /// <summary>
        /// Thanks http://gobittest.appspot.com/Address
        /// </summary>
        /// <param name="ecdsaPublickey">Standard format ecdsa public key taken from the blockchain</param>
        /// <returns></returns>
        private static string ComputeBitcoinAddress(byte[] ecdsaPublickey)
        {
            // step1: byte[32] -- sha256 ecdsaPublicKey
            // step2: byte[20] -- ripemd-160 hash step1
            // step3: byte[21] -- add network bytes to step2
            // step4: byte[32] -- sha256 step3
            // step5: byte[32] -- sha256 step4
            // step6: byte[4]  -- get first four bytes of step 5
            // step7: byte[25] -- add step6 to the end of step3

            using (var sha256Managed = new SHA256Managed())
            {
                using (var ripeMd160Managed = new RIPEMD160Managed())
                {
                    var step3 = new byte[21];
                    var step6 = new byte[4];
                    var step7 = new byte[25];

                    var step1 = sha256Managed.ComputeHash(ecdsaPublickey);
                    var step2 = ripeMd160Managed.ComputeHash(step1);
                    Array.Copy(step2, 0, step3, 1, 20);
                    var step4 = sha256Managed.ComputeHash(step3);
                    var step5 = sha256Managed.ComputeHash(step4);
                    Array.Copy(step5, 0, step6, 0, 4);
                    Array.Copy(step3, 0, step7, 0, 21);
                    Array.Copy(step6, 0, step7, 21, 4);

                    return(Base58Encoding.Encode(step7));
                }
            }
        }
Пример #18
0
 public static byte[] ToRIPEMD160Managed(this string s, Encoding encoding)
 {
     using (var ripemd160 = new RIPEMD160Managed())
     {
         return(ripemd160.ComputeHash(s.GetBytes(encoding)));
     }
 }
Пример #19
0
        public static Address GetLegacyAddress(string _private = "", bool _mainnet = true)
        {
            _private = _private == "" ? RandomPlus.RandomHex(64) : _private;

            BigInteger _privateInt = BigInteger.Parse("0" + _private, NumberStyles.HexNumber);

            byte[] _public = Secp256k1.PrivateKeyToPublicKey(_privateInt, false);

            RIPEMD160Managed _ripemd = new RIPEMD160Managed();

            byte[] _ripemdHashed = _ripemd.ComputeHash(SHA.EncodeSHA256(_public));
            byte[] _addedVersion = new byte[_ripemdHashed.Length + 1];
            _addedVersion[0] = (byte)(_mainnet ? 0x00 : 0x6f);
            Array.Copy(_ripemdHashed, 0, _addedVersion, 1, _ripemdHashed.Length);

            byte[] _shaHashed = SHA.EncodeSHA256(SHA.EncodeSHA256(_addedVersion));
            Array.Resize(ref _shaHashed, 4);

            byte[] _result = new byte[_addedVersion.Length + _shaHashed.Length];
            Array.Copy(_addedVersion, 0, _result, 0, _addedVersion.Length);
            Array.Copy(_shaHashed, 0, _result, _addedVersion.Length, _shaHashed.Length);

            string _key1 = string.Join("", (_mainnet ? "80" : "ef"), _private);
            string _key2 = HexPlus.ByteArrayToHexString(SHA.EncodeSHA256(SHA.EncodeSHA256(HexPlus.HexStringToByteArray(_key1))).Take(4).ToArray());

            Address _address = new Address
            {
                Text    = Base58.Encode(_result),
                Public  = HexPlus.ByteArrayToHexString(_public),
                Private = Base58.Encode(_key1 + _key2)
            };

            return(_address);
        }
Пример #20
0
        public static Address GenerateAddress(out string _uncompressKey, string _existsPrivateKey = "", bool _mainNet = true)
        {
            string _netVersion = _mainNet ? "00" : "6f";
            string _privateKey = string.IsNullOrWhiteSpace(_existsPrivateKey) ? Lion.RandomPlus.RandomHex() : _existsPrivateKey;

            _uncompressKey = _privateKey;
            BigInteger    _bigPrivateKey = BigInteger.Parse("0" + _privateKey, System.Globalization.NumberStyles.HexNumber);
            var           _publicKey     = Secp256k1.PrivateKeyToPublicKey(_bigPrivateKey);
            SHA256Managed sha256         = new SHA256Managed();
            var           _ripemd        = new RIPEMD160Managed();
            var           _ripemdHashed  = _ripemd.ComputeHash(sha256.ComputeHash(_publicKey));
            var           _addedVersion  = new byte[_ripemdHashed.Length + 1];

            if (!_mainNet)
            {
                _addedVersion[0] = 0x6f;
            }
            Buffer.BlockCopy(_ripemdHashed, 0, _addedVersion, 1, _ripemdHashed.Length);
            var _doubleSha = sha256.ComputeHash(sha256.ComputeHash(_addedVersion));

            Array.Resize(ref _doubleSha, 4);

            byte[] _result = new byte[_addedVersion.Length + _doubleSha.Length];
            Buffer.BlockCopy(_addedVersion, 0, _result, 0, _addedVersion.Length);
            Buffer.BlockCopy(_doubleSha, 0, _result, _addedVersion.Length, _doubleSha.Length);

            Address _address = new Address();

            _address.Text       = Base58.Encode(_result);
            _address.PublicKey  = Lion.HexPlus.ByteArrayToHexString(_publicKey);
            _address.PrivateKey = CompressPrivateKey(_privateKey, _mainNet);
            _address.Text       = (_mainNet ? (_address.Text.StartsWith("1") ? "" : "1") : "") + _address.Text;
            return(_address);
        }
Пример #21
0
 private static byte[] RipeMD160(byte[] pubKey)
 {
     using (var hasher = new RIPEMD160Managed())
     {
         return(hasher.ComputeHash(pubKey));
     }
 }
Пример #22
0
        private static HashAlgorithm GetAlgorithm(string algorithm)
        {
            switch (algorithm)
            {
            case "MD5":
                return(new MD5CryptoServiceProvider());

            case "RIPEMD160":
                return(RIPEMD160Managed.Create());

            case "SHA1":
                return(new SHA1CryptoServiceProvider());

            case "SHA256":
                return(new SHA256CryptoServiceProvider());

            case "SHA384":
                return(new SHA384CryptoServiceProvider());

            case "SHA512":
                return(new SHA512CryptoServiceProvider());

            default:
                throw new Exception("Invalid Hash Algorithm Provided");
            }
        }
Пример #23
0
 private byte[] HexToRipe(string data)
 {
     using (var ripe = new RIPEMD160Managed())
     {
         return(ripe.ComputeHash(Encoding.Unicode.GetBytes(data)));
     }
 }
Пример #24
0
 public static byte[] ToRIPEMD160(this byte[] s)
 {
     using (var ripemd160 = new RIPEMD160Managed())
     {
         return(ripemd160.ComputeHash(s));
     }
 }
Пример #25
0
 public static byte[] RIPEMD160(byte[] data, int offset, int count)
 {
     using (var ripm = new RIPEMD160Managed())
     {
         return(ripm.ComputeHash(data, offset, count));
     }
 }
Пример #26
0
        private string RIPEMD160Hash(string input)
        {
            var RIPEMD160Manager = new RIPEMD160Managed();

            byte[] byteHash = RIPEMD160Manager.ComputeHash(ASCIIEncoding.ASCII.GetBytes(input));
            return(BitConverter.ToString(byteHash).Replace("-", null));
        }
Пример #27
0
 public static byte[] ComputeRIPEMD160(byte[] data)
 {
     using (RIPEMD160Managed ripemd160 = new RIPEMD160Managed())
     {
         return(ripemd160.ComputeHash(data));
     }
 }
Пример #28
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);
        }
Пример #29
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.");
        }
    }
Пример #30
0
        public byte[] CreateOutputFromPublicKey(byte[] publicKey)
        {
            var sha256        = new SHA256Managed();
            var ripemd160     = new RIPEMD160Managed();
            var publicKeyHash = ripemd160.ComputeHash(sha256.ComputeHash(publicKey));

            return(CreateOutputFromPublicKeyHash(publicKeyHash));
        }
Пример #31
0
 public HMACRIPEMD160(byte[] key)
 {
     m_hashName    = "RIPEMD160";
     m_hash1       = new RIPEMD160Managed();
     m_hash2       = new RIPEMD160Managed();
     HashSizeValue = 160;
     base.InitializeKey(key);
 }