示例#1
0
        public static Hash160 GetScriptHashFromScript(byte[] script)
        {
            var scripthash = sha256.ComputeHash(script);

            scripthash = ripemd160.ComputeHash(scripthash);
            return(scripthash);
        }
示例#2
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;
        }
示例#3
0
        /// <summary>
        /// 获取密码hash值
        /// </summary>
        /// <param name="password">原始密码</param>
        /// <param name="salt">加密盐</param>
        /// <returns>密码hash值</returns>
        private string GetHashPwd(string password, string salt)
        {
            var content      = password + salt;
            var contentBytes = Encoding.UTF8.GetBytes(content);
            var part1        = Encoding.UTF8.GetBytes(salt);

            RIPEMD160Managed ripemd160Managed = new RIPEMD160Managed();
            var part2 = ripemd160Managed.ComputeHash(contentBytes);
            var part3 = ripemd160Managed.ComputeHash(part1.Concat(part2).ToArray());

            var part4 = SHA1.Create().ComputeHash(part3);

            return(Base58.Encode(part4));
        }
 /// <summary>
 /// Generate the initialization vector (IV) to feed to the encryption engine.
 /// </summary>
 /// <param name="passphrase">A string containing the passphrase</param>
 /// <param name="size">The size in bits of the IV to generate</param>
 /// <returns>An array of bytes containing the generated IV</returns>
 private static byte[] GenerateIV(string passphrase, int size)
 {
     try
     {
         // Complain if the passphrase is empty:
         if (passphrase == null || passphrase == String.Empty || passphrase == "")
         {
             throw new SecureFileException("The passphrase is empty");
         }
         if (size <= 0 || size % 8 != 0)
         {
             throw new SecureFileException("The block size of the generated initialization " +
                                           "vector (IV) is invalid");
         }
         // To generate the IV, we're going to do some funky things to the passphrase (and the
         // salt) to try and get something close to random but still derived.  To do that, we'll
         // use the RIPEMD-160 hash engine.
         RIPEMD160Managed rip = new RIPEMD160Managed();
         // Hash the password with RIPEMD-160 and convert the bytes to Base64:
         string passripper = Convert.ToBase64String(rip.ComputeHash(utf8.GetBytes(passphrase)));
         // Do the same thing with the salt:
         string saltripper = Convert.ToBase64String(rip.ComputeHash(utf8.GetBytes(salt)));
         // Reverse the passphrase using a StringBuilder, then hash that string as well using
         // the RIPEMD-160 / Base64 combo:
         StringBuilder sb     = new StringBuilder(passphrase.Length);
         char[]        ppBits = passphrase.ToCharArray();
         for (int i = passphrase.Length - 1; i >= 0; i--)
         {
             sb.Append(ppBits[i]);
         }
         string passriprev = Convert.ToBase64String(rip.ComputeHash(utf8.GetBytes(sb.ToString())));
         // Now we'll use SHA-512 and has the combined strings we generated above.  We'll end up
         // with a 512-bit IV, which is probably overkill, but it should be good and "randomized"
         // but still derived from the passphrase.
         SHA512Managed sha    = new SHA512Managed();
         byte[]        hashed =
             sha.ComputeHash(sha.ComputeHash(utf8.GetBytes(passriprev + saltripper +
                                                           passripper)));
         // Now just get the first so many bytes (size divided by 8) and return them:
         byte[] iv = new byte[size / 8];
         Array.Copy(hashed, iv, size / 8);
         return(iv);
     }
     catch (SecureFileException sfe) { throw sfe; }
     catch (Exception ex)
     {
         throw new SecureFileException("An unspecified error occurred: " + ex.ToString());
     }
 }
示例#5
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);
        }
示例#6
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));
            });
        }
        /// <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));
                }
            }
        }
示例#8
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)));
        }
示例#9
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);
            }
        }
示例#10
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);
        }
示例#11
0
 public static byte[] ToRIPEMD160Managed(this string s, Encoding encoding)
 {
     using (var ripemd160 = new RIPEMD160Managed())
     {
         return(ripemd160.ComputeHash(s.GetBytes(encoding)));
     }
 }
示例#12
0
 public static Hash RipeMD160(Hash data)
 {
     using (RIPEMD160Managed rp = new RIPEMD160Managed())
     {
         return(rp.ComputeHash(data));
     }
 }
示例#13
0
 public static byte[] ToRIPEMD160(this byte[] s)
 {
     using (var ripemd160 = new RIPEMD160Managed())
     {
         return(ripemd160.ComputeHash(s));
     }
 }
示例#14
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);
        }
示例#15
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);
        }
示例#16
0
 private static byte[] RipeMD160(byte[] pubKey)
 {
     using (var hasher = new RIPEMD160Managed())
     {
         return(hasher.ComputeHash(pubKey));
     }
 }
示例#17
0
 public static byte[] ComputeRIPEMD160(byte[] data)
 {
     using (RIPEMD160Managed ripemd160 = new RIPEMD160Managed())
     {
         return(ripemd160.ComputeHash(data));
     }
 }
示例#18
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));
                    }
                }
        }
示例#19
0
 public static byte[] RIPEMD160(byte[] data, int offset, int count)
 {
     using (var ripm = new RIPEMD160Managed())
     {
         return(ripm.ComputeHash(data, offset, count));
     }
 }
示例#20
0
 private byte[] HexToRipe(string data)
 {
     using (var ripe = new RIPEMD160Managed())
     {
         return(ripe.ComputeHash(Encoding.Unicode.GetBytes(data)));
     }
 }
示例#21
0
        private string RIPEMD160Hash(string input)
        {
            var RIPEMD160Manager = new RIPEMD160Managed();

            byte[] byteHash = RIPEMD160Manager.ComputeHash(ASCIIEncoding.ASCII.GetBytes(input));
            return(BitConverter.ToString(byteHash).Replace("-", null));
        }
示例#22
0
        public byte[] CreateOutputFromPublicKey(byte[] publicKey)
        {
            var sha256        = new SHA256Managed();
            var ripemd160     = new RIPEMD160Managed();
            var publicKeyHash = ripemd160.ComputeHash(sha256.ComputeHash(publicKey));

            return(CreateOutputFromPublicKeyHash(publicKeyHash));
        }
示例#23
0
        public static string GetRipeMd(string text)
        {
            byte[]           bytes = Encoding.UTF8.GetBytes(text);
            RIPEMD160Managed rMD   = new RIPEMD160Managed();

            byte[] hashed = rMD.ComputeHash(bytes);
            return(Convert.ToBase64String(hashed));
        }
示例#24
0
        /// <summary>
        /// Calculates RIPEMD160(SHA256(input)). This is used in Address calculations.
        /// </summary>
        public static byte[] Sha256Hash160(byte[] input)
        {
            var shaAlgorithm    = new SHA256Managed();
            var ripemdAlgorithm = new RIPEMD160Managed();
            var sha256          = shaAlgorithm.ComputeHash(input);

            return(ripemdAlgorithm.ComputeHash(sha256, 0, sha256.Length));
        }
示例#25
0
        public static byte[] PublicKeyHashed(byte[] pubK)
        {
            var pubHash       = Sha.GenerateSha256String(ByteHelper.GetStringFromBytes(pubK));
            var ripemd160     = new RIPEMD160Managed();
            var ripemd160Hash = ripemd160.ComputeHash(Encoding.UTF8.GetBytes(pubHash));

            return(ripemd160Hash);
        }
示例#26
0
        private static string GetKey(byte[] content)
        {
            RIPEMD160Managed ripemd160Managed = new RIPEMD160Managed();
            var part1 = ripemd160Managed.ComputeHash(content);
            var part2 = SHA1.Create().ComputeHash(content);

            return(Base58.Encode(part1.Concat(part2).ToArray()));
        }
示例#27
0
        private static string ripemdencrypt(string phrase)
        {
            UTF8Encoding     encoder      = new UTF8Encoding();
            RIPEMD160Managed ripemdhasher = new RIPEMD160Managed();

            byte[] hashedDataBytes = ripemdhasher.ComputeHash(encoder.GetBytes(phrase));
            return(byteArrayToString(hashedDataBytes));
        }
示例#28
0
        private static byte[] GetDataHash(byte[] byteData, HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256)
        {
            //choose any hash algorithm
            //SHA1Managed managedHash = new SHA1Managed();
            //return managedHash.ComputeHash(Encoding.Unicode.GetBytes(sampleData));
            // Create a SHA256
            switch (hashAlgorithm)
            {
            case HashAlgorithm.MD5:
                using (MD5 md5Hash = MD5.Create())
                {
                    // ComputeHash - returns byte array
                    return(md5Hash.ComputeHash(byteData));
                }

            case HashAlgorithm.RIPEMD160:
                using (RIPEMD160 ripemd160Hash = new RIPEMD160Managed())
                {
                    // ComputeHash - returns byte array
                    return(ripemd160Hash.ComputeHash(byteData));
                }

            case HashAlgorithm.SHA1:
                using (SHA1 sha1Hash = SHA1.Create())
                {
                    // ComputeHash - returns byte array
                    return(sha1Hash.ComputeHash(byteData));
                }

            case HashAlgorithm.SHA256:
                using (SHA256 sha256Hash = SHA256.Create())
                {
                    // ComputeHash - returns byte array
                    return(sha256Hash.ComputeHash(byteData));
                }

            case HashAlgorithm.SHA384:
                using (SHA384 sha384Hash = SHA384.Create())
                {
                    // ComputeHash - returns byte array
                    return(sha384Hash.ComputeHash(byteData));
                }

            case HashAlgorithm.SHA512:
                using (SHA256 sha256Hash = SHA256.Create())
                {
                    // ComputeHash - returns byte array
                    return(sha256Hash.ComputeHash(byteData));
                }

            default:
                using (SHA256 sha256Hash = SHA256.Create())
                {
                    // ComputeHash - returns byte array
                    return(sha256Hash.ComputeHash(byteData));
                }
            }
        }
示例#29
0
        public void TestDoubleFree()
        {
            ExecutionContextBase context;

            byte[] realHash;
            using (var script = new ScriptBuilder(EVMOpCode.RET))
                using (var engine = CreateEngine(null))
                {
                    // Load script

                    engine.LoadScript(script);

                    // Compute hash

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

                    // Get Context

                    context = engine.CurrentContext;

                    // Create new array

                    using (var ar = engine.CreateArray())
                    {
                        // Create bool item and free

                        using (var btest = engine.CreateBool(true))
                        {
                            // Append item to array

                            ar.Add(btest);
                        }

                        // Check

                        Assert.IsTrue(ar[0] is BooleanStackItem b0 && b0.Value);
                    }

                    Assert.AreEqual(context.NextInstruction, EVMOpCode.RET);
                    Assert.IsTrue(context.ScriptHash.SequenceEqual(realHash));
                }

            // Check

            Assert.ThrowsException <ObjectDisposedException>(() =>
            {
                Assert.AreEqual(context.NextInstruction, EVMOpCode.RET);
            });
            Assert.ThrowsException <ObjectDisposedException>(() =>
            {
                Assert.IsTrue(context.ScriptHash.SequenceEqual(realHash));
            });
        }
示例#30
0
        internal static string GetFileHash(string filePath, HashType type)
        {
            if (!File.Exists(filePath))
            {
                return(string.Empty);
            }

            System.Security.Cryptography.HashAlgorithm hasher;
            switch (type)
            {
            case HashType.SHA1:
            default:
                hasher = new SHA1CryptoServiceProvider();
                break;

            case HashType.SHA256:
                hasher = new SHA256Managed();
                break;

            case HashType.SHA384:
                hasher = new SHA384Managed();
                break;

            case HashType.SHA512:
                hasher = new SHA512Managed();
                break;

            case HashType.MD5:
                hasher = new MD5CryptoServiceProvider();
                break;

            case HashType.RIPEMD160:
                hasher = new RIPEMD160Managed();
                break;
            }
            StringBuilder buff = new StringBuilder();

            try
            {
                using (FileStream f = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192))
                {
                    hasher.ComputeHash(f);
                    Byte[] hash = hasher.Hash;
                    foreach (Byte hashByte in hash)
                    {
                        buff.Append(string.Format("{0:x2}", hashByte));
                    }
                }
            }
            catch (Exception exp)
            {
                string str = new System.Random(DateTime.Now.Second * DateTime.Now.Millisecond).Next().ToString();
                // String.Format( "HashGenerator.GetFileHash.\r\n\t{0}", exp.Message ).Log( "Error reading file." + str );
                return("Error reading file." + str);
            }
            return(buff.ToString());
        }