Exemple #1
0
        static byte[] GetRMD160Hash(byte[] myByte)
        {
            RIPEMD160 _r160 = RIPEMD160Managed.Create();

            byte[] _encrypted = _r160.ComputeHash(myByte);
            ; return(_encrypted);
        }
        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);
        }
        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();
            }
        }
Exemple #4
0
 // :$$$.контрольнаясумма
 public static byte[] MD160(byte[] toHash)
 {
     using (RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create())
     {
         return(myRIPEMD160.ComputeHash(toHash));
     }
 }
Exemple #5
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");
            }
        }
Exemple #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 кодировке
        }
Exemple #7
0
 private static byte[] ComputeRipeMdHash(byte[] data)
 {
     using (RIPEMD160 ripemd160 = RIPEMD160Managed.Create())
     {
         return(ripemd160.ComputeHash(data));
     }
 }
Exemple #8
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);
        }
    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.");
        }
    }
Exemple #10
0
        public static byte[] Hash160(byte[] bytes)
        {
            var sha256    = SHA256Managed.Create();
            var ripemd160 = RIPEMD160Managed.Create();

            return(ripemd160.ComputeHash(
                       sha256.ComputeHash(bytes)
                       ));
        }
Exemple #11
0
        public void RIPEMD160(string fname)//TODO: check for null fname
        {
            if (string.IsNullOrWhiteSpace(fname))
            {
                return;
            }
            StreamReader sr       = new StreamReader(fname);
            RIPEMD160    ripmd160 = RIPEMD160Managed.Create();

            byte[] cmphash = ripmd160.ComputeHash(sr.BaseStream);
            Hashvalue = No2Hex(cmphash);
        }
Exemple #12
0
        string hash_value(string local_path)
        {
            RIPEMD160  myRIPEMD160   = RIPEMD160Managed.Create();
            FileStream tmppathStream = File.OpenRead(local_path);

            byte[] hashValue = myRIPEMD160.ComputeHash(tmppathStream);
            tmppathStream.Close();
            string hash = BitConverter.ToString(hashValue).Replace("-", String.Empty);


            return(hash);
        }
 public static byte[] hash160(byte[] data)
 {
     byte[] hash1;
     byte[] hash2;
     using (SHA256Managed sha256 = new SHA256Managed())
     {
         hash1 = sha256.ComputeHash(data);
     }
     using (RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create())
     {
         hash2 = myRIPEMD160.ComputeHash(hash1);
     }
     return(hash2);
 }
Exemple #14
0
        public static string getHash(string cartera)
        {
            RIPEMD160 r160 = RIPEMD160Managed.Create();

            byte[]        myByte    = System.Text.Encoding.ASCII.GetBytes(cartera);
            byte[]        encrypted = r160.ComputeHash(myByte);
            StringBuilder sb        = new StringBuilder();

            for (int i = 0; i < encrypted.Length; i++)
            {
                sb.Append(encrypted[i].ToString("x2"));
            }
            return(sb.ToString().ToLower());
        }
        public string GetPublicAddress()
        {
            byte[] content = Tool.Sha3Util.Get256Hash(GetPubKey());

            content = RIPEMD160Managed.Create().ComputeHash(content);
            //content = RIPEMD160Managed.GetHash(content);


            content = ByteUtil.Merge(new byte[] { ADDRESS_PREFIX }, new byte[] { (int)AddressType.NormalType }, content);


            byte[] checksum = ByteUtil.Slice(Tool.Sha3Util.Get256Hash(content), 0, 4);

            return(ByteUtil.Merge(content, checksum).ToHex());
        }
Exemple #16
0
 /// <summary>
 /// RIPEMD160哈希算法
 /// </summary>
 /// <param name="para"></param>
 /// <returns></returns>
 public static string GetRIPEMD160String(this string para)
 {
     try
     {
         var md5      = RIPEMD160Managed.Create();
         var byteData = System.Text.Encoding.UTF8.GetBytes(para);
         byteData = md5.ComputeHash(byteData);
         var OutString = BitConverter.ToString(byteData).Replace("-", "").ToUpper();
         return(OutString);
     }
     catch
     {
         return(para);
     }
 }
Exemple #17
0
        private void button4_Click(object sender, EventArgs e)
        {
            string hashstring = "";



            try
            {
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                // Call the ShowDialog method to show the dialog box.
                DialogResult userClickedOK = openFileDialog1.ShowDialog();

                RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
                byte[]    hashValue;

#if DEBUG
                Console.WriteLine(userClickedOK);
#endif
                // Process input if the user clicked OK.
                if (userClickedOK == DialogResult.OK)
                {
                    // Open the selected file to read.
                    FileStream fileStream = new FileStream(openFileDialog1.FileName, FileMode.Open);
                    fileStream.Position = 0;
                    // Compute the hash of the fileStream.
                    hashValue = myRIPEMD160.ComputeHash(fileStream);


                    cm.SetFile(hashValue);
#if DEBUG
                    Console.WriteLine("hash=" + PrintByteArray(hashValue));
#endif
                    cm.Path = openFileDialog1.FileName;
                    fileStream.Close();
                }

                statusLabel.Text = "File in Use: " + openFileDialog1.FileName;
                certInUse        = false;
            }
            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.");
            }
        }
        public static byte[] ComputeHash(byte[] input, string algorithm)
        {
            if (input == null)
            {
                throw new ArgumentNullException();
            }

            System.Security.Cryptography.HashAlgorithm hash;
            switch (algorithm.ToUpperInvariant())
            {
            case "BKDR":
                hash = new BKDRManaged();
                break;

            case "MD5":
                hash = MD5CryptoServiceProvider.Create();
                break;

            case "MD160":
            case "RIPEMD160":
                hash = RIPEMD160Managed.Create();
                break;

            case "SHA":
            case "SHA1":
                hash = SHA1CryptoServiceProvider.Create();
                break;

            case "SHA256":
                hash = SHA256Managed.Create();
                break;

            case "SHA384":
                hash = SHA384Managed.Create();
                break;

            case "SHA512":
                hash = SHA512Managed.Create();
                break;

            default:
                throw new NotSupportedException();
            }
            byte[] result = hash.ComputeHash(input);
            hash.Clear();
            return(result);
        }
        /// <summary>
        /// Returns singleton of Packager with PackageHash created and set. Hashes current app domain's DLL, EXE and CONFIG files.
        /// </summary>
        /// <returns></returns>
        internal static Packager Create()
        {
            if (null != _singleton)
            {
                return(_singleton);
            }
            lock (_syncRoot)
            {
                if (null != _singleton)
                {
                    return(_singleton);
                }
                var rootDir     = AppDomain.CurrentDomain.BaseDirectory;
                var exeFiles    = Directory.GetFiles(rootDir, "*.exe", SearchOption.AllDirectories);
                var dllFiles    = Directory.GetFiles(rootDir, "*.dll", SearchOption.AllDirectories);
                var configFiles = Directory.GetFiles(rootDir, "*.config", SearchOption.AllDirectories);

                var list = exeFiles.Concat(dllFiles).Concat(configFiles).Where(n => !Path.GetFileName(n).Contains(".vshost.")).ToList();
                list.Sort();

                //get hash codes for each file
                var fileHashes = new ConcurrentDictionary <string, string>();
                Parallel.ForEach(list, file =>
                {
                    using (RIPEMD160 rip = RIPEMD160Managed.Create())
                    {
                        byte[] hashValue;
                        using (var fileStream = File.OpenRead(file))
                        {
                            fileStream.Position = 0;
                            hashValue           = rip.ComputeHash(fileStream);
                        }
                        fileHashes.TryAdd(file, Convert.ToBase64String(hashValue));
                    }
                });

                var hash = new PackageHash()
                {
                    Name   = AppDomain.CurrentDomain.FriendlyName,
                    Files  = fileHashes.Keys.ToArray(),
                    Hashes = fileHashes.Values.ToArray()
                };

                _singleton = new Packager(hash);
                return(_singleton);
            }
        }
Exemple #20
0
        /// <summary>
        /// Загрузка файла в БД
        /// </summary>
        /// <param name="fileName">Полный путь и имя файла для загрузки в БД</param>
        public void Upload(String fullFileName)
        {
            SqlConnection CN          = MiscFunction.OpenConnection(_connectionString);
            RIPEMD160     myRIPEMD160 = RIPEMD160Managed.Create();
            String        fileName    = MiscFunction.GetFileName(fullFileName);

            FileStream fs = new System.IO.FileStream(fullFileName, FileMode.Open, FileAccess.Read);

            Byte[] imageData = new Byte[fs.Length];
            fs.Read(imageData, 0, Convert.ToInt32(fs.Length));

            //SHA-1
            byte[] hashValue;
            hashValue = myRIPEMD160.ComputeHash(fs);
            string result = BitConverter.ToString(hashValue).Replace("-", String.Empty);

            //System.IO.File.WriteAllText("C:\\Users\\Марсель\\Documents\\Uploader\\Updater\\bin\\Debug\\TestFile2.txt", result);

            fs.Close();

            String strSQL;

            if (!ChekExists(CN, fileName))
            {//INSERT
                strSQL = "INSERT INTO Srv_ProgramFile (version, name, author, binaryData, Date, hashCode) " +
                         "VALUES (1, @name, @autor, @binaryData, @Date, @hashCode)";
            }
            else
            {//UPDATE
                strSQL = "UPDATE Srv_ProgramFile SET version=version+1, name=@name, author=@autor, binaryData=@binaryData " +
                         "WHERE name=@name";
            }

            SqlCommand cmd = new SqlCommand(strSQL, CN)
            {
                CommandTimeout = 60
            };

            cmd.Parameters.Add(new SqlParameter("@name", SqlDbType.NVarChar, 128)).Value = fileName;
            cmd.Parameters.Add(new SqlParameter("@autor", SqlDbType.NVarChar, 50)).Value = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            cmd.Parameters.Add(new SqlParameter("@binaryData", SqlDbType.Image)).Value   = imageData;
            cmd.Parameters.Add("@Date", DateTime.Now.Date);
            cmd.Parameters.Add("@hashCode", SqlDbType.NVarChar, 50).Value = result;
            cmd.ExecuteNonQuery();

            CN.Close();
        }
Exemple #21
0
        static void Main(string[] args)
        {
            try
            {
                log.Add("Входная строка " + args[0]);
                string[] split_vhparam = args[0].Split('=');

                Process proc2 = Process.GetProcessById(Convert.ToInt32(split_vhparam[0]));

                proc2.WaitForExit();

                string path = split_vhparam[2];//new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.ToString() + @"\TreeCadN.dll";


                WebClient client = new WebClient();
                var       url    = "http://ecad.giulianovars.ru/TreeCadN/TreeCadN.dll";


                string tmppath = Path.GetTempPath() + @"\TreeCadN.dll";


                client.DownloadFile(url, tmppath);//скачаем новую


                RIPEMD160  myRIPEMD160   = RIPEMD160Managed.Create();
                FileStream tmppathStream = File.OpenRead(tmppath);
                byte[]     hashValue     = myRIPEMD160.ComputeHash(tmppathStream);
                tmppathStream.Close();
                string hash = BitConverter.ToString(hashValue).Replace("-", String.Empty);


                if (hash == split_vhparam[1])
                {
                    log.Add("заменим на новую - успех");
                    File.Copy(tmppath, path, true);//заменим на новую
                    //   MessageBox.Show("Процесс завершён обновимся сумма=" + hash);
                }


                File.Delete(tmppath);                                                                                            // File.Delete("TreeCadN_pre.dll");
            }
            catch (Exception err) {
                log.Add("catch " + err.Message);
            }
        }
Exemple #22
0
        public static string getHash(string method, string text)
        {
            byte[] bytes      = StringToByteArray(text);
            string hashString = "";

            if (method.Equals("sha256"))
            {
                SHA256Managed hashMethod = new SHA256Managed();
                hashString = getHashStringFromBytes(hashMethod.ComputeHash(bytes));
            }
            else if (method.Equals("ripemd160"))
            {
                RIPEMD160 hashMethod = RIPEMD160Managed.Create();
                hashString = getHashStringFromBytes(hashMethod.ComputeHash(bytes));
            }

            return(hashString);
        }
        static string getHash(string password)
        {
            // create a ripemd160 object
            RIPEMD160 r160 = RIPEMD160Managed.Create();

            // convert the string to byte
            byte[] myByte = System.Text.Encoding.ASCII.GetBytes(password);
            // compute the byte to RIPEMD160 hash
            byte[] encrypted = r160.ComputeHash(myByte);
            // create a new StringBuilder process the hash byte
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < encrypted.Length; i++)
            {
                sb.Append(encrypted[i].ToString("X2"));
            }
            // convert the StringBuilder to String and convert it to lower case and return it.
            return(sb.ToString().ToLower());
        }
Exemple #24
0
        private void sha1sumAllFiles(string directory)
        {
            output.Text += "Taking sha1sum's of all files...\n";
            // 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)
            {
                output.Text += "Taking sha1sum for " + fInfo.Name + "...";
                // 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);
                //conver the byte array to a HEX string
                string convertedHash = HexStringFromBytes(hashValue);
                // Write the Hex value to a file called <FILENAME>.sha
                if (File.Exists(Directory.GetCurrentDirectory() + "/Evidence/" + Path.GetFileNameWithoutExtension(fInfo.Name) + ".sha"))
                {
                    warningText.Text = "Warning: Ended with errors. Check the output window for information.";
                    string errorText = "\nERROR:File already exsists. Remove it and try again.\n";
                    output.AppendText(errorText);
                }
                else
                {
                    File.WriteAllText(directory + "/" + Path.GetFileNameWithoutExtension(fInfo.Name) + ".sha", convertedHash + " *" + Path.GetFileName(fInfo.Name));
                }
                // Close the file.
                fileStream.Close();
                output.Text += "Done.\n";
            }
            output.Text += "Finished taking sha1sums of all files.\n";
        }
Exemple #25
0
        } //compute hash from arguments and return hash value as string

        private static string GetRIPEMD160Hash(string text)
        {
            //create variables for computing hash and making it a string
            UnicodeEncoding UniCode = new UnicodeEncoding();

            byte[]    HashResult;
            byte[]    msg        = UniCode.GetBytes(text);
            RIPEMD160 hashString = RIPEMD160Managed.Create();
            string    Str        = "";

            //compute hash with RIPEMD160 module and format output as string
            //convert bytes in HashResult to string values
            HashResult = hashString.ComputeHash(msg);
            foreach (byte x in HashResult)
            {
                Str += String.Format("{0:x2}", x);
            }

            //clear excess resource usage
            hashString.Clear();
            return(Str);
        } //compute hash from arguments and return hash value as string
Exemple #26
0
        public void RipemdCalls()
        {
            using (var ripemd160 = RIPEMD160.Create()) // Noncompliant
            {
            }
            using (var ripemd160 = HashAlgorithm.Create("RIPEMD160")) // Noncompliant
            {
            }
            using (var ripemd160 = (HashAlgorithm)CryptoConfig.CreateFromName("RIPEMD160")) // Noncompliant
            {
            }

            using (var ripemd160Managed = RIPEMD160Managed.Create()) // Noncompliant
            {
            }
            using (var ripemd160Managed = HashAlgorithm.Create("RIPEMD160Managed")) // Noncompliant
            {
            }
            using (var ripemd160Managed = (HashAlgorithm)CryptoConfig.CreateFromName("RIPEMD160Managed")) // Noncompliant
            {
            }
        }
Exemple #27
0
        public static InvocationTransaction GetDeployContractTransaction(ContractModel contractModel, out string scriptHash, out string scriptBytesString)
        {
            MainWindow mainWindow = (MainWindow)App.Current.MainWindow;

            scriptHash        = null;
            scriptBytesString = null;

            if (mainWindow.ActiveDocument == null)
            {
                return(null);
            }

            RIPEMD160 myRIPEMD160    = RIPEMD160Managed.Create();
            string    uniqueTempHash = BitConverter.ToString(myRIPEMD160.ComputeHash(Guid.NewGuid().ToByteArray()));

            mainWindow.ActiveDocument.scintilla.Text = mainWindow.ActiveDocument.scintilla.Text.Replace("MI4m2tqy+RPxxQfKGdKhg1Hb62s=", uniqueTempHash);
            mainWindow.ActiveDocument.Save();
            if (!SmartContract.Build())
            {
                return(null);
            }

            string contractFileName = Path.Combine(Path.GetDirectoryName(mainWindow.ActiveDocument.FilePath), Path.GetFileNameWithoutExtension(mainWindow.ActiveDocument.FilePath), ".avm");

            if (!File.Exists(contractFileName))
            {
                return(null);
            }

            if (!contractModel.Validate())
            {
                return(null);
            }

            byte[] script = File.ReadAllBytes(contractFileName);
            scriptHash = script.ToScriptHash().ToString();

            byte[] parameter_list = contractModel.ParameterHexValue.HexToBytes();

            ContractParameterType return_type = contractModel.ReturnTypeHexValue.HexToBytes().Select(p => (ContractParameterType?)p).FirstOrDefault() ?? ContractParameterType.Void;
            ContractPropertyState properties  = ContractPropertyState.NoProperty;

            if (contractModel.IsStorageRequired)
            {
                properties |= ContractPropertyState.HasStorage;
            }
            if (contractModel.HasDynamicInvoke)
            {
                properties |= ContractPropertyState.HasDynamicInvoke;
            }

            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitSysCall("Neo.Contract.Create", script, parameter_list, return_type, properties, contractModel.Name, contractModel.Version, contractModel.Author,
                               contractModel.Email, contractModel.Description);
                return(new InvocationTransaction
                {
                    Script = sb.ToArray()
                });
            }
        }
Exemple #28
0
        public static byte[] RipeMd160(byte[] data)
        {
            var h160 = RIPEMD160Managed.Create();

            return(h160.ComputeHash(data));
        }
Exemple #29
0
        public static byte[] RipeMd160(byte[] data, int offset, int count)
        {
            var h160 = RIPEMD160Managed.Create();

            return(h160.ComputeHash(data, offset, count));
        }
Exemple #30
0
        static void Main(string[] args)
        {
            // Bitcoin
            var privateKeyBitcoin             = "L4Y1cGSsNv1Nf9dZpTkEyQjLU24zRyRQeRyE5i4MoVvrjrr15Koy"; // Example https://komodoplatform.com/en/academy/bitcoin-private-key/
            var privateKeyBillText            = new BitcoinSecret(privateKeyBitcoin, Network.Main);
            var uncompressed                  = privateKeyBillText.Copy(false);
            var privateKeyBill                = uncompressed.ToBytes();
            var publicKeyBillText             = privateKeyBillText.PubKey.GetAddress(ScriptPubKeyType.Legacy, Network.Main).ToString();
            var publicKeyBillTextUncompressed = uncompressed.PubKey.GetAddress(ScriptPubKeyType.Legacy, Network.Main).ToString(); // TODO Remove
            var publicKeyBillHex              = Convert.ToHexString(uncompressed.PubKey.ToBytes().Skip(1).ToArray());

            // Data
            var data = new byte[] { 1, 2, 3 };
            // var hash = SHA256.Create().ComputeHash(data); // Calculate hash of data. See also ECDsa.SignHash();

            // PrivateKey
            var privateKey = privateKeyBill; // new byte[32] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            // RNGCryptoServiceProvider.Create().GetBytes(privateKey); // Fill random

            // PublicKey calculate
            var ecdsaCurve = ECCurve.CreateFromFriendlyName("secp256k1");
            var ecdsa      = ECDsa.Create(new ECParameters
            {
                Curve = ecdsaCurve,
                D     = privateKey
            });
            var publicAndPrivateKey = ecdsa.ExportParameters(true);

            // Sign
            var ecdsaSign = ECDsa.Create(new ECParameters
            {
                Curve = ecdsaCurve,
                D     = publicAndPrivateKey.D,
                Q     = publicAndPrivateKey.Q
            });
            var signature = ecdsaSign.SignData(data, HashAlgorithmName.SHA256); // Needs private and public key

            // Verify
            var ecdsaVerify = ECDsa.Create(new ECParameters
            {
                Curve = ecdsaCurve,
                Q     = publicAndPrivateKey.Q
            });
            bool isValid = ecdsaVerify.VerifyData(data, signature, HashAlgorithmName.SHA256); // No private key needed!

            // Output
            var publicKey = Enumerable.Concat(publicAndPrivateKey.Q.X, publicAndPrivateKey.Q.Y).ToArray();

            Console.WriteLine("PrivateKey=" + Convert.ToHexString(publicAndPrivateKey.D));
            Console.WriteLine("PublicKey=" + Convert.ToHexString(publicKey));
            Console.WriteLine("Data=" + Convert.ToHexString(data));
            Console.WriteLine("IsValid=" + isValid);

            Debug.Assert(publicKeyBillHex == Convert.ToHexString(publicKey));

            // P2PKH Address
            var x = new byte[65];

            x[0] = 0x04;
            publicAndPrivateKey.Q.X.CopyTo(x, 1);
            publicAndPrivateKey.Q.Y.CopyTo(x, 33);

            var sha256    = System.Security.Cryptography.SHA256.Create().ComputeHash(x);
            var ripemd160 = RIPEMD160Managed.Create().ComputeHash(sha256);

            Debug.Assert(ripemd160.Length == 20);
            var publicKeyText = Base58CheckEncoding.Encode(Enumerable.Concat(new byte[] { 0 }, ripemd160).ToArray());

            // Debug.Assert(publicKeyBillText == publicKeyText); // TODO
            Debug.Assert(publicKeyBillTextUncompressed == publicKeyText); // TODO Remove. Use compressed

            Console.WriteLine("Hello World!");
        }