예제 #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;
    }
    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);
    }
예제 #3
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;
    }
예제 #4
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;
    }
예제 #5
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];
     }
 }
 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);
 }
예제 #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();
 }
예제 #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;
    }
예제 #9
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);
 }
예제 #10
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;
 }
예제 #11
0
파일: Util.cs 프로젝트: vsite-prog/PIN
 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);
 }
예제 #12
0
파일: Util.cs 프로젝트: vsite-prog/PIN
 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);
 }
 /**
    * 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;
 }
예제 #14
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();
        }
    }
예제 #15
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;
    }
예제 #16
0
파일: Util.cs 프로젝트: vsite-prog/PIN
    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);
    }
예제 #17
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;
 }
예제 #18
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();
    }
예제 #19
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();
    }
예제 #20
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;
    }
예제 #21
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);
    }
예제 #22
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;
    }
예제 #24
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;
    }
예제 #25
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;
            }
    }
예제 #27
0
    // Genera una cadena de texto hash a partir de un SaveData dado
    private string generateHash(SaveData sd)
    {
        // Guardamos todo en un JSON como cadena de texto
        // Este string solo lo utilizaremos para generar el hash luego lo desecharemos
        string saveString = JsonUtility.ToJson(sd, true);

        // Setup de SHA
        SHA256Managed crypt = new SHA256Managed();
        string        hash  = System.String.Empty;

        // Computamos el hash
        byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(saveString), 0, Encoding.UTF8.GetByteCount(saveString));

        // Convertimos a hexadecimal
        foreach (byte bit in crypto)
        {
            hash += bit.ToString("x2");
        }

        return(hash);
    }
예제 #28
0
        /***
         * This function decrypts the encrypted text to plain text using the key
         * provided. You'll have to use the same key which you used during
         * encryption
         *
         * @param _encryptedText
         *            Encrypted/Cipher text to be decrypted
         * @param _key
         *            Encryption key which you used during encryption
         */
        public static string getHashSha256(string text, int length)
        {
            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);                 //covert to hex string
            }
            if (length > hashString.Length)
            {
                return(hashString);
            }
            else
            {
                return(hashString.Substring(0, length));
            }
        }
예제 #29
0
        /// <summary>
        /// Create a SHA256 or MD5 checksum from a bunch of bytes
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="mode">SHA256,MD5</param>
        /// <returns></returns>
        public static string GetChecksumFromBytes(byte[] fileData, string mode)
        {
            using (MemoryStream stream = new MemoryStream(fileData))
            {
                if (mode == "SHA256")
                {
                    var    sha      = new SHA256Managed();
                    byte[] checksum = sha.ComputeHash(stream);
                    return(BinaryToBinHex(checksum));
                }
                if (mode == "MD5")
                {
                    var    md       = new MD5CryptoServiceProvider();
                    byte[] checkSum = md.ComputeHash(stream);

                    return(BinaryToBinHex(checkSum));
                }
            }

            return(null);
        }
예제 #30
0
        /// <summary>
        /// Creates an SHA256 or MD5 checksum of a file
        /// </summary>
        /// <param name="file"></param>
        /// <param name="mode">SHA256,MD5</param>
        /// <returns></returns>
        public static string GetChecksumFromFile(string file, string mode, bool useBinHex = false)
        {
            using (FileStream stream = File.OpenRead(file))
            {
                if (mode == "SHA256")
                {
                    var    sha      = new SHA256Managed();
                    byte[] checksum = sha.ComputeHash(stream);
                    return(BinaryToBinHex(checksum));
                }
                if (mode == "MD5")
                {
                    var    md       = new MD5CryptoServiceProvider();
                    byte[] checkSum = md.ComputeHash(stream);

                    return(BinaryToBinHex(checkSum));
                }
            }

            return(null);
        }
예제 #31
0
 public static string EncryptDataForLogins(string username, string password)
 {
     try
     {
         string salt = Constants.SALT;
         // merge password and salt together
         string sHashWithSalt = password + username.Trim() + salt;
         // convert this merged value to a byte array
         byte[] saltedHashBytes = Encoding.UTF8.GetBytes(sHashWithSalt);
         // use hash algorithm to compute the hash
         HashAlgorithm algorithm = new SHA256Managed();
         // convert merged bytes to a hash as byte array
         byte[] hash = algorithm.ComputeHash(saltedHashBytes);
         // return the has as a base 64 encoded string
         return(Convert.ToBase64String(hash));
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
예제 #32
0
        public async Task <TLUser> MakeAuthWithPasswordAsync(TLPassword password, string password_str, CancellationToken token = default(CancellationToken))
        {
            token.ThrowIfCancellationRequested();

            byte[]             password_Bytes = Encoding.UTF8.GetBytes(password_str);
            IEnumerable <byte> rv             = password.CurrentSalt.Concat(password_Bytes).Concat(password.CurrentSalt);

            SHA256Managed hashstring    = new SHA256Managed();
            var           password_hash = hashstring.ComputeHash(rv.ToArray());

            var request = new TLRequestCheckPassword()
            {
                PasswordHash = password_hash
            };

            await RequestWithDcMigration(request, token).ConfigureAwait(false);

            OnUserAuthenticated((TLUser)request.Response.User);

            return((TLUser)request.Response.User);
        }
예제 #33
0
        private static string encryptPlaintextPassword(string plaintextPassword, string salt)
        {
            var hash = new SHA256Managed();

            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plaintextPassword);
            byte[] saltBytes      = Encoding.UTF8.GetBytes(salt);

            byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];
            Array.Copy(plainTextBytes, plainTextWithSaltBytes, plainTextBytes.Length);
            Array.ConstrainedCopy(saltBytes, 0, plainTextWithSaltBytes, plainTextBytes.Length, saltBytes.Length);

            byte[] hashBytes         = hash.ComputeHash(plainTextWithSaltBytes);
            byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length];

            Array.Copy(hashBytes, hashWithSaltBytes, hashBytes.Length);
            Array.ConstrainedCopy(saltBytes, 0, hashWithSaltBytes, hashBytes.Length, saltBytes.Length);

            string hashValue = Convert.ToBase64String(hashWithSaltBytes);

            return(hashValue);
        }
예제 #34
0
    public static void Main()
    {
        string        msg    = "StackOverflow test 123";
        string        sig    = "IB7XjSi9TdBbB3dVUK4+Uzqf2Pqk71XkZ5PUsVUN+2gnb3TaZWJwWW2jt0OjhHc4B++yYYRy1Lg2kl+WaiF+Xsc=";
        string        pubkey = "045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5";
        SHA256Managed sha256 = new SHA256Managed();

        byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(msg), 0, Encoding.UTF8.GetByteCount(msg));
        Console.WriteLine("Hash: " + ToHex(hash));
        byte[] tmpBytes = Convert.FromBase64String(sig);
        byte[] sigBytes = new byte[tmpBytes.Length - 1];
        Buffer.BlockCopy(tmpBytes, 1, sigBytes, 0, sigBytes.Length);
        int rec = (tmpBytes[0] - 27) & ~4;

        Console.WriteLine("Rec {0}", rec);
        ECPoint Q    = Recover(hash, sigBytes, rec);
        string  qstr = ToHex(Q.GetEncoded());

        Console.WriteLine("Q is same as supplied: " + qstr.Equals(pubkey));
        Console.WriteLine("Signature verified correctly: " + VerifySignature(Q.GetEncoded(), hash, sigBytes));
    }
예제 #35
0
파일: crypto.cs 프로젝트: oheil/doTimeTable
        public void Sha256ChecksumFile(string fileNamePath)
        {
            if (File.Exists(fileNamePath))
            {
                FileStream fileIO = new FileStream(fileNamePath, FileMode.Open);

                SHA256Managed sha      = new SHA256Managed();
                byte[]        checksum = sha.ComputeHash(fileIO);
                sha.Dispose();
                fileIO.Close();

                string hex = BitConverter.ToString(checksum).Replace("-", "");
                if (File.Exists(fileNamePath + ".sha256_checksum"))
                {
                    File.Delete(fileNamePath + ".sha256_checksum");
                }
                StreamWriter shachecksumfileIO = new StreamWriter(fileNamePath + ".sha256_checksum", false);
                shachecksumfileIO.Write(hex);
                shachecksumfileIO.Close();
            }
        }
예제 #36
0
        // from: http://stackoverflow.com/questions/2138429/hash-and-salt-passwords-in-c-sharp

        public static byte[] GenerateSaltedHash(string plainText, string salt)
        {
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            var saltBytes      = Encoding.UTF8.GetBytes(salt);

            HashAlgorithm algorithm = new SHA256Managed();

            byte[] plainTextWithSaltBytes =
                new byte[plainText.Length + salt.Length];

            for (int i = 0; i < plainText.Length; i++)
            {
                plainTextWithSaltBytes[i] = plainTextBytes[i];
            }
            for (int i = 0; i < salt.Length; i++)
            {
                plainTextWithSaltBytes[plainText.Length + i] = saltBytes[i];
            }

            return(algorithm.ComputeHash(plainTextWithSaltBytes));
        }
예제 #37
0
        public static string HashEmail(string inString)
        {
            if (inString == null)
            {
                return(null);
            }

            var regex =
                new Regex(
                    @"(?<alias>\A[a-z0-9!# \.$%&'*+/=?^_`{|}~-]+(?<alias>:\.[a-z0-9!# \.$%&'*+/=?^_`{|}~-]+)*)@(?<domain>(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9]))?\z", RegexOptions.CultureInvariant);
            var matches = regex.Matches(inString.Trim().ToLowerInvariant());

            if (matches.Count >= 1)
            {
                var sha       = new SHA256Managed();
                var shaString = BitConverter.ToString(sha.ComputeHash(Encoding.UTF8.GetBytes(matches[0].Groups["alias"].Value))).Replace("-", "").ToLowerInvariant();
                return(String.Concat(shaString, "@", matches[0].Groups["domain"].Value));
            }

            return(inString);
        }
예제 #38
0
        protected virtual string GetBundleSha256(string[] parts)
        {
            if (parts == null || parts.Length == 0)
            {
                throw new ArgumentException("parts");
            }

            var hash = "";

            using (SHA256 sha = new SHA256Managed())
            {
                var hashInput = "";
                foreach (var part in parts)
                {
                    hashInput += $",{part}";
                }
                var input = sha.ComputeHash(Encoding.Unicode.GetBytes(hashInput));
                hash = WebEncoders.Base64UrlEncode(input);
            }
            return(hash.ToSeoUrl());
        }
예제 #39
0
        public void DownloadVersion_InvalidHashRetryOnce()
        {
            //arrange
            var content  = Guid.NewGuid().ToByteArray();
            var sha      = new SHA256Managed();
            var checksum = sha.ComputeHash(new MemoryStream(content));
            var hash     = BitConverter.ToString(checksum).Replace("-", String.Empty);

            mockFileProxy.Setup(x => x.OpenRead(It.IsAny <string>())).Returns(() => new MemoryStream(Guid.NewGuid().ToByteArray()));
            mockFileProxy.Setup(x => x.FileExists(@"C:\invalid.txt")).Returns(true);
            mockFileProxy.Setup(x => x.ReadAllLines(@"C:\invalid.txt")).Returns(new[] { hash + " paket.exe" });
            var tempFileName = BootstrapperHelper.GetTempFile("paket");

            //act
            sut.DownloadVersion("2.57.1", "paketExeLocation", @"C:\invalid.txt");

            //assert
            mockWebProxy.Verify(x => x.DownloadFile(It.IsAny <string>(), tempFileName), Times.Exactly(2));
            mockFileProxy.Verify(x => x.CopyFile(tempFileName, "paketExeLocation", true), Times.Once);
            mockFileProxy.Verify(x => x.DeleteFile(tempFileName), Times.Once);
        }
예제 #40
0
        /// <summary>Generates Salted Hash STRING code to store passwords safely</summary>
        public static string GenerateSaltedHash(string pPlainText, string pSalt)
        {
            byte[] plainText = Encoding.UTF8.GetBytes(pPlainText);
            byte[] salt      = Encoding.UTF8.GetBytes(pSalt);

            HashAlgorithm algorithm = new SHA256Managed();

            byte[] plainTextWithSaltBytes =
                new byte[plainText.Length + salt.Length];

            for (int i = 0; i < plainText.Length; i++)
            {
                plainTextWithSaltBytes[i] = plainText[i];
            }
            for (int i = 0; i < salt.Length; i++)
            {
                plainTextWithSaltBytes[plainText.Length + i] = salt[i];
            }

            return(Convert.ToBase64String(algorithm.ComputeHash(plainTextWithSaltBytes)));
        }
예제 #41
0
        /// <summary>
        /// 获取字符串的Sha256哈希值,默认编码为<see cref="Encoding.UTF8"/>
        /// </summary>
        public static string ComputeSHA256(this string value, Encoding encoding = null)
        {
            Check.NotNull(value, nameof(value));

            var sb   = new StringBuilder();
            var hash = new SHA256Managed();

            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            var bytes = hash.ComputeHash(encoding.GetBytes(value));

            foreach (var b in bytes)
            {
                sb.AppendFormat("{0:x2}", b);
            }

            return(sb.ToString());
        }
예제 #42
0
        private string SHA(string s, WG_Hash hash)
        {
            byte[]        bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(s);
            byte[]        result;
            HashAlgorithm sha;

            switch (hash)
            {
            case WG_Hash.Sha1:
                //sha = new SHA1Managed();
                sha = new SHA256Managed();
                break;

            //WG_Hash.Sha256:
            default:
                sha = new SHA256Managed();
                break;
            }
            result = sha.ComputeHash(bytes);
            return(System.Convert.ToBase64String(result));
        }
예제 #43
0
        // Con este método realizamos el cifrado sin retorno. Devuelve una lista de Strings con los resultados de cada tipo de cifrado utilizado-
        public static List <String> CifradoHash(String text)
        {
            // Instanciamos un conversor para convertir el String recibido en un array de bytes.
            UnicodeEncoding converter = new UnicodeEncoding();

            byte[]        input  = converter.GetBytes(text);
            List <String> output = new List <String>();
            // Tipos de cifrado a utilizar
            SHA1Managed   sha1   = new SHA1Managed();   // No es recomendable.
            SHA256Managed sha256 = new SHA256Managed(); // Recomendado.
            MD5Cng        md5    = new MD5Cng();        // No es recomendable.
            SHA512Managed sha512 = new SHA512Managed(); // Muy recomendado. Pero ocupa más espacio y puede ser más lento.

            // Añadimos los resultados a la lista de Strings
            output.Add(converter.GetString(sha1.ComputeHash(input)));
            output.Add(converter.GetString(md5.ComputeHash(input)));
            output.Add(converter.GetString(sha256.ComputeHash(input)));
            output.Add(converter.GetString(sha512.ComputeHash(input)));
            // Devolvemos la lista
            return(output);
        }
 public IActionResult Sha256([FromQuery] string pMessage)
 {
     using (var pCtx = new UserContext())
     {
         this.Request.Query.TryGetValue("message", out var values);
         string verify = values.ToString();
         if (verify.IsNull() || verify == "")
         {
             return(BadRequest("Bad Request"));
         }
         var    pCrypt = new SHA256Managed();
         var    pHash  = new StringBuilder();
         byte[] crypto = pCrypt.ComputeHash(Encoding.UTF8.GetBytes(values));
         foreach (byte theByte in crypto)
         {
             // x2 will give lower case, needs to be upper
             pHash.Append(theByte.ToString("X2"));
         }
         return(Ok(pHash.ToString()));
     }
 }
예제 #45
0
        public string SHA256(string valor)
        {
            try
            {
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[]          HashValue, MessageBytes = UE.GetBytes(valor);
                SHA256Managed   SHhash = new SHA256Managed();
                string          strHex = "";

                HashValue = SHhash.ComputeHash(MessageBytes);
                foreach (byte b in HashValue)
                {
                    strHex += String.Format("{0:x2}", b);
                }
                return(strHex);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
예제 #46
0
        /// <summary>
        /// Computes a token for the specified file stream.
        /// </summary>
        /// <param name="stream">The file stream.</param>
        /// <returns>The token.</returns>
        public string ComputeToken(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            byte[] hashBytes;

            // Hash the incoming data
            using (var sha256Hash = new SHA256Managed())
            {
                stream.Position = 0;
                hashBytes       = sha256Hash.ComputeHash(stream);
            }

            stream.Position = 0;

            // Convert the hashed data to a Base32 string.
            return(Base32Encoding.ToBase32String(hashBytes));
        }
예제 #47
0
        private static string EncodePassword(string password)
        {
            string result;
            var    bytes = Encoding.Unicode.GetBytes(password);

            using (var stream = new MemoryStream())
            {
                stream.WriteByte(0);

                using (var sha256 = new SHA256Managed())
                {
                    var hash = sha256.ComputeHash(bytes);
                    stream.Write(hash, 0, hash.Length);

                    bytes  = stream.ToArray();
                    result = Convert.ToBase64String(bytes);
                }
            }

            return(result);
        }
예제 #48
0
    public static bool validateSignature(string pk, string clientData, string authnrData, string signature, string challenge)
    {
        try {
            var c = rfc4648_base64_url_decode(clientData);
            var a = rfc4648_base64_url_decode(authnrData);
            var s = rfc4648_base64_url_decode(signature);

            // Make sure the challenge in the client data matches the expected challenge
            var cc = Encoding.ASCII.GetString(c);
            cc = cc.Replace("\0", "").Trim();
            var json = new JavaScriptSerializer();
            var j    = (System.Collections.Generic.Dictionary <string, object>)json.DeserializeObject(cc);
            if ((string)j["challenge"] != challenge)
            {
                return(false);
            }

            // Hash data with sha-256
            var hash = new SHA256Managed();
            var h    = hash.ComputeHash(c);

            // Create data buffer to verify signature over
            var b = new byte[a.Length + h.Length];
            a.CopyTo(b, 0);
            h.CopyTo(b, a.Length);

            // Load public key
            j = (System.Collections.Generic.Dictionary <string, object>)json.DeserializeObject(pk);
            var keyinfo = new RSAParameters();
            keyinfo.Modulus  = rfc4648_base64_url_decode((string)j["n"]);
            keyinfo.Exponent = rfc4648_base64_url_decode((string)j["e"]);
            var rsa = new RSACng();
            rsa.ImportParameters(keyinfo);

            // Verify signature is correct for authnrData + hash
            return(rsa.VerifyData(b, s, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
        } catch (Exception) {
            return(false);
        }
    }
예제 #49
0
            public BlogPosting Sign(ICipherParameters PrivateKey)
            {
                var posting = new BlogPosting(Id,
                                              Text,
                                              PublicationDate,
                                              GeoLocation,
                                              Tags,
                                              PrivacyLevel,
                                              IsHidden,
                                              Signatures,
                                              DataSource);

                var ctext = posting.ToJSON(Embedded:           false,
                                           ExpandTags:         InfoStatus.ShowIdOnly,
                                           IncludeCryptoHash:  false).ToString(Newtonsoft.Json.Formatting.None);

                var BlockSize = 32;

                var SHA256     = new SHA256Managed();
                var SHA256Hash = SHA256.ComputeHash(ctext.ToUTF8Bytes());
                var signer     = SignerUtilities.GetSigner("NONEwithECDSA");

                signer.Init(true, PrivateKey);
                signer.BlockUpdate(SHA256Hash, 0, BlockSize);

                var signature  = signer.GenerateSignature().ToHexString();
                var signatures = new List <BlogPostingSignature>(Signatures);

                signatures.Add(new BlogPostingSignature("json", "secp256k1", "DER+HEX", signature));

                return(new BlogPosting(Id,
                                       Text,
                                       PublicationDate,
                                       GeoLocation,
                                       Tags,
                                       PrivacyLevel,
                                       IsHidden,
                                       signatures,
                                       DataSource));
            }
예제 #50
0
 public ActionResult Agregar(UsuarioCLS oUsuarioCLS)
 {
     listarComboGrupo();
     try
     {
         int numRegistroEncontrados = 0;
         using (var bd = new BDDemoLoginEntities())
         {
             numRegistroEncontrados = bd.Usuario.Where(p => p.NOMBREUSUARIO == oUsuarioCLS.nombreUsuario && p.IDUSUARIO != oUsuarioCLS.idUsuario).Count();
         }
         if (!ModelState.IsValid || numRegistroEncontrados > 1)
         {
             if (numRegistroEncontrados > 1)
             {
                 oUsuarioCLS.mensajeError = "El nombre de usuario ya existe";
             }
             return(View(oUsuarioCLS));
         }
         else
         {
             using (var bd = new BDDemoLoginEntities())
             {
                 Usuario oUsuario = new Usuario();
                 oUsuario.NOMBREUSUARIO = oUsuarioCLS.nombreUsuario;
                 SHA256Managed sha                = new SHA256Managed();
                 byte[]        byteContra         = Encoding.Default.GetBytes(oUsuarioCLS.contra);
                 byte[]        byteContraCifrada  = sha.ComputeHash(byteContra);
                 string        cadenContraCifrada = BitConverter.ToString(byteContraCifrada).Replace("-", "");
                 oUsuario.CONTRA     = cadenContraCifrada;
                 oUsuario.IDGRUPO    = oUsuarioCLS.idGrupo;
                 oUsuario.HABILITADO = 1;
                 bd.Usuario.Add(oUsuario);
                 bd.SaveChanges();
             }
         }
     }catch (Exception ex)
     {
     }
     return(RedirectToAction("Index"));
 }
        private void LoginUserExecute()
        {
            try
            {
                Service s = new Service();

                string username = login.txtUsername.Text;


                // Hash password
                var hasher         = new SHA256Managed();
                var unhashed       = Encoding.Unicode.GetBytes(login.txtPassword.Password);
                var hashed         = hasher.ComputeHash(unhashed);
                var hashedPassword = Convert.ToBase64String(hashed);

                string password = hashedPassword;

                //Checks if there is a username and password in the database
                tblUser userLogin = s.GetUsernamePassword(username, password);

                if (userLogin != null)
                {
                    LoggedGuest.Name     = userLogin.UserName;
                    LoggedGuest.Surname  = userLogin.UserSurname;
                    LoggedGuest.Username = userLogin.UserUsername;
                    LoggedGuest.Birth    = userLogin.DateOfBirth.ToString("dd.MM.yyyy");
                    LoggedGuest.Gendre   = userLogin.Gender;
                    LoggedGuest.ID       = userLogin.UserID;
                    usersLogin           = true;
                    OpenMainMenu();
                }
                else
                {
                    SnackError();
                }
            }
            catch (Exception)
            {
            }
        }
예제 #52
0
        /// <summary>
        /// Translates claims to strings
        /// </summary>
        /// <param name="claim">Claim to translate to a string</param>
        /// <returns>The string representation of a claim's value.</returns>
        internal static string GetResourceValue(Claim claim)
        {
            string strClaim = claim.Resource as string;

            if (!string.IsNullOrEmpty(strClaim))
            {
                return(strClaim);
            }

            IdentityReference reference = claim.Resource as IdentityReference;

            if (null != reference)
            {
                return(reference.Value);
            }

            ICspAsymmetricAlgorithm rsa = claim.Resource as ICspAsymmetricAlgorithm;

            if (null != rsa)
            {
                using (SHA256 sha = new SHA256Managed()) {
                    return(Convert.ToBase64String(sha.ComputeHash(rsa.ExportCspBlob(false))));
                }
            }

            MailAddress mail = claim.Resource as MailAddress;

            if (null != mail)
            {
                return(mail.ToString());
            }

            byte[] bufferValue = claim.Resource as byte[];
            if (null != bufferValue)
            {
                return(Convert.ToBase64String(bufferValue));
            }

            return(claim.Resource.ToString());
        }
예제 #53
0
        private static byte[] LoadKeyFile(string strKeyFilePath)
        {
            FileStream fs;

            try { fs = new FileStream(strKeyFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); }
            catch (Exception) { return(null); }

            long         lLength = fs.Length;
            BinaryReader br      = new BinaryReader(fs);

            byte[] pbFileData = br.ReadBytes((int)lLength);
            br.Close();
            fs.Close();

            byte[] pbKey = null;

            if (lLength == 32)
            {
                pbKey = LoadBinaryKey32(pbFileData);
            }
            else if (lLength == 64)
            {
                pbKey = LoadHexKey32(pbFileData);
            }

            if (pbKey == null)
            {
                if (pbFileData.Length == lLength)
                {
                    SHA256Managed sha256 = new SHA256Managed();
                    pbKey = sha256.ComputeHash(pbFileData);
                }
                else
                {
                    Debug.Assert(false); pbKey = null;
                }
            }

            return(pbKey);
        }
예제 #54
0
        public string ComputeHash(string text)
        {
            byte[] saltBytes = this._hashParameters.Salt;

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

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

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

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

            // Compute hash value of our text with appended salt.
            byte[] hashBytes = textWithSaltBytes;

            // Initialize hashing algorithm class.
            using (HashAlgorithm hash = new SHA256Managed())
            {
                for (int i = 0; i < this._hashParameters.Iterations; i++)
                {
                    hashBytes = hash.ComputeHash(hashBytes);
                }
            }

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

            // Return the result.
            return(hashValue);
        }
예제 #55
0
 protected void btZaloguj_Click(object sender, EventArgs e)
 {
     if (Page.IsValid)
     {
         SqlConnection con = null;
         SqlCommand    cmd;
         SqlParameter  param;
         con = new SqlConnection(ConfigurationManager.ConnectionStrings["SRSConnectionString"].ConnectionString);
         con.Open();
         cmd = con.CreateCommand();
         // This will specify that we are passing the stored procedures name
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.CommandText = "AddUser"; // This will be the stored procedures name
         param           = new SqlParameter("@login", tbLogin.Text);
         cmd.Parameters.Add(param);
         SHA256Managed SHA      = new SHA256Managed();
         byte[]        pass     = Encoding.UTF8.GetBytes(tbHaslo.Text);
         byte[]        hashPass = SHA.ComputeHash(pass);
         StringBuilder sb       = new StringBuilder();
         foreach (byte b in hashPass)
         {
             sb.Append(b.ToString("X2"));
         }
         param = new SqlParameter("@haslo", sb.ToString());
         cmd.Parameters.Add(param);
         param = new SqlParameter("@nazwisko", tbNazwisko.Text);
         cmd.Parameters.Add(param);
         param = new SqlParameter("@imie", tbImie.Text);
         cmd.Parameters.Add(param);
         param = new SqlParameter("@kontakt", tbKontakt.Text);
         cmd.Parameters.Add(param);
         param = new SqlParameter("@rola", tbRola.Text);
         cmd.Parameters.Add(param);
         param = new SqlParameter("@uprawnienia", "0");
         cmd.Parameters.Add(param);
         cmd.ExecuteNonQuery();
         con.Close();
         Response.Redirect("RegisterComplete.aspx");
     }
 }
예제 #56
0
            /// <summary>
            /// Generates a DID, Given the dept name
            /// </summary>
            /// <param name="deptName"></param>
            /// <returns></returns>
            public static string DID(string deptName, string STRID)
            {
                var id = "Dpt" + (
                    Convert.ToBase64String(
                        hasher.ComputeHash(
                            Encoding.ASCII.GetBytes(deptName + STRID))).Substring(0, 10) +
                    Convert.ToBase64String(
                        Encoding.ASCII.GetBytes(deptName))).Substring(0, 10);

                if (!filter.CheckFor(id))
                {
                    filter.AddItem(id);
                }

                return(id.Replace("/", "c").Replace("=", "b").Replace("+", "A").Replace("\\", "C"));
            }
    //this method checks that passwords match in a login attempt
    public bool checkPassword()
    {
        Credentials userCredentials = UserDao.getUserCredentials(username);
        if (userCredentials != null)
        {
            byte[] dbPass = Convert.FromBase64String(userCredentials.getPassword());

            byte[] userPass = createByteArrayFromString(password);
            byte[] dbSalt = createByteArrayFromString(userCredentials.getSalt());

            byte[] userSaltedPass = userPass.Concat(dbSalt).ToArray();

            HashAlgorithm algorithm = new SHA256Managed();
            byte[] hasheduserPass = algorithm.ComputeHash(userSaltedPass);

            bool match = compareByteArrays(dbPass, hasheduserPass);

            return match;
        }
        else
        {
            return false;
        }
    }
예제 #58
0
 protected virtual byte[] getHash()
 {
     var hashIterations = 242;
     List<byte> hashList = new List<byte>();
     var hash = new SHA256Managed();
     var hashLength = Math.Max(plaintext.Length, cyphertext.Length);
     while (hashList.Count <= hashLength)
     {
         byte[] hashBytes = hash.ComputeHash(key);
         for (var i = 1; i < hashIterations; i++)
         {
             hashBytes = hash.ComputeHash(hashBytes);
         }
         hashList.AddRange(hashBytes);
     }
     return hashList.ToArray();
 }
예제 #59
0
    /// <summary>
    /// Generates the signature for the V2 API request based on the given parameters. <seealso cref="http://api.ooyala.com/v2/docs"/>
    /// </summary>
    /// <param name="SecretKey">Ooyala Backlot Secret Key</param>
    /// <param name="APIKey">Ooyala Backlot API Key</param>
    /// <param name="HTTPMethod">
    /// The method to be used for the request. Possible values are: GET, POST, PUT, PATCH or DELETE
    /// </param>
    /// <param name="path">
    /// The path to use for the request
    /// </param>
    /// <param name="sortedParameterKeys">
    /// A sorted array containing the keys of the parameters hash. This is to improve efficiency and not sort them twice since generateURL already does it.
    /// </param>
    /// <param name="parameters">
    /// A hash containing the list of parameters that will be included in the request.
    /// </param>
    /// <param name="body">
    /// A string containing the JSON representation of the data to be sent on the request. If its a GET request, the body parameter will not be used to generate the signature.
    /// </param>
    /// <returns>
    /// A string containing the signature to be used in the V2 API request.
    /// </returns>
    private static string generateRequestSignature(string SecretKey, string HTTPMethod, String path, String[] sortedParameterKeys, Dictionary<String, String> parameters, String body)
    {
        var stringToSign = SecretKey + HTTPMethod + path;

        for (int i = 0; i < sortedParameterKeys.Length; i++)
        {
            stringToSign += sortedParameterKeys[i] + "=" + parameters[sortedParameterKeys[i]];
        }

        stringToSign += body;

        var sha256 = new SHA256Managed();
        byte[] digest = sha256.ComputeHash(Encoding.Default.GetBytes(stringToSign));
        string signedInput = Convert.ToBase64String(digest);

        var lastEqualsSignindex = signedInput.Length - 1;
        while (signedInput[lastEqualsSignindex] == '=')
        {
            lastEqualsSignindex--;
        }

        signedInput = signedInput.Substring(0, lastEqualsSignindex + 1);

        return HttpUtility.UrlEncode(signedInput.Substring(0, 43));
    }
    private bool Login(string password, string userid)
    {
        bool success = false;
        string sql = "dbo.proc_login_getvector";
        string ConnectionString = "Initial Catalog=PMSInterface;Data Source=smvcdbsvr00\\smvcdbsvr01;User Id=SMVCwebservice;Password=smvc2009;Application Name=TSW_Only;Connection Timeout=5";

        SqlConnection conn = new SqlConnection(ConnectionString);
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        SqlParameter param1 = cmd.Parameters.Add(new SqlParameter("email", SqlDbType.NVarChar, 200));
        SqlParameter param2 = cmd.Parameters.Add(new SqlParameter("FromLive", SqlDbType.Int, 1));
        param1.Value = userid;
        param2.Value = m_FromLive;

        try
        {
            UserName_tblUser = "";
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                byte[] dbvector = (byte[])dr["vector"];                             // vector of user as previously saved

                byte[] dbpwd = (byte[])dr["password"];                              // SHA of user (pwd + vector)

                string dbAccessLevel = (string)dr["AccessLevel"];
                //Session.Add("AccessLevel", dbAccessLevel);
                Session["AccessLevel"] = dbAccessLevel;

                UserName_tblUser = (string)dr["UserName_tblUser"];

                if (dr["SiteID"] != DBNull.Value && dr["SiteID"] != null)
                {
                    int dbSiteID = (int)dr["SiteID"];
                    //Session.Add("SiteID", dbSiteID);
                    Session["SiteID"] = dbSiteID;
                    //Session.Add("UserName_tblUser",(string)dr["UserName_tblUser"]);
                }
                else
                {
                    //throw new Exception("SYS Null Value");
                    Response.Redirect("login.aspx?m_error=Invalid_SiteID_for_user");
                }

                dr.Close();
                conn.Close();

                byte[] pwdBytes = System.Text.UTF8Encoding.UTF8.GetBytes(password); // user provided password in bytes
                byte[] pwdAndVector = AddBytes(pwdBytes, dbvector);                 // user pwd + dabatase vector

                SHA256Managed sha = new SHA256Managed();
                byte[] hashPassword = sha.ComputeHash(pwdAndVector);                // SHA of user (pwd + vector)

                return (BitConverter.ToString(hashPassword) == BitConverter.ToString(dbpwd));                                     // Is this what we are expecting?
            }

        }
        catch (Exception ex)
        {
            throw new Exception(ex.GetBaseException().Message);
        }

        return success;
    }