Ejemplo n.º 1
1
    public static CompareResult Compare(Bitmap bmp1, Bitmap bmp2)
    {
        CompareResult cr = CompareResult.ciCompareOk;

        //Test to see if we have the same size of image
        if (bmp1.Size != bmp2.Size)
        {
            cr = CompareResult.ciSizeMismatch;
        }
        else
        {
            //Convert each image to a byte array
            System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
            byte[] btImage1 = new byte[1];
            btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
            byte[] btImage2 = new byte[1];
            btImage2 = (byte[])ic.ConvertTo(bmp2, btImage2.GetType());

            //Compute a hash for each image
            SHA256Managed shaM = new SHA256Managed();
            byte[] hash1 = shaM.ComputeHash(btImage1);
            byte[] hash2 = shaM.ComputeHash(btImage2);

            //Compare the hash values
            for (int i = 0; i < hash1.Length && i < hash2.Length && cr == CompareResult.ciCompareOk; i++)
            {
                if (hash1[i] != hash2[i])
                    cr = CompareResult.ciPixelMismatch;
            }
            shaM.Clear();
        }

        return cr;
    }
Ejemplo n.º 2
0
    private static SqlDataRecord FillRecord(Int32 pk, SqlDataRecord record)
    {
        Int32 age = SlowRandom(16, 99);
        string sourceString = "Age: " + age.ToString();
        DateTime sourceDate = DateTime.UtcNow;

        var data = /*salt + */sourceString;
                
        string key = "Top Secret Key";

        var encData = AES.EncryptBytes(data, key);
        //var encDataBytes = Encoding.Unicode.GetBytes(encData);
        var decData = AES.DecryptBytes(encData, key);

        var sha = new SHA256Managed();
        byte[] dataSHA256 = sha.ComputeHash(encData/*Bytes*/);
        sha.Dispose();

        // конвертирую хеш из byte[16] в строку шестнадцатиричного формата
        // (вида «3C842B246BC74D28E59CCD92AF46F5DA»)
        // это опциональный этап, если вам хеш нужен в строковом виде
        // string sha512hex = BitConverter.ToString(dataSHA512).Replace("-", string.Empty); 

        record.SetInt32(0, pk);
        record.SetDateTime(1, sourceDate);        
        record.SetString(2, sourceString);
        record.SetString(3, Convert.ToBase64String(dataSHA256)); // sha256
        record.SetString(4, Convert.ToBase64String(encData)); // Encrypted
        record.SetString(5, decData); // Decrypted

        return record;
    }
Ejemplo n.º 3
0
    static Boolean Test()
    {
    	Console.WriteLine("Testing SHA256 hash...");
    	SimpleHash	sh = new SimpleHash();
        SHA256 sha = new SHA256Managed();

		return sh.TestAlgorithm(sha);
    }
Ejemplo n.º 4
0
        public HMACSHA256 (byte[] key) {
            m_hashName = "SHA256"; 

            m_hash1 = new SHA256Managed(); 
            m_hash2 = new SHA256Managed(); 
            HashSizeValue = 256;
            base.InitializeKey(key); 
        }
Ejemplo n.º 5
0
    //hashes the string
    public static byte[] sha256(string password)
    {
        var crypt = new SHA256Managed();
        string hash = String.Empty;
        byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(password), 0, Encoding.UTF8.GetByteCount(password));

        return crypto;
    }
Ejemplo n.º 6
0
 /// <summary>
 /// Initialize the cipher.
 /// </summary>
 /// <param name="key"></param>
 public Cipher(String key)
 {
     using (SHA256Managed SHA = new SHA256Managed())
     {
         AES = new RijndaelManaged();
         AES.Key = SHA.ComputeHash(Encoding.ASCII.GetBytes(key));
         AES.IV = new Byte[16];
     }
 }
Ejemplo n.º 7
0
 // original, samo copy-paste
 public static string SHA256(string input)
 {
     SHA256 sha256 = new SHA256Managed();
     byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
     byte[] hash = sha256.ComputeHash(inputBytes);
     StringBuilder sb = new StringBuilder();
     for (int i = 0; i < hash.Length; i++)
         sb.Append(hash[i].ToString("X2"));
     return sb.ToString();
 }
Ejemplo n.º 8
0
    public static string EncryptText(string input)
    {
        // Get the bytes of the string
        SHA256 sha256 = new SHA256Managed();
        byte[] b = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));

        string result = BitConverter.ToString(b);

        return result;
    }
Ejemplo n.º 9
0
 public static string Encrypt(string input)
 {
     SHA256Managed cypher = new SHA256Managed();
     string hash = "";
     byte[] crypto = cypher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(input), 0, System.Text.Encoding.UTF8.GetByteCount(input));
     foreach (byte a in crypto)
     {
         hash += a.ToString("x2");
     }
     return hash;
 }
Ejemplo n.º 10
0
 public static string KriptirajMe(string txt)
 {
     //Ugrađena .NET biblioteka za kriptiranje
     SHA256Managed sha = new SHA256Managed();
     //Pretvorimo text u niz bajtova da bi kriptirali
     byte[] poljeBajtova = Encoding.UTF8.GetBytes(txt);
     //Idemoooo
     byte[] poljeRezultata = sha.ComputeHash(poljeBajtova);
     // Vrati rez kao string
     return Convert.ToBase64String(poljeRezultata);
 }
Ejemplo n.º 11
0
 protected string hashMe(string ulazni)
 {
     //kreiraj objekt koji će hashitrat sa SHA256
     SHA256Managed algoritam = new SHA256Managed();
     //prebaci string u polje bajtova
     byte[] poljeBajtova = System.Text.Encoding.ASCII.GetBytes(ulazni);
     //hashiraj polje bajtova
     byte[] rezultatHashiranja = algoritam.ComputeHash(poljeBajtova);
     //vrati nazad u base64 string(samo slova i brojevi...)
     return Convert.ToBase64String(rezultatHashiranja);
 }
Ejemplo n.º 12
0
 public static string hash(string tekst)
 {
     //SHA hashing algorithm
     SHA256Managed algoritam = new SHA256Managed();
     //Get bytes from string
     byte[] bytes = System.Text.Encoding.UTF8.GetBytes(tekst);
     //Execute hashing
     byte[] resultBytes = algoritam.ComputeHash(bytes);
     //return as string
     return Convert.ToBase64String(resultBytes);
 }
Ejemplo n.º 13
0
		SHA256Managed (SHA256Managed other)
		{
			count = other.count;
			_H = new uint [other._H.Length];
			Array.Copy (other._H, _H, _H.Length);
			_ProcessingBufferCount = other._ProcessingBufferCount;
			_ProcessingBuffer = new byte [other._ProcessingBuffer.Length];
			Array.Copy (other._ProcessingBuffer, _ProcessingBuffer, _ProcessingBuffer.Length);
			buff = new uint [other.buff.Length];
			Array.Copy (other.buff, buff, buff.Length);
		}
 /**
    * This function calculates the Sha 256 of the text
    * passed to it.
    **/
 public static string getHashSha256(string text)
 {
     byte[] bytes = Encoding.UTF8.GetBytes(text);
       SHA256Managed hashstring = new SHA256Managed();
       byte[] hash = hashstring.ComputeHash(bytes);
       string hashString = string.Empty;
       foreach (byte x in hash)
       {
      hashString += String.Format("{0:x2}", x);
       }
       return hashString;
 }
Ejemplo n.º 15
0
    static void _Main(string[] args)
    {
        // Get path+filename of this executable (i.e. argv[0])
        string argv0 = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);

        // Check args
        if (args.Length < 2) {
            Console.WriteLine("Usage: pin label [count [wait-in-milliseconds]]\r\nSign this executable ({0}).", argv0);
            return;
        }

        // Parse optional args
        int count, wait;
        if (args.Length < 3 || !int.TryParse(args[2], out count))
            count = 1;
        if (args.Length < 4 || !int.TryParse(args[3], out  wait))
            wait  = 10000;

        // Create a SHA-256 hash of this executable
        byte[] buf  = File.ReadAllBytes(argv0);
        #if MANAGED
        SHA256Managed sha256 = new SHA256Managed();
        byte[] hash = sha256.ComputeHash(buf, 0, buf.Length);
        #else
        byte[] ctx  = new byte[104]; // 104 => sizeof(sha256_ctx)
        byte[] hash = new byte[ 32]; //  32 => 256-bit sha256
        sha256_starts(ctx);
        sha256_update(ctx, buf, (uint)buf.Length);
        sha256_finish(ctx, hash);
        #endif

        // Sign the hash of this executable n times, where n = count
        try {
            for (int i = 0; i < count; i++) {
                if (i > 0 && count > 1) {
                    Console.WriteLine("wait {0} milliseconds for next signature", wait);
                    Thread.Sleep(wait);
                }
                IntPtr pCms;
                long start = Environment.TickCount;
                int  len   = sign_hash(args[0], args[1], hash, hash.Length, out pCms);
                long end   = Environment.TickCount;
                Console.WriteLine("sign_hash returned: {0}, time used: {1} ms", len, end - start);
                if (len > 0) {
                    byte[] cms = new byte[len];
                    Marshal.Copy(pCms, cms, 0, cms.Length);
                    File.WriteAllBytes(argv0 + ".p7s", cms);
                }
            }
        } finally {
            release_template();
        }
    }
Ejemplo n.º 16
0
    public static string hashHash(string pojam)
    {
        //Racunam dajte mi string da ga hashiram
        SHA256Managed sha = new SHA256Managed();
        //Treba mi polje bajtova za hashiranje
        byte[] poljeBajtova = Encoding.UTF8.GetBytes(pojam);
        //sad možemo hashirati
        byte[] rezultat = sha.ComputeHash(poljeBajtova);

        //vrati nazad kao string
        return Convert.ToBase64String(rezultat);
    }
Ejemplo n.º 17
0
    /// <summary>
    /// Generate the SHA256 hash from a passed string value
    /// </summary>
    public static string ComputeHash(string stringValue)
    {
        SHA256Managed shaM = new SHA256Managed();

        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
        string correctPasswordHash = BitConverter.ToString(shaM.ComputeHash(enc.GetBytes(stringValue)));

        // hash value cleanup
        correctPasswordHash = correctPasswordHash.Replace("-", string.Empty).ToLower();

        return correctPasswordHash;
    }
Ejemplo n.º 18
0
 private static byte[] GetBytes(byte[] password, byte[] salt, int iterations, int howManyBytes)
 {
     // round up
     uint cBlocks = (uint)((howManyBytes + HASH_SIZE_IN_BYTES - 1) / HASH_SIZE_IN_BYTES);
     // seed for the pseudo-random fcn: salt + block index
     byte[] saltAndIndex = new byte[salt.Length + 4];
     Array.Copy(salt, 0, saltAndIndex, 0, salt.Length);
     byte[] output = new byte[cBlocks * HASH_SIZE_IN_BYTES];
     int outputOffset = 0;
     SHA256Managed innerHash = new SHA256Managed();
     SHA256Managed outerHash = new SHA256Managed();
     // HMAC says the key must be hashed or padded with zeros
     // so it fits into a single block of the hash in use
     if (password.Length > BLOCK_SIZE_IN_BYTES)
     {
         password = innerHash.ComputeHash(password);
     }
     byte[] key = new byte[BLOCK_SIZE_IN_BYTES];
     Array.Copy(password, 0, key, 0, password.Length);
     byte[] InnerKey = new byte[BLOCK_SIZE_IN_BYTES];
     byte[] OuterKey = new byte[BLOCK_SIZE_IN_BYTES];
     for (int i = 0; i < BLOCK_SIZE_IN_BYTES; ++i)
     {
         InnerKey[i] = (byte)(key[i] ^ IPAD);
         OuterKey[i] = (byte)(key[i] ^ OPAD);
     }
     // for each block of desired output
     for (int iBlock = 0; iBlock < cBlocks; ++iBlock)
     {
         // seed HMAC with salt & block index
         _incrementBigEndianIndex(saltAndIndex, salt.Length);
         byte[] U = saltAndIndex;
         for (int i = 0; i < iterations; ++i)
         {
             // simple implementation of HMAC-SHA-256
             innerHash.Initialize();
             innerHash.TransformBlock(InnerKey, 0, BLOCK_SIZE_IN_BYTES, InnerKey, 0);
             innerHash.TransformFinalBlock(U, 0, U.Length);
             byte[] temp = innerHash.Hash; outerHash.Initialize();
             outerHash.TransformBlock(OuterKey, 0, BLOCK_SIZE_IN_BYTES, OuterKey, 0);
             outerHash.TransformFinalBlock(temp, 0, temp.Length);
             U = outerHash.Hash;
             // U = result of HMAC
             // xor result into output buffer
             _xorByteArray(U, 0, HASH_SIZE_IN_BYTES, output, outputOffset);
         }
         outputOffset += HASH_SIZE_IN_BYTES;
     }
     byte[] result = new byte[howManyBytes];
     Array.Copy(output, 0, result, 0, howManyBytes);
     return result;
 }
Ejemplo n.º 19
0
    protected void Button_Login_Click(object sender, EventArgs e)
    {
        var salt = "";
        string kode = "";
        SqlConnection conn = new SqlConnection(MyConnectionString.ConnectionString); // MyConnectionString.ConnectionString er fra en class som gør det lettere og skrive sin connectionstring.
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn; // Standard connection til din database.

        cmd.CommandText = @"
            SELECT bruger_id, bruger_navn, bruger_email, bruger_password, bruger_salt, rolle_adgang
            FROM bruger INNER JOIN rolle ON rolle_id = fk_rolle_id
            WHERE
                bruger_email = @bruger_email"; // Din CommandText hvor du fortæller hvad den skal loade fra db.
        cmd.Parameters.AddWithValue("@bruger_email", TextBox_Email.Text);

        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader.Read())
        {
            salt = reader["bruger_salt"].ToString(); // Henter salt fra db. Salt bruges til når man skal krypterer koden så sætter man salt bag ved koden og så kryptere man koden.
            // Så hvis der er 2 der har koden 123, så er deres kode ikke ens efter den er krypteret.
            kode = reader["bruger_password"].ToString(); // Henter password fra db så vi kan se om koden er ens.
            var password = TextBox_Password.Text; // Tager koden som er indtastet i texboxen.
            UTF8Encoding encoder = new UTF8Encoding(); // Gør klar så vi encoder koden om til UTF8.
            SHA256Managed sha256hasher = new SHA256Managed(); // Gør klar til at lave kryptering.
            byte[] hashedDataBytes = sha256hasher.ComputeHash(encoder.GetBytes(password + salt)); // Her sætter vi koden (textboxen) og salted (fra db) og laver det til bytes efter, da ComputeHash kun kan bruge bytes.
            StringBuilder hash = new StringBuilder(""); // Laver en string builder så vi kan samle alle bytes til en string.
            for (int i = 0; i < hashedDataBytes.Length; i++) // For hver bytes
                hash.Append(hashedDataBytes[i].ToString("X2")); // Her laver vi bytesne om til Hexadecimal.
            if (hash.ToString() == kode) // Nu tjekker vi om de koder er ens. Vi blev nød til at kryptere koden (fra texboxen) da koden fra db er kryptere og vi ikke kan dekryptere koden.
            {
                Session["bruger_id"] = reader["bruger_id"]; // Hvis koden er ens laver vi en masse sessions, så vi kan bruge dem hvis vi får brug for dem.
                Session["bruger_navn"] = reader["bruger_navn"];
                Session["bruger_email"] = reader["bruger_email"];
                Session["rolle_adgang"] = reader["rolle_adgang"];
                Session.Remove("besked");

                Response.Redirect(ResolveClientUrl("~/Admin/Default.aspx"));
            }
            else // Hvis koden ikke er ens.
            {
                Label_Errors.Text = "Forkert Email eller Password";
                Label_Errors.Visible = true;
            }
        }
        else // Hvis emailen ikke er findes. Af sikkerheds mæssige grunde fortæller vi ikke at det er emailen som er forkert.
        {
            Label_Errors.Text = "Forkert Email eller Password";
            Label_Errors.Visible = true;
        }
        conn.Close();
    }
Ejemplo n.º 20
0
    public static string hashSHA256(string unhashedValue)
    {
        SHA256Managed shaM = new SHA256Managed();
        byte[] hash =
         shaM.ComputeHash(Encoding.ASCII.GetBytes(unhashedValue));

        StringBuilder stringBuilder = new StringBuilder();
        foreach (byte b in hash)
        {
            stringBuilder.AppendFormat("{0:x1}", b);
        }
        return stringBuilder.ToString();
    }
Ejemplo n.º 21
0
    //Function to convert password string into a SHA256 Hexadecimal Hash
    public static string GetSha256FromString(string strData)
    {
        var message = Encoding.ASCII.GetBytes(strData);
            SHA256Managed hashString = new SHA256Managed();
            string hex = "";

            var hashValue = hashString.ComputeHash(message);
            foreach (byte x in hashValue)
            {
                hex += String.Format("{0:x2}", x);
            }
            return hex;
    }
Ejemplo n.º 22
0
    public string hashiraj(string ulaz)
    {
        //Dohvati algoritam za hashiranje, neka bude SHA256

        SHA256 algoritam = new SHA256Managed();

        // pretvori ulazni string u niz byte-ova koji će se kodirati
        byte[] ulazBajtovi = System.Text.Encoding.ASCII.GetBytes(ulaz);
        //kodiraj i preimi novi niz byte-ova koji sadrže hashiran niz
        byte[] izlazBajtovi = algoritam.ComputeHash(ulazBajtovi);
        //pretvori ponovo u string i vrati rezultat
        return Convert.ToBase64String(izlazBajtovi);
    }
    public static void Main(String[] args)
    {
        //calculate caninicalized xml

        var t = new XmlDsigEnvelopedSignatureTransform(false);
        XmlDocument doc = new XmlDocument();
        //doc.PreserveWhitespace = true;
        doc.Load(@"c:\temp\x.xml");
        t.LoadInput(doc);

        FieldInfo field = t.GetType().GetField("_signaturePosition",
                         BindingFlags.NonPublic |
                         BindingFlags.Instance);

        field.SetValue(t, 1);

        var res = (XmlDocument)t.GetOutput();
        var s = res.OuterXml;

        var c14 = new XmlDsigC14NTransform();
        c14.LoadInput(res);
        var mem = (MemoryStream)c14.GetOutput();

        var sha = new SHA256Managed();

        var byte1 = c14.GetDigestedOutput(new SHA256Managed());
        var digest1 = Convert.ToBase64String(byte1);
        var byte2 = sha.ComputeHash(mem.ToArray());
        var digest2 = Convert.ToBase64String(byte2);

        var s1 = System.Text.Encoding.UTF8.GetString(mem.ToArray());
        var byte3 = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(s1));
        var digest3 = Convert.ToBase64String(byte3);

        //return;

        //validate signature

        CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(@"c:\temp\x.xml");
        XmlNode node = xmlDoc.DocumentElement;
        X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(@"c:\temp\x.cer"));
        bool isValid = ValidateXml(xmlDoc, cert);
        //return;

        //calc hash
        var sha1 = new SHA256Managed();
        var b1 = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(@"c:\temp\x_no_sig.xml")));
        var b64 = Convert.ToBase64String(b1);
    }
Ejemplo n.º 24
0
        public HMACSHA256 (byte[] key) {
            m_hashName = "SHA256";

#if FEATURE_CRYPTO
            m_hash1 = GetHashAlgorithmWithFipsFallback(() => new SHA256Managed(), () => HashAlgorithm.Create("System.Security.Cryptography.SHA256CryptoServiceProvider"));
            m_hash2 = GetHashAlgorithmWithFipsFallback(() => new SHA256Managed(), () => HashAlgorithm.Create("System.Security.Cryptography.SHA256CryptoServiceProvider"));
#else
            m_hash1 = new SHA256Managed();
            m_hash2 = new SHA256Managed();
#endif // FEATURE_CRYPTO

            HashSizeValue = 256;
            base.InitializeKey(key);
        }
Ejemplo n.º 25
0
 public static string hashFile(string filePath)
 {
     using (var c = new SHA256Managed()) {
         using (var f = new FileStream(filePath, FileMode.Open))
         {
             byte[] hash = c.ComputeHash(f);
             StringBuilder sb = new StringBuilder();
             foreach (byte b in hash) {
                 sb.Append(b.ToString("x2"));
             }
             return sb.ToString();
         }
     }
 }
    /*
         *pHash - is the Hash Returned from the Credit Service.  You need to URLDecode the value before passing it in.
         *pSecretValue - the secret key issued when you registered at the Credit Gateway
         *pAppId - the appid issued to you when you registered at the credit gateway
         *pTransId - the transaction id your system issues to identify the purchase
         *pTransAmount - the value you are charging for this transaction
         *pAppStatus - The status of the credit transaction. Values : A = Accepted, D = Denied
         */
    public static bool VerifyServerResponseHash(String pHash, String pSecretValue, String pAppId, String pTransId, String pTransAmount, String pAppStatus)
    {
        String secretPartA = pSecretValue.Substring(0, 5);
            String secretPartB = pSecretValue.Substring(5, 5);
            String val = secretPartA + "-" + pAppId + "-" + pTransId + "-" + pTransAmount + "-" + pAppStatus + "-" + secretPartB;
            var pwdBytes = Encoding.UTF8.GetBytes(val);

            SHA256 hashAlg = new SHA256Managed();
            hashAlg.Initialize();
            var hashedBytes = hashAlg.ComputeHash(pwdBytes);
            var hash = Convert.ToBase64String(hashedBytes);

            if (hash == pHash)
                return true;
            else
                return false;
    }
Ejemplo n.º 27
0
    static Boolean Test()
    {
        Boolean bRes = true;
        Byte[] abData1 = { (Byte)'a', (Byte)'b', (Byte)'c' };
        Byte[] abDigest1 = {0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,
        					0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
        					0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
        					0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad};
        String sData2 = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
        Byte[] abData2 = new Byte[sData2.Length];
        for (int i=0; i<sData2.Length; i++) abData2[i] = (Byte)sData2[i];
        Byte[] abDigest2 = {0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,
        					0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,
        					0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,
        					0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1};

        Console.WriteLine("Testing SHA1 hash...");
        SHA256Managed   sha1 = new SHA256Managed();
        SHA256Managed   sha2 = new SHA256Managed();
        sha1.ComputeHash(abData1);
        sha2.ComputeHash(abData2);
        Console.WriteLine("The computed hash #1 is : ");
        PrintByteArray(sha1.Hash);
        Console.WriteLine("The correct hash #1 is : ");
        PrintByteArray(abDigest1);
        if(Compare(sha1.Hash, abDigest1)) {
            Console.WriteLine("CORRECT");
        } else {
            Console.WriteLine("INCORRECT");
            bRes = false;
        }
        Console.WriteLine("The computed hash #2 is : ");
        PrintByteArray(sha2.Hash);
        Console.WriteLine("The correct hash #2 is : ");
        PrintByteArray(abDigest2);
        if(Compare(sha2.Hash, abDigest2)) {
            Console.WriteLine("CORRECT");
        } else {
            Console.WriteLine("INCORRECT");
            bRes = false;
        }
        
        return bRes;
    }
 string Decrypt(string coded, string key)
 {
     RijndaelManaged cryptProvider = new RijndaelManaged();
     cryptProvider.KeySize = 256;
     cryptProvider.BlockSize = 256;
     cryptProvider.Mode = CipherMode.CBC;
     SHA256Managed hashSHA256 = new SHA256Managed();
     cryptProvider.Key = hashSHA256.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
     string iv = "user";
     cryptProvider.IV = hashSHA256.ComputeHash(ASCIIEncoding.ASCII.GetBytes(iv));
     byte[] cipherTextByteArray = Convert.FromBase64String(coded);
     MemoryStream ms = new MemoryStream();
     CryptoStream cs = new CryptoStream(ms, cryptProvider.CreateDecryptor(), CryptoStreamMode.Write);
     cs.Write(cipherTextByteArray, 0, cipherTextByteArray.Length);
     cs.FlushFinalBlock();
     cs.Close();
     byte[] byt = ms.ToArray();
     return Encoding.ASCII.GetString(byt);
 }
Ejemplo n.º 29
0
    /// <summary>
    /// Tjekker om man har indtastet al infomation og tilføjer en bruger.
    /// </summary>
    protected void Button_Save_Click(object sender, EventArgs e)
    {
        var fejl = false;

        if (TextBox_Name.Text == "") // Hvis TexBoxen er tom.
        {
            fejl = true; // Fortæller en der er sket en fejl så den ikke prøve og tilføje brugeren.
            eName.Attributes.Add("class", "form-group has-error"); // Gør TexBoxen rød så man kan se at det er den der er problemet.
        }

        if (TextBox_Email.Text == "") // Hvis TexBoxen er tom.
        {
            fejl = true; // Fortæller en der er sket en fejl så den ikke prøve og tilføje brugeren.
            eEmail.Attributes.Add("class", "form-group has-error");// Gør TexBoxen rød så man kan se at det er den der er problemet.
        }
        if (!fejl) // Hvis der ikke sker en fejl så skal den udfører dette.
        {
            var salt = Guid.NewGuid().ToString(); // Opretter et salt som er unique som bruges til at tilføje efter koden.
            var password = TextBox_Password.Text; // Tager koden som er indtastet i texboxen.
            UTF8Encoding encoder = new UTF8Encoding(); // Gør klar så vi encoder koden om til UTF8.
            SHA256Managed sha256hasher = new SHA256Managed(); // Gør klar til at lave kryptering.
            byte[] hashedDataBytes = sha256hasher.ComputeHash(encoder.GetBytes(password + salt));  // Her sætter vi koden (textboxen) og salted (fra db) og laver det til bytes efter, da ComputeHash kun kan bruge bytes.
            StringBuilder hash = new StringBuilder(""); // Laver en string builder så vi kan samle alle bytes til en string.
            for (int i = 0; i < hashedDataBytes.Length; i++) // For hver bytes
                hash.Append(hashedDataBytes[i].ToString("X2")); // Her laver vi bytesne om til Hexadecimal.

            var cmd = new SqlCommand();
            var conn = new SqlConnection(MyConnectionString.ConnectionString); // MyConnectionString.ConnectionString er fra en class som gør det lettere og skrive sin connectionstring.
            cmd.Connection = conn; // Standard connection til din database.
            cmd.CommandText = cmd.CommandText = "INSERT INTO bruger (bruger_navn, bruger_email, bruger_password, bruger_salt, fk_rolle_id, bruger_dato) VALUES (@1, @2, @3, @4, @5, @6)"; // Din CommandText hvor du fortæller hvad den skal loade fra db.
            cmd.Parameters.AddWithValue("@1", TextBox_Name.Text); // Dit parameter som laver sikkerhed for sql injection.
            cmd.Parameters.AddWithValue("@2", TextBox_Email.Text);
            cmd.Parameters.AddWithValue("@3", hash.ToString());
            cmd.Parameters.AddWithValue("@4", salt);
            cmd.Parameters.AddWithValue("@5", DropDownList_Role.SelectedValue);
            cmd.Parameters.AddWithValue("@6", DateTime.Now);
            conn.Open(); // Åbner din connection så så du kan Execute og få din data ud.
            cmd.ExecuteNonQuery(); // Gør hvad du fortæller den skal gøre som står i din CommandText.
            conn.Close(); // Lukker din connection så den ved at du ikke skal bruge mere data.
            Response.Redirect("OprerBruger.aspx"); // Sender personen til siden igen så der ikke er daten som lige er blevet sendt.
        }
    }
    /*
         *pSecretValue - the secret key issued when you registered at the Credit Gateway
         *pAppId - the appid issued to you when you registered at the credit gateway
         *pTransId - the transaction id your system issues to identify the purchase
         *pTransAmount - the value you are charging for this transaction
         */
    public static String GenerateClientRequestHash(String pSecretValue, String pAppId, String pTransId, String pTransAmount)
    {
        try
            {
                String secretPartA = pSecretValue.Substring(0, 5);
                String secretPartB = pSecretValue.Substring(5, 5);
                String val = secretPartA + "-" + pAppId + "-" + pTransId + "-" + pTransAmount + "-" + secretPartB;
                var pwdBytes = Encoding.UTF8.GetBytes(val);

                SHA256 hashAlg = new SHA256Managed();
                hashAlg.Initialize();
                var hashedBytes = hashAlg.ComputeHash(pwdBytes);
                var hash = Convert.ToBase64String(hashedBytes);
                return hash;
            }
            catch (Exception)
            {
                return null;
            }
    }
Ejemplo n.º 31
0
        public static unsafe void Save(string path)
        {
            string idx = Path.Combine(path, "texidx.mul");
            string mul = Path.Combine(path, "texmaps.mul");

            _checkSums = new List <Checksums>();

            using (var fsidx = new FileStream(idx, FileMode.Create, FileAccess.Write, FileShare.Write))
                using (var fsmul = new FileStream(mul, FileMode.Create, FileAccess.Write, FileShare.Write))
                {
                    var memidx = new MemoryStream();
                    var memmul = new MemoryStream();
                    using (BinaryWriter binidx = new BinaryWriter(memidx), binmul = new BinaryWriter(memmul))
                    {
                        var sha = new SHA256Managed();
                        //StreamWriter Tex = new StreamWriter(new FileStream("d:/texlog.txt", FileMode.Create, FileAccess.ReadWrite));
                        for (int index = 0; index < GetIdxLength(); ++index)
                        {
                            if (_cache[index] == null)
                            {
                                _cache[index] = GetTexture(index);
                            }

                            Bitmap bmp = _cache[index];
                            if ((bmp == null) || (_removed[index]))
                            {
                                binidx.Write(-1); // lookup
                                binidx.Write(0);  // length
                                binidx.Write(-1); // extra
                            }
                            else
                            {
                                var ms = new MemoryStream();
                                bmp.Save(ms, ImageFormat.Bmp);
                                byte[] checksum = sha.ComputeHash(ms.ToArray());

                                if (compareSaveImages(checksum, out Checksums sum))
                                {
                                    binidx.Write(sum.pos); //lookup
                                    binidx.Write(sum.length);
                                    binidx.Write(0);
                                    //Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, (int)sum.pos, (int)sum.length));
                                    //Tex.WriteLine(System.String.Format("0x{0:X4} -> 0x{1:X4}", sum.index, index));
                                    continue;
                                }

                                BitmapData bd = bmp.LockBits(
                                    new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly,
                                    PixelFormat.Format16bppArgb1555);
                                var line  = (ushort *)bd.Scan0;
                                int delta = bd.Stride >> 1;

                                binidx.Write((int)binmul.BaseStream.Position); //lookup
                                var length = (int)binmul.BaseStream.Position;

                                for (int y = 0; y < bmp.Height; ++y, line += delta)
                                {
                                    ushort *cur = line;
                                    for (int x = 0; x < bmp.Width; ++x)
                                    {
                                        binmul.Write((ushort)(cur[x] ^ 0x8000));
                                    }
                                }

                                int start = length;
                                length = (int)binmul.BaseStream.Position - length;
                                binidx.Write(length);
                                binidx.Write((bmp.Width == 64 ? 0 : 1));
                                bmp.UnlockBits(bd);
                                var s = new Checksums {
                                    pos = start, length = length, checksum = checksum, index = index
                                };
                                //Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, start, length));
                                _checkSums.Add(s);
                            }
                        }

                        memidx.WriteTo(fsidx);
                        memmul.WriteTo(fsmul);
                    }
                }
        }
Ejemplo n.º 32
0
        public static string cashAddrToOldAddr(string cashAddr, out bool isP2PKH, out bool mainnet)
        {
            cashAddr = cashAddr.ToLower();
            if (cashAddr.Length != 54 && cashAddr.Length != 42 && cashAddr.Length != 50)
            {
                if (cashAddr.StartsWith("bchreg:"))
                {
                    throw new CashAddrConversionException("Decoding RegTest addresses is not implemented.");
                }
                throw new CashAddrConversionException("Address to be decoded is longer or shorter than expected.");
            }
            int afterPrefix;

            if (cashAddr.StartsWith("bitcoincash:"))
            {
                mainnet     = true;
                afterPrefix = 12;
            }
            else if (cashAddr.StartsWith("bchtest:"))
            {
                mainnet     = false;
                afterPrefix = 8;
            }
            else if (cashAddr.StartsWith("bchreg:"))
            {
                throw new CashAddrConversionException("Decoding RegTest addresses is not implemented.");
            }
            else
            {
                if (cashAddr.IndexOf(":") == -1)
                {
                    mainnet     = true;
                    afterPrefix = 0;
                }
                else
                {
                    throw new CashAddrConversionException("Unexpected colon character.");
                }
            }
            int max = afterPrefix + 42;

            if (max != cashAddr.Length)
            {
                throw new CashAddrConversionException("Address to be decoded is longer or shorter than expected.");
            }
            byte[] decodedBytes = new byte[42];
            for (int i = afterPrefix; i < max; i++)
            {
                int value = DICT_CASHADDR[cashAddr[i]];
                if (value != -1)
                {
                    decodedBytes[i - afterPrefix] = (byte)value;
                }
                else
                {
                    throw new CashAddrConversionException("Address contains unexpected character.");
                }
            }
            if (PolyMod(decodedBytes, (ulong)(mainnet ? 1058337025301 : 584719417569)) != 0)
            {
                throw new CashAddrConversionException("Address checksum doesn't match. Have you made a mistake while typing it?");
            }
            decodedBytes = convertBitsFiveToEight(decodedBytes);
            switch (decodedBytes[0])
            {
            case 0x00:
                isP2PKH = true;
                break;

            case 0x08:
                isP2PKH = false;
                break;

            default:
                throw new CashAddrConversionException("Unexpected address byte.");
            }
            if (mainnet && isP2PKH)
            {
                decodedBytes[0] = 0x00;
            }
            else if (mainnet && !isP2PKH)
            {
                decodedBytes[0] = 0x05;
            }
            else if (!mainnet && isP2PKH)
            {
                decodedBytes[0] = 0x6f;
            }
            else
            {
                // Warning! Bigger than 0x80.
                decodedBytes[0] = 0xc4;
            }
            SHA256 hasher = SHA256Managed.Create();

            byte[] checksum = hasher.ComputeHash(hasher.ComputeHash(decodedBytes, 0, 21));
            decodedBytes[21] = checksum[0];
            decodedBytes[22] = checksum[1];
            decodedBytes[23] = checksum[2];
            decodedBytes[24] = checksum[3];
            System.Text.StringBuilder ret = new System.Text.StringBuilder(40);
            for (int numZeros = 0; numZeros < 25 && decodedBytes[numZeros] == 0; numZeros++)
            {
                ret.Append("1");
            }
            {
                var temp = new List <byte>(decodedBytes);
                // for 0xc4
                temp.Insert(0, 0);
                temp.Reverse();
                decodedBytes = temp.ToArray();
            }

            byte[]     retArr         = new byte[40];
            int        retIdx         = 0;
            BigInteger baseChanger    = BigInteger.Abs(new BigInteger(decodedBytes));
            BigInteger baseFiftyEight = new BigInteger(58);
            BigInteger modulo         = new BigInteger();

            while (!baseChanger.IsZero)
            {
                baseChanger      = BigInteger.DivRem(baseChanger, baseFiftyEight, out modulo);
                retArr[retIdx++] = (byte)modulo;
            }
            for (retIdx--; retIdx >= 0; retIdx--)
            {
                ret.Append(CHARSET_BASE58[retArr[retIdx]]);
            }
            return(ret.ToString());
        }
    public void WriteXMLDataToFile(string string_XMLFilePath)
    {
        FileStream fileStream_ServerDB = File.Create(string_XMLFilePath);

        MemoryStream memoryStream_XMLData          = new MemoryStream(),
                     memoryStream_EncryptedXMLData = new MemoryStream();

        SHA256Managed sHA256Managed_obj = new SHA256Managed();

        RijndaelManaged rijndaelManaged_obj = new RijndaelManaged();

        CryptoStream cryptoStream_obj = null;

        byte[] byteArray_ComputedXMLDataHash = new byte[32], byteArray_PasswordHash = new byte[32],
        byteArray_EncryptedData      = null, byteArray_CompressedXMLData,
        byteArray_HashOfPasswordHash = new byte[32];

        byte byte_ToEncryptServerDataBase = 0, byte_ToCompressSettingsDataBase = 0;

        ConnectingServiceDB.WriteXml(memoryStream_XMLData);


        if (CommonEnvironment.EncryptSettingsDataBase == true)
        {
            byte_ToEncryptServerDataBase = 1;
        }
        if (CommonEnvironment.CompressSettingsDataBase == true)
        {
            byte_ToCompressSettingsDataBase = 1;
        }


        if (CommonEnvironment.CompressSettingsDataBase == true)
        {
            YakSys.Compression.LZSS lZSS_obj = new YakSys.Compression.LZSS(16, true, true, false, 65536);

            byteArray_CompressedXMLData = lZSS_obj.Compress(memoryStream_XMLData.ToArray(), false);

            memoryStream_XMLData = new MemoryStream(byteArray_CompressedXMLData);
        }

        byteArray_ComputedXMLDataHash = sHA256Managed_obj.ComputeHash(memoryStream_XMLData);

        if (CommonEnvironment.LocalSecurityPassword.Length > 5 && CommonEnvironment.EncryptSettingsDataBase == true)
        {
            byteArray_PasswordHash       = sHA256Managed_obj.ComputeHash(System.Text.Encoding.Default.GetBytes(CommonEnvironment.LocalSecurityPassword));
            byteArray_HashOfPasswordHash = sHA256Managed_obj.ComputeHash(byteArray_PasswordHash);

            rijndaelManaged_obj.KeySize = 256;

            rijndaelManaged_obj.Key = byteArray_PasswordHash;
            rijndaelManaged_obj.IV  = new byte[rijndaelManaged_obj.BlockSize / 8];

            cryptoStream_obj = new CryptoStream(memoryStream_EncryptedXMLData, rijndaelManaged_obj.CreateEncryptor(), CryptoStreamMode.Write);

            cryptoStream_obj.Write(memoryStream_XMLData.ToArray(), 0, memoryStream_XMLData.ToArray().Length);

            memoryStream_XMLData.SetLength(0);

            cryptoStream_obj.FlushFinalBlock();

            byteArray_EncryptedData = memoryStream_EncryptedXMLData.ToArray();

            cryptoStream_obj.Close();

            memoryStream_XMLData = new MemoryStream(byteArray_EncryptedData);
        }

        fileStream_ServerDB.Write(System.Text.Encoding.Default.GetBytes("ConnectingServiceDB010"), 0, 22);

        fileStream_ServerDB.WriteByte(byte_ToEncryptServerDataBase);
        fileStream_ServerDB.WriteByte(byte_ToCompressSettingsDataBase);

        fileStream_ServerDB.Write(byteArray_ComputedXMLDataHash, 0, byteArray_ComputedXMLDataHash.Length);
        fileStream_ServerDB.Write(byteArray_HashOfPasswordHash, 0, byteArray_HashOfPasswordHash.Length);


        fileStream_ServerDB.Write(memoryStream_XMLData.ToArray(), 0, memoryStream_XMLData.ToArray().Length);

        fileStream_ServerDB.Close();
    }
Ejemplo n.º 34
0
 public ShaRandom()
 {
     sha = new SHA256Managed();
 }
Ejemplo n.º 35
0
        public static String ToSha256(this String input)
        {
            var sha = new SHA256Managed();

            return(BitConverter.ToString(sha.ComputeHash(Encoding.UTF8.GetBytes(input))).Replace("-", ""));
        }
Ejemplo n.º 36
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="TimeStampQuery"></param>
        /// <returns></returns>
        public OutputResponseMarca getTimeStamp(InputMarca TimeStampQuery)
        {
            OutputResponseMarca outputMarca = new OutputResponseMarca();


            byte[] dati = String_To_Bytes(TimeStampQuery.file_p7m);
            //SHA1 sha1 = SHA1CryptoServiceProvider.Create();
            //byte[] hash = sha1.ComputeHash(dati);

            SHA256Managed sha256 = new SHA256Managed();

            byte[] hash = sha256.ComputeHash(dati);

            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

            reqGen.SetCertReq(true);


            //Funzione randomica per il Nonce.
            //RandomNumberGenerator nRand = new RNGCryptoServiceProvider();
            long casuale = (long)nRandom.Next();
            //TimeStampRequest tsReq = reqGen.Generate(TspAlgorithms.Sha1, hash, BigInteger.ValueOf(casuale));
            TimeStampRequest tsReq = reqGen.Generate(TspAlgorithms.Sha256, hash, BigInteger.ValueOf(casuale));

            byte[] tsData = tsReq.GetEncoded();

            string urlTSA = string.Empty;

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["URL_TSA"]))
            {
                urlTSA = ConfigurationManager.AppSettings["URL_TSA"].ToString();
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urlTSA);
                req.Method      = "POST";
                req.ContentType = "application/timestamp-query";

                //Username e password per accedere alla Time Stamping Authority
                string pwd = string.Empty;
                if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["PASSWORD_UTENTE_TSA"]))
                {
                    pwd = ConfigurationManager.AppSettings["PASSWORD_UTENTE_TSA"].ToString();
                    req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(pwd)));
                }

                req.ContentLength = tsData.Length;

                Stream reqStream = req.GetRequestStream();
                reqStream.Write(tsData, 0, tsData.Length);
                reqStream.Close();

                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                if (res == null)
                {
                    outputMarca.esito             = "KO";
                    outputMarca.descrizioneErrore = "Impossibile contattare la TSA o autorizzazione negata";
                    return(outputMarca);
                }
                else
                {
                    Stream            resStream = new BufferedStream(res.GetResponseStream());
                    TimeStampResponse tsRes     = new TimeStampResponse(resStream);
                    resStream.Close();
                    BusinessLogic.Documenti.DigitalSignature.VerifyTimeStamp checkMarca = new BusinessLogic.Documenti.DigitalSignature.VerifyTimeStamp();
                    outputMarca = checkMarca.Verify(tsReq, tsRes);
                }
            }
            else
            {
                outputMarca.esito             = "KO";
                outputMarca.descrizioneErrore = "Impossibile contattare la TSA o url configurata errata!";
                return(outputMarca);
            }

            return(outputMarca);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// 计算SHA256哈希值
        /// </summary>
        /// <param name="buffer">要计算其哈希代码的数组。</param>
        /// <returns>返回SHA256哈希值</returns>
        public static string SHA256(byte[] buffer)
        {
            SHA256Managed sha256 = new SHA256Managed();

            return(ConvertToString(sha256.ComputeHash(buffer)));
        }
Ejemplo n.º 38
0
        /// <summary>
        ///     Saves mul
        /// </summary>
        /// <param name="path"></param>
        public static unsafe void Save(string path)
        {
            checksumsLand   = new List <CheckSums>();
            checksumsStatic = new List <CheckSums>();
            string idx = Path.Combine(path, "artidx.mul");
            string mul = Path.Combine(path, "art.mul");

            using (
                FileStream fsidx = new FileStream(idx, FileMode.Create, FileAccess.Write, FileShare.Write),
                fsmul = new FileStream(mul, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                MemoryStream  memidx = new MemoryStream();
                MemoryStream  memmul = new MemoryStream();
                SHA256Managed sha    = new SHA256Managed();
                //StreamWriter Tex = new StreamWriter(new FileStream("d:/artlog.txt", FileMode.Create, FileAccess.ReadWrite));

                using (BinaryWriter binidx = new BinaryWriter(memidx), binmul = new BinaryWriter(memmul))
                {
                    for (int index = 0; index < GetIdxLength(); index++)
                    {
                        Files.FireFileSaveEvent();
                        if (m_Cache[index] == null)
                        {
                            if (index < 0x4000)
                            {
                                m_Cache[index] = GetLand(index);
                            }
                            else
                            {
                                m_Cache[index] = GetStatic(index - 0x4000, false);
                            }
                        }
                        Bitmap bmp = m_Cache[index];
                        if ((bmp == null) || (m_Removed[index]))
                        {
                            binidx.Write(-1); // lookup
                            binidx.Write(0);  // length
                            binidx.Write(-1); // extra
                                              //Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, (int)-1, (int)-1));
                        }
                        else if (index < 0x4000)
                        {
                            MemoryStream ms = new MemoryStream();
                            bmp.Save(ms, ImageFormat.Bmp);
                            byte[]    checksum = sha.ComputeHash(ms.ToArray());
                            CheckSums sum;
                            if (compareSaveImagesLand(checksum, out sum))
                            {
                                binidx.Write(sum.pos); //lookup
                                binidx.Write(sum.length);
                                binidx.Write(0);
                                //Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, (int)sum.pos, (int)sum.length));
                                //Tex.WriteLine(System.String.Format("0x{0:X4} -> 0x{1:X4}", sum.index, index));
                                continue;
                            }
                            //land
                            BitmapData bd = bmp.LockBits(
                                new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, Settings.PixelFormat);
                            ushort *line  = (ushort *)bd.Scan0;
                            int     delta = bd.Stride >> 1;
                            binidx.Write((int)binmul.BaseStream.Position); //lookup
                            int length    = (int)binmul.BaseStream.Position;
                            int x         = 22;
                            int y         = 0;
                            int linewidth = 2;
                            for (int m = 0; m < 22; ++m, ++y, line += delta, linewidth += 2)
                            {
                                --x;
                                ushort *cur = line;
                                for (int n = 0; n < linewidth; ++n)
                                {
                                    binmul.Write((ushort)(cur[x + n] ^ 0x8000));
                                }
                            }
                            x         = 0;
                            linewidth = 44;
                            y         = 22;
                            line      = (ushort *)bd.Scan0;
                            line     += delta * 22;
                            for (int m = 0; m < 22; m++, y++, line += delta, ++x, linewidth -= 2)
                            {
                                ushort *cur = line;
                                for (int n = 0; n < linewidth; n++)
                                {
                                    binmul.Write((ushort)(cur[x + n] ^ 0x8000));
                                }
                            }
                            int start = length;
                            length = (int)binmul.BaseStream.Position - length;
                            binidx.Write(length);
                            binidx.Write(0);
                            bmp.UnlockBits(bd);
                            CheckSums s = new CheckSums
                            {
                                pos      = start,
                                length   = length,
                                checksum = checksum,
                                index    = index
                            };
                            //Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, start, length));
                            checksumsLand.Add(s);
                        }
                        else
                        {
                            MemoryStream ms = new MemoryStream();
                            bmp.Save(ms, ImageFormat.Bmp);
                            byte[]    checksum = sha.ComputeHash(ms.ToArray());
                            CheckSums sum;
                            if (compareSaveImagesStatic(checksum, out sum))
                            {
                                binidx.Write(sum.pos); //lookup
                                binidx.Write(sum.length);
                                binidx.Write(0);
                                //Tex.WriteLine(System.String.Format("0x{0:X4} -> 0x{1:X4}", sum.index, index));
                                //Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, sum.pos, sum.length));
                                continue;
                            }

                            // art
                            BitmapData bd = bmp.LockBits(
                                new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, Settings.PixelFormat);
                            ushort *line  = (ushort *)bd.Scan0;
                            int     delta = bd.Stride >> 1;
                            binidx.Write((int)binmul.BaseStream.Position); //lookup
                            int length = (int)binmul.BaseStream.Position;
                            binmul.Write(1234);                            // header
                            binmul.Write((short)bmp.Width);
                            binmul.Write((short)bmp.Height);
                            int lookup    = (int)binmul.BaseStream.Position;
                            int streamloc = lookup + bmp.Height * 2;
                            int width     = 0;
                            for (int i = 0; i < bmp.Height; ++i) // fill lookup
                            {
                                binmul.Write(width);
                            }
                            int X = 0;
                            for (int Y = 0; Y < bmp.Height; ++Y, line += delta)
                            {
                                ushort *cur = line;
                                width = (int)(binmul.BaseStream.Position - streamloc) / 2;
                                binmul.BaseStream.Seek(lookup + Y * 2, SeekOrigin.Begin);
                                binmul.Write(width);
                                binmul.BaseStream.Seek(streamloc + width * 2, SeekOrigin.Begin);
                                int i = 0;
                                int j = 0;
                                X = 0;
                                while (i < bmp.Width)
                                {
                                    i = X;
                                    for (i = X; i <= bmp.Width; ++i)
                                    {
                                        //first pixel set
                                        if (i < bmp.Width)
                                        {
                                            if (cur[i] != 0)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                    if (i < bmp.Width)
                                    {
                                        for (j = (i + 1); j < bmp.Width; ++j)
                                        {
                                            //next non set pixel
                                            if (cur[j] == 0)
                                            {
                                                break;
                                            }
                                        }
                                        binmul.Write((short)(i - X)); //xoffset
                                        binmul.Write((short)(j - i)); //run
                                        for (int p = i; p < j; ++p)
                                        {
                                            binmul.Write((ushort)(cur[p] ^ 0x8000));
                                        }
                                        X = j;
                                    }
                                }
                                binmul.Write((short)0); //xOffset
                                binmul.Write((short)0); //Run
                            }
                            int start = length;
                            length = (int)binmul.BaseStream.Position - length;
                            binidx.Write(length);
                            binidx.Write(0);
                            bmp.UnlockBits(bd);
                            CheckSums s = new CheckSums
                            {
                                pos      = start,
                                length   = length,
                                checksum = checksum,
                                index    = index
                            };
                            //Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, start, length));
                            checksumsStatic.Add(s);
                        }
                    }
                    memidx.WriteTo(fsidx);
                    memmul.WriteTo(fsmul);
                }
            }
        }
Ejemplo n.º 39
0
        public static Fingerprint EvaluateKeyToFingerprint(
            AgentTaskPluginExecutionContext context,
            string filePathRoot,
            IEnumerable <string> keySegments)
        {
            var sha256 = new SHA256Managed();

            string defaultWorkingDirectory = context.Variables.GetValueOrDefault(
                "system.defaultworkingdirectory" // Constants.Variables.System.DefaultWorkingDirectory
                )?.Value;

            var resolvedSegments = new List <string>();

            foreach (string keySegment in keySegments)
            {
                CheckKeySegment(keySegment);
            }

            foreach (string keySegment in keySegments)
            {
                if (IsPathyKeySegment(keySegment))
                {
                    context.Verbose($"Interpretting `{keySegment}` as a path.");

                    string[] pathRules    = keySegment.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray();
                    string[] includeRules = pathRules.Where(p => !p.StartsWith('!')).ToArray();

                    if (!includeRules.Any())
                    {
                        throw new ArgumentException("No include rules specified.");
                    }

                    var enumerations = new Dictionary <Enumeration, List <string> >();
                    foreach (string includeRule in includeRules)
                    {
                        string absoluteRootRule = MakePathCanonical(defaultWorkingDirectory, includeRule);
                        context.Verbose($"Expanded include rule is `{absoluteRootRule}`.");
                        Enumeration   enumeration = DetermineFileEnumerationFromGlob(absoluteRootRule);
                        List <string> globs;
                        if (!enumerations.TryGetValue(enumeration, out globs))
                        {
                            enumerations[enumeration] = globs = new List <string>();
                        }
                        globs.Add(absoluteRootRule);
                    }

                    string[] excludeRules         = pathRules.Where(p => p.StartsWith('!')).ToArray();
                    string[] absoluteExcludeRules = excludeRules.Select(excludeRule => {
                        excludeRule = excludeRule.Substring(1);
                        return(MakePathCanonical(defaultWorkingDirectory, excludeRule));
                    }).ToArray();

                    var fileHashes = new SortedDictionary <string, string>(StringComparer.Ordinal);

                    foreach (var kvp in enumerations)
                    {
                        Enumeration   enumerate            = kvp.Key;
                        List <string> absoluteIncludeGlobs = kvp.Value;
                        context.Verbose($"Enumerating starting at root `{enumerate.RootPath}` with pattern `{enumerate.Pattern}` and depth `{enumerate.Depth}`.");
                        IEnumerable <string> files  = Directory.EnumerateFiles(enumerate.RootPath, enumerate.Pattern, enumerate.Depth);
                        Func <string, bool>  filter = CreateFilter(context, absoluteIncludeGlobs, absoluteExcludeRules);
                        files = files.Where(f => filter(f)).Distinct();

                        foreach (string path in files)
                        {
                            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                byte[] hash = sha256.ComputeHash(fs);
                                // Path.GetRelativePath returns 'The relative path, or path if the paths don't share the same root.'
                                string displayPath = filePathRoot == null ? path : Path.GetRelativePath(filePathRoot, path);
                                fileHashes.Add(path, $"\nSHA256({displayPath})=[{fs.Length}]{hash.ToHex()}");
                            }
                        }
                    }

                    if (!fileHashes.Any())
                    {
                        throw new FileNotFoundException("No files found.");
                    }

                    var fileHashesBuilder = new StringBuilder();
                    foreach (string fileHashString in fileHashes.Values)
                    {
                        fileHashesBuilder.Append(fileHashString);
                    }

                    string wholeFileHashString = fileHashesBuilder.ToString();
                    string summary             = SummarizeString(wholeFileHashString);
                    context.Output($"File hashes summarized as `{summary}` from BASE64(SHA256(`{wholeFileHashString}`))");
                    resolvedSegments.Add(summary);
                }
                else
                {
                    context.Verbose($"Interpretting `{keySegment}` as a string.");
                    resolvedSegments.Add($"{keySegment}");
                }
            }

            return(new Fingerprint()
            {
                Segments = resolvedSegments.ToArray()
            });
        }
Ejemplo n.º 40
0
            /// <summary>
            /// Generates a hash for the given plain text value and returns a
            /// base64-encoded result. Before the hash is computed, a random salt
            /// is generated and appended to the plain text. This salt is stored at
            /// the end of the hash value, so it can be used later for hash
            /// verification.
            /// </summary>
            /// <param name="plainText">
            /// Plaintext value to be hashed. The function does not check whether
            /// this parameter is null.
            /// </param>
            /// <param name="hashAlgorithm">
            /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
            /// "SHA256", "SHA384", and "SHA512" (if any other value is specified
            /// MD5 hashing algorithm will be used). This value is case-insensitive.
            /// </param>
            /// <param name="saltBytes">
            /// Salt bytes. This parameter can be null, in which case a random salt
            /// value will be generated.
            /// </param>
            /// <returns>
            /// Hash value formatted as a base64-encoded string.
            /// </returns>
            public static string ComputeHash(string plainText,
                                             string hashAlgorithm,
                                             byte[] saltBytes)
            {
                // If salt is not specified, generate it on the fly.
                if (saltBytes == null)
                {
                    // Define min and max salt sizes.
                    int minSaltSize = 4;
                    int maxSaltSize = 8;

                    // Generate a random number for the size of the salt.
                    Random random   = new Random();
                    int    saltSize = random.Next(minSaltSize, maxSaltSize);

                    // Allocate a byte array, which will hold the salt.
                    saltBytes = new byte[saltSize];

                    // Initialize a random number generator.
                    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

                    // Fill the salt with cryptographically strong byte values.
                    rng.GetNonZeroBytes(saltBytes);
                }

                // Convert plain text into a byte array.
                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

                // Allocate array, which will hold plain text and salt.
                byte[] plainTextWithSaltBytes =
                    new byte[plainTextBytes.Length + saltBytes.Length];

                // Copy plain text bytes into resulting array.
                for (int i = 0; i < plainTextBytes.Length; i++)
                {
                    plainTextWithSaltBytes[i] = plainTextBytes[i];
                }

                // Append salt bytes to the resulting array.
                for (int i = 0; i < saltBytes.Length; i++)
                {
                    plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
                }

                // Because we support multiple hashing algorithms, we must define
                // hash object as a common (abstract) base class. We will specify the
                // actual hashing algorithm class later during object creation.
                HashAlgorithm hash;

                // Make sure hashing algorithm name is specified.
                if (hashAlgorithm == null)
                {
                    hashAlgorithm = "";
                }

                // Initialize appropriate hashing algorithm class.
                switch (hashAlgorithm.ToUpper())
                {
                case "SHA1":
                    hash = new SHA1Managed();
                    break;

                case "SHA256":
                    hash = new SHA256Managed();
                    break;

                case "SHA384":
                    hash = new SHA384Managed();
                    break;

                case "SHA512":
                    hash = new SHA512Managed();
                    break;

                default:
                    hash = new MD5CryptoServiceProvider();
                    break;
                }

                // Compute hash value of our plain text with appended salt.
                byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

                // Create array which will hold hash and original salt bytes.
                byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                                    saltBytes.Length];

                // Copy hash bytes into resulting array.
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    hashWithSaltBytes[i] = hashBytes[i];
                }

                // Append salt bytes to the result.
                for (int i = 0; i < saltBytes.Length; i++)
                {
                    hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
                }

                // Convert result into a base64-encoded string.
                string hashValue = Convert.ToBase64String(hashWithSaltBytes);

                // Return the result.
                return(hashValue);
            }
Ejemplo n.º 41
0
        public static Byte[] SHA256(IEnumerable <Byte> Bytes)
        {
            SHA256 sha = new SHA256Managed();

            return(sha.ComputeHash(Bytes.ToArray()));
        }
Ejemplo n.º 42
0
        public DriverSignatureCheckup(String SHA25632, String SHA25664, String NewSHA25632, String NewSHA25664, Boolean Is64Bit)
        {
            InitializeComponent();

            var sha32    = new SHA256Managed();
            var DLL32bit = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86) + "\\keppysynth\\keppysynth.dll", FileMode.OpenOrCreate, FileAccess.Read);

            byte[] checksum32     = sha32.ComputeHash(DLL32bit);
            String Driver32SHA256 = BitConverter.ToString(checksum32).Replace("-", String.Empty);
            String Driver64SHA256 = null;

            Driver32Current.Text  = Driver32SHA256;
            Driver32Expected.Text = SHA25632;

            if (Driver32SHA256 != SHA25632)
            {
                if (!object.Equals(SHA25664, NewSHA25664))
                {
                    Driver32Status.Image = KeppySynthConfigurator.Properties.Resources.erroriconupd;
                }
                else
                {
                    Driver32Status.Image = KeppySynthConfigurator.Properties.Resources.erroricon;
                }
                Is32BitMatch = false;
            }
            else
            {
                if (!object.Equals(SHA25664, NewSHA25664))
                {
                    Driver32Status.Image = KeppySynthConfigurator.Properties.Resources.successiconupd;
                }
                else
                {
                    Driver32Status.Image = KeppySynthConfigurator.Properties.Resources.successicon;
                }
                Is32BitMatch = true;
            }

            if (Environment.Is64BitOperatingSystem)
            {
                Functions.Wow64DisableWow64FsRedirection(ref WOW64Value);
                var    sha64      = new SHA256Managed();
                var    DLL64bit   = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\keppysynth\\keppysynth.dll", FileMode.OpenOrCreate, FileAccess.Read);
                byte[] checksum64 = sha64.ComputeHash(DLL64bit);
                Driver64SHA256 = BitConverter.ToString(checksum64).Replace("-", String.Empty);
                Functions.Wow64RevertWow64FsRedirection(WOW64Value);

                Driver64Current.Text  = Driver64SHA256;
                Driver64Expected.Text = SHA25664;

                if (Driver64SHA256 != SHA25664)
                {
                    if (!object.Equals(SHA25664, NewSHA25664))
                    {
                        Driver64Status.Image = KeppySynthConfigurator.Properties.Resources.erroriconupd;
                    }
                    else
                    {
                        Driver64Status.Image = KeppySynthConfigurator.Properties.Resources.erroricon;
                    }
                    Is64BitMatch = false;
                }
                else
                {
                    if (!object.Equals(SHA25664, NewSHA25664))
                    {
                        Driver64Status.Image = KeppySynthConfigurator.Properties.Resources.successiconupd;
                    }
                    else
                    {
                        Driver64Status.Image = KeppySynthConfigurator.Properties.Resources.successicon;
                    }
                    Is64BitMatch = true;
                }
            }

            String OriginalRelease   = "{0} not the original from GitHub. Click here to download the original release.";
            String LatestRelease     = "{0} not the original from GitHub.\nThere's also an update, click here to download the latest release.";
            String EverythingFine    = "Both drivers are the originals from GitHub. Everything's good, click OK to close the dialog.";
            String EverythingFineUpd = "Both drivers are the originals from GitHub, but newer versions are available.\nClick here to download the latest release.";

            if (!Is32BitMatch && !Is64BitMatch)
            {
                if (!object.Equals(SHA25632, NewSHA25632) || !object.Equals(SHA25664, NewSHA25664))
                {
                    BothDriverStatus.Text      = String.Format(LatestRelease, "Both drivers are");
                    BothDriverStatus.ForeColor = Color.DarkRed;
                    BothDriverStatus.Cursor    = Cursors.Hand;
                    BothDriverStatus.Font      = new Font(BothDriverStatus.Font.FontFamily, BothDriverStatus.Font.Size, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    IsNewVerAvailable          = true;
                }
                else
                {
                    BothDriverStatus.Text      = String.Format(OriginalRelease, "Both drivers are");
                    BothDriverStatus.ForeColor = Color.DarkRed;
                    BothDriverStatus.Cursor    = Cursors.Hand;
                    BothDriverStatus.Font      = new Font(BothDriverStatus.Font.FontFamily, BothDriverStatus.Font.Size, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                }
            }
            else if (!Is32BitMatch)
            {
                if (!object.Equals(SHA25632, NewSHA25632) || !object.Equals(SHA25664, NewSHA25664))
                {
                    BothDriverStatus.Text      = String.Format(LatestRelease, "The 32-bit driver is");
                    BothDriverStatus.ForeColor = Color.Peru;
                    BothDriverStatus.Cursor    = Cursors.Hand;
                    BothDriverStatus.Font      = new Font(BothDriverStatus.Font.FontFamily, BothDriverStatus.Font.Size, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    IsNewVerAvailable          = true;
                }
                else
                {
                    BothDriverStatus.Text      = String.Format(OriginalRelease, "The 32-bit driver is");
                    BothDriverStatus.ForeColor = Color.Peru;
                    BothDriverStatus.Cursor    = Cursors.Hand;
                    BothDriverStatus.Font      = new Font(BothDriverStatus.Font.FontFamily, BothDriverStatus.Font.Size, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                }
            }
            else if (!Is64BitMatch)
            {
                if (!object.Equals(SHA25632, NewSHA25632) || !object.Equals(SHA25664, NewSHA25664))
                {
                    BothDriverStatus.Text      = String.Format(LatestRelease, "The 64-bit driver is");
                    BothDriverStatus.ForeColor = Color.Peru;
                    BothDriverStatus.Cursor    = Cursors.Hand;
                    BothDriverStatus.Font      = new Font(BothDriverStatus.Font.FontFamily, BothDriverStatus.Font.Size, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    IsNewVerAvailable          = true;
                }
                else
                {
                    BothDriverStatus.Text      = String.Format(OriginalRelease, "The 64-bit driver is");
                    BothDriverStatus.ForeColor = Color.Peru;
                    BothDriverStatus.Cursor    = Cursors.Hand;
                    BothDriverStatus.Font      = new Font(BothDriverStatus.Font.FontFamily, BothDriverStatus.Font.Size, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                }
            }
            else
            {
                if (!object.Equals(Driver32SHA256, NewSHA25632) || !object.Equals(Driver64SHA256, NewSHA25664))
                {
                    BothDriverStatus.Text      = EverythingFineUpd;
                    BothDriverStatus.ForeColor = Color.Blue;
                    BothDriverStatus.Cursor    = Cursors.Hand;
                    BothDriverStatus.Font      = new Font(BothDriverStatus.Font.FontFamily, BothDriverStatus.Font.Size, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    IsNewVerAvailable          = true;
                }
                else
                {
                    BothDriverStatus.Text      = EverythingFine;
                    BothDriverStatus.ForeColor = Color.Green;
                    BothDriverStatus.Cursor    = Cursors.Arrow;
                    BothDriverStatus.Font      = new Font(BothDriverStatus.Font.FontFamily, BothDriverStatus.Font.Size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                }
            }
        }
        void TryRegister()
        {
            if (Globals.WaitingOnServer)
            {
                return;
            }

            if (Networking.Network.Connected)
            {
                if (FieldChecking.IsValidUsername(mUsernameTextbox.Text, Strings.Regex.username))
                {
                    if (mPasswordTextbox.Text == mPasswordTextbox2.Text)
                    {
                        if (FieldChecking.IsValidPassword(mPasswordTextbox.Text, Strings.Regex.password))
                        {
                            if (FieldChecking.IsWellformedEmailAddress(mEmailTextbox.Text, Strings.Regex.email))
                            {
                                Hide();

                                //Hash Password
                                using (var sha = new SHA256Managed())
                                {
                                    var hashedPass = BitConverter.ToString(
                                        sha.ComputeHash(Encoding.UTF8.GetBytes(mPasswordTextbox.Text.Trim()))
                                        )
                                                     .Replace("-", "");

                                    PacketSender.SendCreateAccount(
                                        mUsernameTextbox.Text, hashedPass, mEmailTextbox.Text
                                        );
                                }

                                Globals.WaitingOnServer = true;
                                mRegisterBtn.Disable();
                                ChatboxMsg.ClearMessages();
                            }
                            else
                            {
                                Interface.MsgboxErrors.Add(
                                    new KeyValuePair <string, string>("", Strings.Registration.emailinvalid)
                                    );
                            }
                        }
                        else
                        {
                            Interface.MsgboxErrors.Add(
                                new KeyValuePair <string, string>("", Strings.Errors.passwordinvalid)
                                );
                        }
                    }
                    else
                    {
                        Interface.MsgboxErrors.Add(
                            new KeyValuePair <string, string>("", Strings.Registration.passwordmatch)
                            );
                    }
                }
                else
                {
                    Interface.MsgboxErrors.Add(new KeyValuePair <string, string>("", Strings.Errors.usernameinvalid));
                }
            }
            else
            {
                Interface.MsgboxErrors.Add(new KeyValuePair <string, string>("", Strings.Errors.notconnected));
            }
        }
Ejemplo n.º 44
0
        public void SaveAttachmentsToDisk(bool rewriteExisting = false)
        {
            //string root = AppDomain.CurrentDomain.BaseDirectory + "\\Prilohy\\";
            //if (!System.IO.Directory.Exists(root))
            //    System.IO.Directory.CreateDirectory(root);


            //string dir = root + item.Id;
            //if (!System.IO.Directory.Exists(dir))
            //{
            //    System.IO.Directory.CreateDirectory(dir);
            //}
            var io = Lib.Init.PrilohaLocalCopy;

            int    count   = 0;
            string listing = "";

            if (this.Prilohy != null)
            {
                if (!System.IO.Directory.Exists(io.GetFullDir(this)))
                {
                    System.IO.Directory.CreateDirectory(io.GetFullDir(this));
                }

                foreach (var p in this.Prilohy)
                {
                    string attUrl = p.odkaz;
                    if (string.IsNullOrEmpty(attUrl))
                    {
                        continue;
                    }
                    count++;
                    string fullPath = io.GetFullPath(this, p);
                    listing = listing + string.Format("{0} : {1} \n", count, System.Net.WebUtility.UrlDecode(attUrl));
                    if (!System.IO.File.Exists(fullPath) || rewriteExisting)
                    {
                        try
                        {
                            using (Devmasters.Net.Web.URLContent url = new Devmasters.Net.Web.URLContent(attUrl))
                            {
                                url.Timeout = url.Timeout * 10;
                                byte[] data = url.GetBinary().Binary;
                                System.IO.File.WriteAllBytes(fullPath, data);
                                //p.LocalCopy = System.Text.UTF8Encoding.UTF8.GetBytes(io.GetRelativePath(item, p));
                            }
                        }
                        catch (Exception e)
                        {
                            HlidacStatu.Util.Consts.Logger.Error(attUrl, e);
                        }
                    }
                    if (p.hash == null)
                    {
                        using (FileStream filestream = new FileStream(fullPath, FileMode.Open))
                        {
                            using (SHA256 mySHA256 = SHA256Managed.Create())
                            {
                                filestream.Position = 0;
                                byte[] hashValue = mySHA256.ComputeHash(filestream);
                                p.hash = new Lib.XSD.tHash()
                                {
                                    algoritmus = "sha256",
                                    Value      = BitConverter.ToString(hashValue).Replace("-", String.Empty)
                                };
                            }
                        }
                    }

                    //System.IO.File.WriteAllText(dir + "\\" + "content.nfo", listing);
                }
            }
        }
Ejemplo n.º 45
0
        /// <summary>
        /// 计算SHA256哈希值
        /// </summary>
        /// <param name="buffer">要计算其哈希代码的数组。</param>
        /// <param name="offset">字节数组中的偏移量,从该位置开始使用数据。</param>
        /// <param name="count">数组中用作数据的字节数。</param>
        /// <returns>返回SHA256哈希值</returns>
        public static string SHA256(byte[] buffer, int offset, int count)
        {
            SHA256Managed sha256 = new SHA256Managed();

            return(ConvertToString(sha256.ComputeHash(buffer, offset, count)));
        }
Ejemplo n.º 46
0
 public static string GetSHA256(this Stream stream)
 {
     return(stream.GetHashString(SHA256Managed.Create()));
 }
Ejemplo n.º 47
0
        public ActionResult Agregar(encuesta_usuariosCLS Oencuesta_usuariosCLS)
        {
            using (var db = new csstdura_encuestaEntities())
            {
                using (var transaction = new TransactionScope())
                {
                    if (!ModelState.IsValid)
                    {
                        llenarEmpresa();
                        llenarSexo();
                        llenarEdad();
                        llenarEdoCivil();
                        llenarOpciones();
                        llenarProcesoEdu();
                        llenarTipoPuesto();
                        llenarTipoContratacion();
                        llenarTipoPersonal();
                        llenarTipoJornada();
                        llenarRotacionTurno();
                        llenarTiempoEmp();
                        llenarExpLab();
                        //llenarDepto();
                        // llenarCentro();
                        ViewBag.listaSexo     = listaSexo;
                        ViewBag.listaEdad     = listaEdad;
                        ViewBag.listaEdoCivil = listaEdoCivil;
                        ViewBag.listaOpciones = listaOpciones;
                        ViewBag.listaProceso  = listaProceso;
                        ViewBag.listaPuesto   = listaPuesto;
                        ViewBag.listaContrata = listaContrata;
                        ViewBag.listaPersonal = listaPersonal;
                        ViewBag.listaJornada  = listaJornada;
                        ViewBag.listaRotacion = listaRotacion;
                        ViewBag.listaTiempo   = listaTiempo;
                        ViewBag.listaExpLab   = listaExpLab;
                        // ViewBag.listaDepto = listaDepto;
                        // ViewBag.listaCentro = listaCentro;
                        return(View(Oencuesta_usuariosCLS));
                    }
                    //Usando clase de entity framework
                    encuesta_usuarios usuarios = new encuesta_usuarios();
                    usuarios.usua_nombre    = Oencuesta_usuariosCLS.usua_nombre;
                    usuarios.usua_empresa   = Oencuesta_usuariosCLS.usua_empresa;
                    usuarios.usua_f_aplica  = DateTime.Now;
                    usuarios.usua_tipo      = "U";
                    usuarios.usua_estatus   = "ACTIVO";
                    usuarios.usua_n_usuario = Oencuesta_usuariosCLS.usua_n_usuario;

                    //Cifrando el password
                    SHA256Managed sha               = new SHA256Managed();
                    byte[]        byteContra        = Encoding.Default.GetBytes(Oencuesta_usuariosCLS.usua_p_usuario);
                    byte[]        byteContraCifrado = sha.ComputeHash(byteContra);
                    string        contraCifrada     = BitConverter.ToString(byteContraCifrado).Replace("-", "");
                    usuarios.usua_p_usuario = contraCifrada;

                    int periodo = db.Database.SqlQuery <int>("Select periodo_id from encuaesta_periodo where periodo_estatus='A'")
                                  .FirstOrDefault();

                    //usuarios.usua_p_usuario = Oencuesta_usuariosCLS.usua_p_usuario;
                    usuarios.usua_u_alta            = "";
                    usuarios.usua_f_alta            = DateTime.Now;
                    usuarios.usua_u_cancela         = "";
                    usuarios.usua_f_cancela         = null;
                    usuarios.usua_genero            = Oencuesta_usuariosCLS.usua_genero;
                    usuarios.usua_edad              = Oencuesta_usuariosCLS.usua_edad;
                    usuarios.usua_edo_civil         = Oencuesta_usuariosCLS.usua_edo_civil;
                    usuarios.usua_sin_forma         = Oencuesta_usuariosCLS.usua_sin_forma;
                    usuarios.usua_primaria          = Oencuesta_usuariosCLS.usua_primaria;
                    usuarios.usua_secundaria        = Oencuesta_usuariosCLS.usua_secundaria;
                    usuarios.usua_preparatoria      = Oencuesta_usuariosCLS.usua_preparatoria;
                    usuarios.usua_tecnico           = Oencuesta_usuariosCLS.usua_tecnico;
                    usuarios.usua_licenciatura      = Oencuesta_usuariosCLS.usua_licenciatura;
                    usuarios.usua_maestria          = Oencuesta_usuariosCLS.usua_maestria;
                    usuarios.usua_doctorado         = Oencuesta_usuariosCLS.usua_doctorado;
                    usuarios.usua_tipo_puesto       = Oencuesta_usuariosCLS.usua_tipo_puesto;
                    usuarios.usua_tipo_contratacion = Oencuesta_usuariosCLS.usua_tipo_contratacion;
                    usuarios.usua_tipo_personal     = Oencuesta_usuariosCLS.usua_tipo_personal;
                    usuarios.usua_tipo_jornada      = Oencuesta_usuariosCLS.usua_tipo_jornada;
                    usuarios.usua_rotacion_turno    = Oencuesta_usuariosCLS.usua_rotacion_turno;
                    usuarios.usua_tiempo_puesto     = Oencuesta_usuariosCLS.usua_tiempo_puesto;
                    usuarios.usua_exp_laboral       = Oencuesta_usuariosCLS.usua_exp_laboral;
                    usuarios.usua_presento          = "N";
                    usuarios.usua_departamento      = Oencuesta_usuariosCLS.usua_departamento;
                    usuarios.usua_centro_trabajo    = Oencuesta_usuariosCLS.usua_centro_trabajo;
                    usuarios.usua_periodo           = periodo;
                    db.encuesta_usuarios.Add(usuarios);
                    int res = db.SaveChanges();
                    transaction.Complete();
                    if (res == 1)
                    {
                        return(Content("<script language='javascript' type='text/javascript'>alert('Registro exitoso!');window.location = '/Login/Index';</script>"));
                    }
                    else
                    {
                        return(Content("<script language='javascript' type='text/javascript'>alert('Ocurrio un error!');window.location = '/Usuarios/Agregar';</script>"));
                    }
                }
            }
        }
Ejemplo n.º 48
0
 public static Task <string> GetSHA256Async(this Stream stream, CancellationToken token = default)
 {
     return(stream.GetHashStringAsync(SHA256Managed.Create(), token: token));
 }
Ejemplo n.º 49
0
        protected static byte[] Hash256(byte[] orig)
        {
            HashAlgorithm sha = new SHA256Managed();

            return(sha.ComputeHash(orig));
        }
Ejemplo n.º 50
0
        private void btn_ingresar_Click(object sender, EventArgs e)
        {
            if (!ValidarCampos())
            {
                return;
            }


            Usuario usuario = new Usuario(textBox_user.Text);



            if (!usuario.existeUsuario())
            {
                Interfaz.Interfaz.mostrarMensaje("El usuario no existe!!");
                return;
            }

            if (!usuario.estaHabilitado())
            {
                Interfaz.Interfaz.mostrarMensaje("El usuario no esta habilitado!! contactese con un administrador");
                return;
            }


            //Si es el primer login tomo como password lo que inserta el usuario ya que nunca se guardo la pass encriptada, si no lo paso al SHA256
            if (usuario.primerLogin)
            {
                usuario.Password = textBox_password.Text;
            }
            else
            {
                UTF8Encoding  encoderHash   = new UTF8Encoding();
                SHA256Managed hasher        = new SHA256Managed();
                byte[]        bytesDeHasheo = hasher.ComputeHash(encoderHash.GetBytes(textBox_password.Text));
                string        password      = Interfaz.Interfaz.bytesDeHasheoToString(bytesDeHasheo);
                usuario.Password = password;
            }


            if (usuario.checkPassword())
            {
                Interfaz.Interfaz.mostrarMensaje("Usuario logueado exitosamente!");
                usuario.resetearIntentos();
                if (usuario.primerLogin)
                {
                    Interfaz.Interfaz.mostrarMensaje("Debido a que es la primera vez que se loguea luego de la migracion, es necesario que modifique su contrasena");
                    InputDialog formDialog = new InputDialog();
                    formDialog.ShowDialog();
                    usuario.cambiarPassword(formDialog.newPass);
                    Interfaz.Interfaz.mostrarMensaje("La contraseña ha sido modificada");
                    usuario.setPrimeraVez(false);
                }



                Interfaz.Interfaz.usuario = usuario;
                //hace falta este?
                Repositorio.currentUser(usuario);
                SelectRolFuncionalidad rolDialog = new SelectRolFuncionalidad();
                rolDialog.ShowDialog();
            }
            else // LA PASSWORD ES INVALIDA
            {
                Interfaz.Interfaz.mostrarMensaje("La password es invalida");
                usuario.sumarIntentoFallido();
                if (usuario.getIntentosFallidos() == 3)
                {
                    usuario.deshabilitar();
                    Interfaz.Interfaz.mostrarMensaje("Su usuario ha sido deshabilitado por reiterados ingresos invalidos");
                }
            }
        }
Ejemplo n.º 51
0
 /// <summary>
 /// Computes the SHA-256 checksum for the bytes.
 /// </summary>
 public static Byte[] Compute(Byte[] bytes)
 {
     SHA256Managed sha256 = new SHA256Managed();
     return sha256.ComputeHash(bytes);
 }
Ejemplo n.º 52
0
        public byte[] GetSuperBlockHash()
        {
            SHA256Managed sha = new SHA256Managed();

            return(sha.ComputeHash(Data, 0, 0x400));
        }
Ejemplo n.º 53
0
        public static string oldAddrToCashAddr(string oldAddress, out bool isP2PKH, out bool mainnet)
        {
            // BigInteger wouldn't be needed, but that would result in the use a MIT License
            BigInteger address        = new BigInteger(0);
            BigInteger baseFiftyEight = new BigInteger(58);

            for (int x = 0; x < oldAddress.Length; x++)
            {
                int value = DICT_BASE58[oldAddress[x]];
                if (value != -1)
                {
                    address = BigInteger.Multiply(address, baseFiftyEight);
                    address = BigInteger.Add(address, new BigInteger(value));
                }
                else
                {
                    throw new CashAddrConversionException("Address contains unexpected character.");
                }
            }
            int numZeros = 0;

            for (; (numZeros < oldAddress.Length) && (oldAddress[numZeros] == Convert.ToChar("1")); numZeros++)
            {
            }
            byte[] addrBytes = address.ToByteArray();
            Array.Reverse(addrBytes);
            // Reminder, addrBytes was converted from BigInteger. So the first byte,
            // the sign byte should be skipped, **if exists**
            if (addrBytes[0] == 0)
            {
                // because of 0xc4
                var temp = new List <byte>(addrBytes);
                temp.RemoveAt(0);
                addrBytes = temp.ToArray();
            }
            if (numZeros > 0)
            {
                var temp = new List <byte>(addrBytes);
                for (; numZeros != 0; numZeros--)
                {
                    temp.Insert(0, 0);
                }
                addrBytes = temp.ToArray();
            }
            if (addrBytes.Length != 25)
            {
                throw new CashAddrConversionException("Address to be decoded is shorter or longer than expected!");
            }
            switch (addrBytes[0])
            {
            case 0x00:
                isP2PKH = true;
                mainnet = true;
                break;

            case 0x05:
                isP2PKH = false;
                mainnet = true;
                break;

            case 0x6f:
                isP2PKH = true;
                mainnet = false;
                break;

            case 0xc4:
                isP2PKH = false;
                mainnet = false;
                break;

            case 0x1c:
            // BitPay P2PKH, obsolete!
            case 0x28:
            // BitPay P2SH, obsolete!
            default:
                throw new CashAddrConversionException("Unexpected address byte.");
            }
            if (addrBytes.Length != 25)
            {
                throw new CashAddrConversionException("Old address is longer or shorter than expected.");
            }
            SHA256 hasher = SHA256Managed.Create();

            byte[] checksum = hasher.ComputeHash(hasher.ComputeHash(addrBytes, 0, 21));
            if (addrBytes[21] != checksum[0] || addrBytes[22] != checksum[1] || addrBytes[23] != checksum[2] || addrBytes[24] != checksum[3])
            {
                throw new CashAddrConversionException("Address checksum doesn't match. Have you made a mistake while typing it?");
            }
            addrBytes[0] = (byte)(isP2PKH ? 0x00 : 0x08);
            byte[] cashAddr = convertBitsEightToFive(addrBytes);
            var    ret      = new System.Text.StringBuilder(mainnet ? "bitcoincash:" : "bchtest:");
            // https://play.golang.org/p/sM_CE4AQ7Vp
            ulong mod = PolyMod(cashAddr, (ulong)(mainnet ? 1058337025301 : 584719417569));

            for (int i = 0; i < 8; ++i)
            {
                cashAddr[i + 34] = (byte)((mod >> (5 * (7 - i))) & 0x1f);
            }
            for (int i = 0; i < cashAddr.Length; i++)
            {
                ret.Append(CHARSET_CASHADDR[cashAddr[i]]);
            }
            return(ret.ToString());
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Attempts to find the correct hash for the current block.
        /// </summary>
        /// <param name="miningWindow">Shows the mining window if set to true.</param>
        /// <returns>Returns true if this user successfully mined the block.</returns>
        public async void MineBlock()
        {
            // Asks for address to collect mining rewards. Defaults to my address if cancelled.
            if (miner_id == "")
            {
                miner_id = Microsoft.VisualBasic.Interaction.InputBox("Enter the public key that you would like your mining rewards sent to.", "Mining Rewards",
                                                                      "BgIAAACkAABSU0ExAAQAAAEAAQA/KlTgRpoq4gx6RQFiPz+1FAEq5VOUZrfOWJ593nwm7gjsV6x+uxEJRScSLOmBda2PEmVTlFim2Y/Aund29KDXryz16sl6719hR3qZVUkEohAbvPayDJ7r70EAM+oGAU8KiPnyoQqF6bLexEE9yXtA39q94KTPMC4wT7jIhi1E9Q==");
            }

            int    count      = 0;
            int    count2     = 0;
            string hashString = "1234567890";

            DateTime start    = DateTime.Now;
            DateTime previous = DateTime.Now;

            mw.ConsoleOutput.Document.Blocks.Clear();
            mw.speedWindow.Clear();

            await Task.Run(() =>
            {
                while (hashString.Substring(0, 5) != "00000")
                {
                    if (mining == false)
                    {
                        break;
                    }

                    byte[] hash;
                    string temp;
                    SHA256Managed hasher = new SHA256Managed();
                    temp             = count.ToString() + previousBlock.index.ToString() + previousBlock.getTimeString() + previousBlock.data.ToString() + previousBlock.previousHash;
                    Byte[] byteArray = Encoding.UTF8.GetBytes(temp);
                    hash             = hasher.ComputeHash(byteArray);

                    hashString = string.Empty;

                    foreach (byte x in hash)
                    {
                        hashString += String.Format("{0:x2}", x);
                    }

                    if (count % 1000 == 0)
                    {
                        mw.Dispatcher.Invoke(DispatcherPriority.Render, new Action(() =>
                        {
                            mw.ConsoleOutput.AppendText(Environment.NewLine + count.ToString() + " - " + hashString);
                            mw.ConsoleOutput.ScrollToEnd();
                        }));
                    }

                    DateTime elapsed = DateTime.Now;

                    if (elapsed.Subtract(previous).TotalMilliseconds >= 1000)
                    {
                        mw.Dispatcher.Invoke(DispatcherPriority.Render, new Action(() =>
                        {
                            mw.speedWindow.Text = (count2 / 1000).ToString() + " KH/sec";
                        }));

                        count2   = 0;
                        previous = DateTime.Now;
                    }

                    count++;
                    count2++;
                }
            });

            if (mining == true)
            {
                mw.Dispatcher.Invoke(DispatcherPriority.Render, new Action(() =>
                {
                    mw.ConsoleOutput.AppendText(Environment.NewLine + count.ToString() + " - " + hashString);
                    mw.ConsoleOutput.ScrollToEnd();
                }));

                DateTime finish   = DateTime.Now;
                Double   duration = finish.Subtract(start).TotalSeconds;

                mw.ConsoleOutput.AppendText(Environment.NewLine + "Block time: " + duration.ToString() + " Seconds. Average speed: " + ((count / duration) / 1000).ToString("N2") + " KH/sec.");

                // Include mining reward in block
                Transaction reward = new Transaction("miningReward", miner_id, MiningReward(), HashCount(count));
                currentBlock.AddTransaction(reward, chain);

                // Add block to chain
                Serialize.WriteBlock(currentBlock);
                chain.Add(currentBlock);
                blockHeight++;
                network.blockheight = blockHeight;
                previousBlock       = chain.ElementAt(blockHeight - 1);

                // Broadcast Block
                SendBlock(currentBlock);

                // Create new block
                currentBlock = new Block();
                currentBlock.NewBlock(blockHeight, previousBlock.HashBlock());

                // Start mining again
                MineBlock();
            }
        }
Ejemplo n.º 55
0
        public static byte[] GetBytes(byte[] payload, byte[] salt, int iterations, int howManyBytes)
        {
            // round up

            uint cBlocks = (uint)((howManyBytes + HASH_SIZE_IN_BYTES - 1) / HASH_SIZE_IN_BYTES);

            // seed for the pseudo-random fcn: salt + block index
            byte[] saltAndIndex = new byte[salt.Length + 4];
            Array.Copy(salt, 0, saltAndIndex, 0, salt.Length);

            byte[] output       = new byte[cBlocks * HASH_SIZE_IN_BYTES];
            int    outputOffset = 0;

            SHA256Managed innerHash = new SHA256Managed();
            SHA256Managed outerHash = new SHA256Managed();

            // HMAC says the key must be hashed or padded with zeros
            // so it fits into a single block of the hash in use
            if (payload.Length > BLOCK_SIZE_IN_BYTES)
            {
                payload = innerHash.ComputeHash(payload);
            }

            byte[] key = new byte[BLOCK_SIZE_IN_BYTES];
            Array.Copy(payload, 0, key, 0, payload.Length);

            byte[] innerKey = new byte[BLOCK_SIZE_IN_BYTES];
            byte[] outerKey = new byte[BLOCK_SIZE_IN_BYTES];
            for (int i = 0; i < BLOCK_SIZE_IN_BYTES; ++i)
            {
                innerKey[i] = (byte)(key[i] ^ IPAD);
                outerKey[i] = (byte)(key[i] ^ OPAD);
            }

            // for each block of desired output
            for (int iBlock = 0; iBlock < cBlocks; ++iBlock)
            {
                // seed HMAC with salt & block index
                IncrementBigEndianIndex(saltAndIndex, salt.Length);
                byte[] u = saltAndIndex;

                for (int i = 0; i < iterations; ++i)
                {
                    // simple implementation of HMAC-SHA-256
                    innerHash.Initialize();
                    innerHash.TransformBlock(innerKey, 0,
                                             BLOCK_SIZE_IN_BYTES, innerKey, 0);
                    innerHash.TransformFinalBlock(u, 0, u.Length);

                    byte[] temp = innerHash.Hash;

                    outerHash.Initialize();
                    outerHash.TransformBlock(outerKey, 0,
                                             BLOCK_SIZE_IN_BYTES, outerKey, 0);
                    outerHash.TransformFinalBlock(temp, 0, temp.Length);

                    u = outerHash.Hash; // U = result of HMAC

                    // xor result into output buffer
                    XorByteArray(u, 0, HASH_SIZE_IN_BYTES,
                                 output, outputOffset);
                }

                outputOffset += HASH_SIZE_IN_BYTES;
            }

            byte[] result = new byte[howManyBytes];
            Array.Copy(output, 0, result, 0, howManyBytes);
            return(result);
        }
Ejemplo n.º 56
0
        private static void LerDados()
        {
            Console.WriteLine("Listening the server in a new thread");
            while (true)
            {
                try
                {
                    //Recebe os dados
                    byte[] lengthBytes = ler.ReadBytes(4);
                    int    length      = System.BitConverter.ToInt32(lengthBytes, 0);
                    byte[] rcvBytes    = ler.ReadBytes(length);

                    //Tira da base64
                    string text = Encoding.UTF8.GetString(rcvBytes);


                    //Tira do JSON
                    Model.Message msg          = JsonConvert.DeserializeObject <Model.Message>(text);
                    string        mensagemText = Encoding.UTF8.GetString(msg.text);
                    Console.WriteLine("DEBUG: Test: " + mensagemText);

                    string chaveString = Encoding.ASCII.GetString(msg.chave);

                    RSA = DecodeX509PublicKey(Convert.FromBase64String(chaveString));

                    string mensagemHash     = Encoding.ASCII.GetString(msg.hash);
                    string mensagemAssinada = Encoding.ASCII.GetString(msg.sign);
                    bool   verify           = verifySignature(mensagemAssinada, mensagemHash);
                    if (verify)
                    {
                        //Verifica o Hash SHA-256
                        SHA256Managed crypt = new SHA256Managed();
                        StringBuilder hash  = new StringBuilder(); //StringBuilder para maior desempenho devido as constantes mudanças na string

                        string hashStr  = Encoding.ASCII.GetString(msg.hash);
                        byte[] hashByte = Convert.FromBase64String(hashStr);

                        byte[] hashBytes = crypt.ComputeHash(msg.text);
                        foreach (byte theByte in hashBytes)
                        {
                            hash.Append(theByte.ToString("x2"));
                        }

                        StringBuilder messageHash = new StringBuilder();
                        foreach (byte theByte in hashByte)
                        {
                            messageHash.Append(theByte.ToString("x2"));
                        }

                        if (messageHash.Equals(hash))
                        {
                            Console.WriteLine("Server response: " + Encoding.UTF8.GetString(msg.text));
                        }
                        else
                        {
                            Console.WriteLine("Invalid message hash!");
                        }
                    }
                    Console.WriteLine("Result: " + verify);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Connection with the server was lost, shutting down client...");
                    Environment.Exit(0);
                }
            }
        }
Ejemplo n.º 57
0
        private void MakeRomFSData(RomfsFile[] RomFiles, MemoryStream metadata)
        {
            TempFile = Path.GetRandomFileName();
            TB_Progress.Invoke((Action)(() => UpdateTB_Progress("Computing IVFC Header Data...")));
            IVFCInfo ivfc = new IVFCInfo();

            ivfc.Levels = new IVFCLevel[3];
            for (int i = 0; i < ivfc.Levels.Length; i++)
            {
                ivfc.Levels[i]           = new IVFCLevel();
                ivfc.Levels[i].BlockSize = 0x1000;
            }
            ivfc.Levels[2].DataLength = RomfsFile.GetDataBlockLength(RomFiles, (ulong)metadata.Length);
            ivfc.Levels[1].DataLength = (Align(ivfc.Levels[2].DataLength, ivfc.Levels[2].BlockSize) / ivfc.Levels[2].BlockSize) * 0x20; //0x20 per SHA256 hash
            ivfc.Levels[0].DataLength = (Align(ivfc.Levels[1].DataLength, ivfc.Levels[1].BlockSize) / ivfc.Levels[1].BlockSize) * 0x20; //0x20 per SHA256 hash
            ulong MasterHashLen = (Align(ivfc.Levels[0].DataLength, ivfc.Levels[0].BlockSize) / ivfc.Levels[0].BlockSize) * 0x20;
            ulong lofs          = 0;

            for (int i = 0; i < ivfc.Levels.Length; i++)
            {
                ivfc.Levels[i].HashOffset = lofs;
                lofs += Align(ivfc.Levels[i].DataLength, ivfc.Levels[i].BlockSize);
            }
            uint IVFC_MAGIC      = 0x43465649; //IVFC
            uint RESERVED        = 0x0;
            uint HeaderLen       = 0x5C;
            uint MEDIA_UNIT_SIZE = 0x200;

            byte[]     SuperBlockHash = new byte[0x20];
            FileStream OutFileStream  = new FileStream(TempFile, FileMode.Create, FileAccess.ReadWrite);

            try
            {
                OutFileStream.Seek(0, SeekOrigin.Begin);
                OutFileStream.Write(BitConverter.GetBytes(IVFC_MAGIC), 0, 0x4);
                OutFileStream.Write(BitConverter.GetBytes(0x10000), 0, 0x4);
                OutFileStream.Write(BitConverter.GetBytes(MasterHashLen), 0, 0x4);
                for (int i = 0; i < ivfc.Levels.Length; i++)
                {
                    OutFileStream.Write(BitConverter.GetBytes(ivfc.Levels[i].HashOffset), 0, 0x8);
                    OutFileStream.Write(BitConverter.GetBytes(ivfc.Levels[i].DataLength), 0, 0x8);
                    OutFileStream.Write(BitConverter.GetBytes((int)(Math.Log(ivfc.Levels[i].BlockSize, 2))), 0, 0x4);
                    OutFileStream.Write(BitConverter.GetBytes(RESERVED), 0, 0x4);
                }
                OutFileStream.Write(BitConverter.GetBytes(HeaderLen), 0, 0x4);
                //IVFC Header is Written.
                OutFileStream.Seek((long)Align(MasterHashLen + 0x60, ivfc.Levels[0].BlockSize), SeekOrigin.Begin);
                byte[] metadataArray = metadata.ToArray();
                OutFileStream.Write(metadataArray, 0, metadataArray.Length);
                long baseOfs = OutFileStream.Position;
                TB_Progress.Invoke((Action)(() => UpdateTB_Progress("Writing Level 2 Data...")));
                PB_Show.Invoke((Action)(() =>
                {
                    PB_Show.Minimum = 0;
                    PB_Show.Maximum = RomFiles.Length;
                    PB_Show.Value = 0;
                    PB_Show.Step = 1;
                }));
                for (int i = 0; i < RomFiles.Length; i++)
                {
                    OutFileStream.Seek((long)(baseOfs + (long)RomFiles[i].Offset), SeekOrigin.Begin);
                    using (FileStream inStream = new FileStream(RomFiles[i].FullName, FileMode.Open, FileAccess.Read))
                    {
                        while (inStream.Position < inStream.Length)
                        {
                            byte[] buffer = new byte[inStream.Length - inStream.Position > 0x100000 ? 0x100000 : inStream.Length - inStream.Position];
                            inStream.Read(buffer, 0, buffer.Length);
                            OutFileStream.Write(buffer, 0, buffer.Length);
                        }
                    }
                    PB_Show.Invoke((Action)(() => PB_Show.PerformStep()));
                }
                long          hashBaseOfs = (long)Align((ulong)OutFileStream.Position, ivfc.Levels[2].BlockSize);
                long          hOfs        = (long)Align(MasterHashLen, ivfc.Levels[0].BlockSize);
                long          cOfs        = hashBaseOfs + (long)ivfc.Levels[1].HashOffset;
                SHA256Managed sha         = new SHA256Managed();
                for (int i = ivfc.Levels.Length - 1; i >= 0; i--)
                {
                    TB_Progress.Invoke((Action)(() => UpdateTB_Progress("Computing Level " + i + " Hashes...")));
                    byte[] buffer = new byte[(int)ivfc.Levels[i].BlockSize];
                    PB_Show.Invoke((Action)(() =>
                    {
                        PB_Show.Minimum = 0;
                        PB_Show.Maximum = (int)(ivfc.Levels[i].DataLength / ivfc.Levels[i].BlockSize);
                        PB_Show.Value = 0;
                        PB_Show.Step = 1;
                    }));
                    for (long ofs = 0; ofs < (long)ivfc.Levels[i].DataLength; ofs += ivfc.Levels[i].BlockSize)
                    {
                        OutFileStream.Seek(hOfs, SeekOrigin.Begin);
                        OutFileStream.Read(buffer, 0, (int)ivfc.Levels[i].BlockSize);
                        hOfs = OutFileStream.Position;
                        byte[] hash = sha.ComputeHash(buffer);
                        OutFileStream.Seek(cOfs, SeekOrigin.Begin);
                        OutFileStream.Write(hash, 0, hash.Length);
                        cOfs = OutFileStream.Position;
                        PB_Show.Invoke((Action)(() => PB_Show.PerformStep()));
                    }
                    if (i == 2)
                    {
                        long len = OutFileStream.Position;
                        if (len % 0x1000 != 0)
                        {
                            len = (long)Align((ulong)len, 0x1000);
                            byte[] buf = new byte[len - OutFileStream.Position];
                            OutFileStream.Write(buf, 0, buf.Length);
                        }
                    }
                    if (i > 0)
                    {
                        hOfs = hashBaseOfs + (long)ivfc.Levels[i - 1].HashOffset;
                        if (i > 1)
                        {
                            cOfs = hashBaseOfs + (long)ivfc.Levels[i - 2].HashOffset;
                        }
                        else
                        {
                            cOfs = (long)Align(HeaderLen, PADDING_ALIGN);
                        }
                    }
                }
                OutFileStream.Seek(0, SeekOrigin.Begin);
                uint   SuperBlockLen = (uint)Align(MasterHashLen + 0x60, MEDIA_UNIT_SIZE);
                byte[] MasterHashes  = new byte[SuperBlockLen];
                OutFileStream.Read(MasterHashes, 0, (int)SuperBlockLen);
                SuperBlockHash = sha.ComputeHash(MasterHashes);
            }
            finally
            {
                if (OutFileStream != null)
                {
                    OutFileStream.Dispose();
                }
            }
            TB_Progress.Invoke((Action)(() => UpdateTB_Progress("RomFS Super Block Hash: " + ByteArrayToString(SuperBlockHash))));
            TB_Progress.Invoke((Action)(() => UpdateTB_Progress("Prompting to Save...")));
            SaveFileDialog sfd = new SaveFileDialog();

            Invoke((Action)(() =>
            {
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    TB_Progress.Invoke((Action)(() => UpdateTB_Progress("Writing Binary to " + sfd.FileName + "...")));
                    Thread thread = new Thread(() => WriteBinary(TempFile, sfd.FileName));
                    thread.IsBackground = true;
                    thread.Start();
                }
            }));
        }
Ejemplo n.º 58
0
        public static Byte[] SHA256(Byte[] Bytes)
        {
            SHA256 sha = new SHA256Managed();

            return(sha.ComputeHash(Bytes));
        }
Ejemplo n.º 59
0
 public static string HashCode(this string password)
 {
     byte[] getByte  = new ASCIIEncoding().GetBytes(password);
     byte[] hashByte = new SHA256Managed().ComputeHash(getByte);
     return(new ASCIIEncoding().GetString(hashByte));
 }
Ejemplo n.º 60
0
        /// <summary>
        /// Generates a hash for the given plain text value and returns a
        /// base64-encoded result. Before the hash is computed, a random salt
        /// is generated and appended to the plain text. This salt is stored at
        /// the end of the hash value, so it can be used later for hash
        /// verification.
        /// </summary>
        /// <param name="byteData">
        /// Plaintext value to be hashed.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
        /// "SHA256", "SHA384", "SHA512", "HMACMD5", "HMACSHA1", "HMACSHA256",
        ///  "HMACSHA512" (if any other value is specified  MD5 will be used).
        ///
        /// HMAC algorithms uses Hash-based Message Authentication Code.
        /// The HMAC process mixes a secret key with the message data, hashes
        /// the result with the hash function, mixes that hash value with
        /// the secret key again, and then applies the hash function
        /// a second time. HMAC hashes are fixed lenght and generally
        /// much longer than non-HMAC hashes of the same type.
        ///
        /// https://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha256(v=vs.110).aspx
        ///
        /// This value is case-insensitive.
        /// </param>
        /// <param name="saltBytes">
        /// Optional but recommended salt bytes to apply to the hash. If not passed the
        /// raw encoding is used. If salt is nullthe raw algorithm is used (useful for
        /// file hashes etc.) HMAC versions REQUIRE that salt is passed.
        /// </param>
        /// <param name="useBinHex">if true returns the data as BinHex byte pair string. Otherwise Base64 is returned.</param>
        /// <returns>
        /// Hash value formatted as a base64-encoded or BinHex stringstring.
        /// </returns>
        public static string ComputeHash(byte[] byteData,
                                         string hashAlgorithm,
                                         byte[] saltBytes,
                                         bool useBinHex = false)
        {
            if (byteData == null)
            {
                return(null);
            }

            // Convert plain text into a byte array.
            byte[] plainTextWithSaltBytes;

            if (saltBytes != null && !hashAlgorithm.StartsWith("HMAC"))
            {
                // Allocate array, which will hold plain text and salt.
                plainTextWithSaltBytes =
                    new byte[byteData.Length + saltBytes.Length];

                // Copy plain text bytes into resulting array.
                for (int i = 0; i < byteData.Length; i++)
                {
                    plainTextWithSaltBytes[i] = byteData[i];
                }

                // Append salt bytes to the resulting array.
                for (int i = 0; i < saltBytes.Length; i++)
                {
                    plainTextWithSaltBytes[byteData.Length + i] = saltBytes[i];
                }
            }
            else
            {
                plainTextWithSaltBytes = byteData;
            }

            HashAlgorithm hash;

            // Make sure hashing algorithm name is specified.
            if (hashAlgorithm == null)
            {
                hashAlgorithm = "";
            }

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm.ToUpper())
            {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            case "HMACMD5":
                hash = new HMACMD5(saltBytes);
                break;

            case "HMACSHA1":
                hash = new HMACSHA1(saltBytes);
                break;

            case "HMACSHA256":
                hash = new HMACSHA256(saltBytes);
                break;

            case "HMACSHA512":
                hash = new HMACSHA512(saltBytes);
                break;

            default:
                // default to MD5
                hash = new MD5CryptoServiceProvider();
                break;
            }

            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);


            hash.Dispose();

            if (useBinHex)
            {
                return(BinaryToBinHex(hashBytes));
            }

            return(Convert.ToBase64String(hashBytes));
        }