コード例 #1
1
    // Use this for initialization
    void Start () {
        Rfc2898DeriveBytes PBKDF2_hash = new Rfc2898DeriveBytes("qwerty", Encoding.ASCII.GetBytes("rm4fSDh0sofK"), 20000);
        HMACSHA256 HMACSHA256_hash = new HMACSHA256();
        //System.Text.Encoding.UTF8.GetString(bytes);
        string hPassword = Convert.ToBase64String(PBKDF2_hash.GetBytes(32));
        Debug.Log("Hash = " + hPassword);
        //Debug.Log("Password hash" + Encoding.ASCII.GetString(PBKDF2.GetBytes(256)));
        //PBKDF2.Salt = 


        /*string password = "******";
        string hPassword = ComputeHash(password, new SHA256CryptoServiceProvider());
        Debug.Log("Hash from: " + password + " = " + hPassword);*/
    }
    //This method is to encrypt the password given by user.
    public static string Encrypt(string data, string password)
    {
        if (String.IsNullOrEmpty(data))
            throw new ArgumentException("No data given");
        if (String.IsNullOrEmpty(password))
            throw new ArgumentException("No password given");

        // setup the encryption algorithm
        Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, 8);
        TripleDES tdes = TripleDES.Create();
        //Rijndael aes = Rijndael.Create();

        tdes.IV = keyGenerator.GetBytes(tdes.BlockSize / 8);
        tdes.Key = keyGenerator.GetBytes(tdes.KeySize / 8);

        // encrypt the data
        byte[] rawData = Encoding.Unicode.GetBytes(data);
        using (MemoryStream memoryStream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateEncryptor(), CryptoStreamMode.Write))
        {
            memoryStream.Write(keyGenerator.Salt, 0, keyGenerator.Salt.Length);
            cryptoStream.Write(rawData, 0, rawData.Length);
            cryptoStream.Close();

            byte[] encrypted = memoryStream.ToArray();
            return Convert.ToBase64String(encrypted);
        }
    }
コード例 #3
0
    internal static bool DecryptFile(string inputPath, string outputPath, string password)
    {
        var input = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
        var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write);

        // Essentially, if you want to use RijndaelManaged as AES you need to make sure that:
        // 1.The block size is set to 128 bits
        // 2.You are not using CFB mode, or if you are the feedback size is also 128 bits
        RijndaelManaged algorithm = new RijndaelManaged {KeySize = 256, BlockSize = 128};

        algorithm.Mode = CipherMode.CBC;

        var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(Salt));

        algorithm.Key = key.GetBytes(algorithm.KeySize/8);
        algorithm.IV = key.GetBytes(algorithm.BlockSize/8);

        try
        {
        using (var decryptedStream = new CryptoStream(output, algorithm.CreateDecryptor(), CryptoStreamMode.Write))
        {
        CopyStream(input, decryptedStream);
        return true;
        }
        }
        catch (CryptographicException)
        {
        throw new InvalidDataException("Please supply a correct password");
        }
        catch (Exception ex)
        {
        throw new Exception(ex.Message);
        }
    }
    //This method is to decrypt the password given by user.
    public static string Decrypt(string data, string password)
    {
        if (String.IsNullOrEmpty(data))
            throw new ArgumentException("No data given");
        if (String.IsNullOrEmpty(password))
            throw new ArgumentException("No password given");

        byte[] rawData = Convert.FromBase64String(data.Replace(" ", "+"));
        if (rawData.Length < 8)
            throw new ArgumentException("Invalid input data");

        // setup the decryption algorithm
        byte[] salt = new byte[8];
        for (int i = 0; i < salt.Length; i++)
            salt[i] = rawData[i];

        Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, salt);

        TripleDES tdes = TripleDES.Create();
        //Rijndael aes = Rijndael.Create();

        tdes.IV = keyGenerator.GetBytes(tdes.BlockSize / 8);
        tdes.Key = keyGenerator.GetBytes(tdes.KeySize / 8);
        // decrypt the data
        using (MemoryStream memoryStream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateDecryptor(), CryptoStreamMode.Write))
        {
            cryptoStream.Write(rawData, 8, rawData.Length - 8);
            cryptoStream.Close();

            byte[] decrypted = memoryStream.ToArray();
            return Encoding.Unicode.GetString(decrypted);
        }
    }
コード例 #5
0
ファイル: SimpleAES256.cs プロジェクト: JorgMU/AES256
    public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
    {
        byte[] encryptedBytes = null;

        // Set your salt here, change it to meet your flavor:
        // The salt bytes must be at least 8 bytes.
        byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

        using (MemoryStream ms = new MemoryStream())
        {
          using (RijndaelManaged AES = new RijndaelManaged())
          {
        AES.KeySize = 256;
        AES.BlockSize = 128;

        var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
        AES.Key = key.GetBytes(AES.KeySize / 8);
        AES.IV = key.GetBytes(AES.BlockSize / 8);

        AES.Mode = CipherMode.CBC;

        using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
        {
          cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
          cs.Close();
        }
        encryptedBytes = ms.ToArray();
          }
        }

        return encryptedBytes;
        //end public byte[] AES_Encrypt
    }
コード例 #6
0
ファイル: Encrypter.cs プロジェクト: RyanShaul/dig
 public static string Encrypt(string clearText)
 {
     byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(_Pwd, _Salt);
         byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
         return Convert.ToBase64String(encryptedData);
 }
コード例 #7
0
ファイル: Encrypter.cs プロジェクト: RyanShaul/dig
 public static string Decrypt(string cipherText)
 {
     byte[] cipherBytes = Convert.FromBase64String(cipherText);
         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(_Pwd, _Salt);
         byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
         return System.Text.Encoding.Unicode.GetString(decryptedData);
 }
コード例 #8
0
ファイル: Encryption.cs プロジェクト: Syriamanal/xprotect
    public static byte[] Encrypt(byte[] data, string password)
    {
        byte[] result = null;
            byte[] passwordBytes = Encoding.Default.GetBytes(password);

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = keySize;
                    AES.BlockSize = 128;
                    var key = new Rfc2898DeriveBytes(passwordBytes, salt, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);
                    AES.Mode = CipherMode.CBC;
                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(data, 0, data.Length);
                        cs.Close();
                    }
                    result = ms.ToArray();
                }

            }
            return result;
    }
コード例 #9
0
ファイル: KeyGen.cs プロジェクト: allanckw/GEMS-Web
    static KeyGen()
    {
        //We create the Rfc2898DerveBytes once as Rfc2898DeriveBytes uses a pseudo-random number generator based on HMACSHA1.

        rfcKeyGen = new Rfc2898DeriveBytes(seedToUse, SALT);
        //When calling GetBytes it initializes a new instance of HMAC, Later calls to GetBytes does not need to do this.
        key = rfcKeyGen.GetBytes(32);
        //Generate Initialization Vector - This will be less expensive as we have already intialized Rfc2898DeriveBytes
        initVector = rfcKeyGen.GetBytes(16);
    }
コード例 #10
0
ファイル: MyHelper.cs プロジェクト: raazalok/IntranetHome
 static MyHelper()
 {
     //We create the Rfc2898DerveBytes once as
     //Rfc2898DeriveBytes uses a pseudo-random number generator based on HMACSHA1.
     //When calling GetBytes it initializes a new instance of HMAC which takes some time.
     //Subsequent calls to GetBytes does not need to do this initialization.
     keyGenerator = new Rfc2898DeriveBytes(ENCRYPTION_KEY, SALT);
     key = keyGenerator.GetBytes(32);
     //Generate Initialization Vector - This will be less expensive as we have already intialized Rfc2898DeriveBytes
     iv = keyGenerator.GetBytes(16);
 }
コード例 #11
0
ファイル: Crypto.cs プロジェクト: JJJohan/RTS
    private ICryptoTransform InitDecrypt(string a_key)
    {
        byte[] keyBytes = Encoding.Unicode.GetBytes(a_key);
        Rfc2898DeriveBytes derivedKey = new Rfc2898DeriveBytes(a_key, keyBytes);

        RijndaelManaged rijndaelCSP = new RijndaelManaged();
        rijndaelCSP.Key = derivedKey.GetBytes(rijndaelCSP.KeySize / 8);
        rijndaelCSP.IV = derivedKey.GetBytes(rijndaelCSP.BlockSize / 8);
        ICryptoTransform decryptor = rijndaelCSP.CreateDecryptor();
        rijndaelCSP.Clear();
        return decryptor;
    }
コード例 #12
0
ファイル: Crypto.cs プロジェクト: crawford/WpGatekeeper
    /// <summary>
    /// Decrypt the given string.  Assumes the string was encrypted using 
    /// EncryptStringAES(), using an identical sharedSecret.
    /// </summary>
    /// <param name="cipherText">The text to decrypt.</param>
    /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
    public static string DecryptStringAES(string cipherText, string sharedSecret)
    {
        if (string.IsNullOrEmpty(cipherText))
            throw new ArgumentNullException("cipherText");
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        // Declare the RijndaelManaged object
        // used to decrypt the data.
        AesManaged aesAlg = null;

        // Declare the string used to hold
        // the decrypted text.
        string plaintext = null;

        try
        {
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

            // Create a RijndaelManaged object
            // with the specified key and IV.
            aesAlg = new AesManaged();
            aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
            aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
            // Create the streams used for decryption.
            byte[] bytes = Convert.FromBase64String(cipherText);
            using (MemoryStream msDecrypt = new MemoryStream(bytes))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                }
            }
        }
        finally
        {
            // Clear the RijndaelManaged object.
            if (aesAlg != null)
                aesAlg.Clear();
        }

        return plaintext;
    }
コード例 #13
0
ファイル: Crypto.cs プロジェクト: mgerasika/portmone-app
    public static string Decrypt(this string text, string lKey)
    {
        try
        {
            using (Aes aes = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey));
                aes.Key = deriveBytes.GetBytes(128 / 8);
                aes.IV = aes.Key;

                using (MemoryStream decryptionStream = new MemoryStream())
                {
                    using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        byte[] encryptedData = Convert.FromBase64String(text);


                        decrypt.Write(encryptedData, 0, encryptedData.Length);
                        decrypt.Flush();
                    }

                    byte[] decryptedData = decryptionStream.ToArray();
                    string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);


                    return decryptedText;
                }
            }
        }
        catch
        {
            return String.Empty;
        }
    }
コード例 #14
0
    public bool TryDecrypt(string encryptedItem, string password, out string decryptedItem)
    {
        if (string.IsNullOrEmpty (encryptedItem) ||
            string.IsNullOrEmpty (password)) {
            decryptedItem = "";
            return false;
        }

        try {
            byte[] cipherBytes = Convert.FromBase64String (encryptedItem);

            using (var memoryStream = new MemoryStream(cipherBytes)) {
                var des = new DESCryptoServiceProvider ();

                byte[] iv = new byte[8];
                memoryStream.Read (iv, 0, iv.Length);

                var rfc2898DeriveBytes = new Rfc2898DeriveBytes (password, iv, ITERATIONS);

                byte[] key = rfc2898DeriveBytes.GetBytes (8);

                using (var cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream)) {
                    decryptedItem = streamReader.ReadToEnd ();
                    return true;
                }
            }
        } catch (Exception ex) {
            Logger.instance.Log (new Logger.Message (this, ex));

            decryptedItem = "";
            return false;
        }
    }
コード例 #15
0
    public string Encrypt(string item, string password)
    {
        if (item == null) {
            throw new ArgumentNullException ("item");
        }

        if (string.IsNullOrEmpty (password)) {
            throw new ArgumentNullException ("password");
        }

        var des = new DESCryptoServiceProvider ();

        des.GenerateIV ();

        var rfc2898DeriveBytes = new Rfc2898DeriveBytes (password, des.IV, ITERATIONS);

        byte[] key = rfc2898DeriveBytes.GetBytes (8);

        using (var memoryStream = new MemoryStream()) {
            using (var cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(key, des.IV), CryptoStreamMode.Write)) {
                memoryStream.Write (des.IV, 0, des.IV.Length);

                byte[] bytes = Encoding.UTF8.GetBytes (item);

                cryptoStream.Write (bytes, 0, bytes.Length);
                cryptoStream.FlushFinalBlock ();

                return Convert.ToBase64String (memoryStream.ToArray ());
            }
        }
    }
コード例 #16
0
ファイル: Crypto.cs プロジェクト: mgerasika/portmone-app
    public static string Encrypt(this string text, string lKey)
    {
        try
        {
            using (Aes aes = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey));
                aes.Key = deriveBytes.GetBytes(128 / 8);
                aes.IV = aes.Key;
                using (MemoryStream encryptionStream = new MemoryStream())
                {
                    using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] cleanText = Encoding.UTF8.GetBytes(text);
                        encrypt.Write(cleanText, 0, cleanText.Length);
                        encrypt.FlushFinalBlock();
                    }

                    byte[] encryptedData = encryptionStream.ToArray();
                    string encryptedText = Convert.ToBase64String(encryptedData);


                    return encryptedText;
                }
            }
        }
        catch
        {
            return String.Empty;
        }
    }
コード例 #17
0
 private static byte[] PBKDF2(string password, byte[] salt, int interations,
     int outputBytes)
 {
     Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt);
     pbkdf2.IterationCount = interations;
     return pbkdf2.GetBytes(outputBytes);
 }
コード例 #18
0
    internal static SecurePassword GetSaltHash(string password) {

        Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, 20);
        byte[] salt = deriveBytes.Salt;
        byte[] pass = deriveBytes.GetBytes(20);
        return new SecurePassword(Convert.ToBase64String(pass), Convert.ToBase64String(salt));
    }
コード例 #19
0
ファイル: TokenUtility.cs プロジェクト: kazeemkz/silverdale
    public static string GenerateUrlToken(string controllerName, string actionName, RouteValueDictionary argumentParams, string password)
    {
        //// The URL hash is dynamic by assign a dynamic key in each session. So
        //// eventhough your URL is stolen, it will not work in other session
        if (HttpContext.Current.Session["url_dynamickey"] == null)
        {
            HttpContext.Current.Session["url_dynamickey"] = RandomString();
        }

        // The salt include the dynamic session key and valid for an hour.
        var salt = HttpContext.Current.Session["url_dynamickey"] + DateTime.Now.ToShortDateString() + " " + DateTime.Now.Hour;

        // generating the partial url
        var stringToToken = controllerName + "/" + actionName + "/";
        stringToToken = argumentParams.Where(item => item.Key != "controller" && item.Key != "action" && item.Key != "urltoken").Aggregate(stringToToken, (current, item) => current + (item.Value));

        // Converting the salt in to a byte array
        var saltValueBytes = System.Text.Encoding.ASCII.GetBytes(salt);

        // Encrypt the salt bytes with the password
        var key = new Rfc2898DeriveBytes(password, saltValueBytes);

        // get the key bytes from the above process
        var secretKey = key.GetBytes(16);

        // generate the hash
        var tokenHash = new HMACSHA1(secretKey);
        tokenHash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(stringToToken));

        // convert the hash to a base64string
        var token = Convert.ToBase64String(tokenHash.Hash).Replace("/", "_");

        return token;
    }
コード例 #20
0
ファイル: aesEncrypt.cs プロジェクト: kkrnt/decryptPassword
 public string decrypt(byte[] cipherText, string ivCode16, string pass8, string salt8)
 {
     var num = 256;
     var bytes = Encoding.ASCII.GetBytes(ivCode16);
     var rfc2898DeriveBytes = new Rfc2898DeriveBytes(pass8, Encoding.ASCII.GetBytes(salt8));
     var bytes2 = rfc2898DeriveBytes.GetBytes(num/8);
     return decryptStringFromBytes_AES(cipherText, bytes2, bytes);
 }
コード例 #21
0
ファイル: aesEncrypt.cs プロジェクト: kkrnt/decryptPassword
 public byte[] encrypt(string plainText, string ivCode16, string pass8, string salt8)
 {
     var num = 256;
     var bytes = Encoding.ASCII.GetBytes(ivCode16);
     var rfc2898DeriveBytes = new Rfc2898DeriveBytes(pass8, Encoding.ASCII.GetBytes(salt8));
     var bytes2 = rfc2898DeriveBytes.GetBytes(num/8);
     return encryptStringToBytes_AES(plainText, bytes2, bytes);
 }
コード例 #22
0
ファイル: Sifreleme.cs プロジェクト: hguldal/bltdrs
 public static string Coz(string cipherText)
 {
     string EncryptionKey = System.Configuration.ConfigurationManager.AppSettings["AESKey"];
     byte[] cipherBytes = Convert.FromBase64String(cipherText);
     using (Aes encryptor = Aes.Create())
     {
         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
         encryptor.Key = pdb.GetBytes(32);
         encryptor.IV = pdb.GetBytes(16);
         using (MemoryStream ms = new MemoryStream())
         {
             using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
             {
                 cs.Write(cipherBytes, 0, cipherBytes.Length);
                 cs.Close();
             }
             cipherText = Encoding.Unicode.GetString(ms.ToArray());
         }
     }
     return cipherText;
 }
コード例 #23
0
 public string Encrypt(string clearText)
 {
     string EncryptionKey = "123CARTRADING456";
     byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
     using (Aes encryptor = Aes.Create())
     {
         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
         encryptor.Key = pdb.GetBytes(32);
         encryptor.IV = pdb.GetBytes(16);
         using (MemoryStream ms = new MemoryStream())
         {
             using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
             {
                 cs.Write(clearBytes, 0, clearBytes.Length);
                 cs.Close();
             }
             clearText = Convert.ToBase64String(ms.ToArray());
         }
     }
     return clearText;
 }
コード例 #24
0
 public string Common_Encrypt(string clearText)
 {
     string EncryptionKey = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
     byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
     using (Aes encryptor = Aes.Create())
     {
         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
         encryptor.Key = pdb.GetBytes(32);
         encryptor.IV = pdb.GetBytes(16);
         using (MemoryStream ms = new MemoryStream())
         {
             using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
             {
                 cs.Write(clearBytes, 0, clearBytes.Length);
                 cs.Close();
             }
             clearText = Convert.ToBase64String(ms.ToArray());
         }
     }
     return clearText;
 }
コード例 #25
0
    static SecurityPlayerPrefs()
    {
        // 8 바이트로 하고, 변경해서 쓸것
        byte[] saltBytes = new byte[] { 25, 36, 77, 51, 43, 14, 75, 93 };

        // 길이 상관 없고, 키를 만들기 위한 용도로 씀
        string randomSeedForKey = "5b6fcb4aaa0a42acae649eba45a506ec";

        // 길이 상관 없고, aes에 쓸 key 와 iv 를 만들 용도
        string randomSeedForValue = "2e327725789841b5bb5c706d6b2ad897";

        {
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(randomSeedForKey, saltBytes, 1000);
            _saltForKey = System.Convert.ToBase64String(key.GetBytes(blockSize / 8));
        }

        {
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(randomSeedForValue, saltBytes, 1000);
            _keys = key.GetBytes(keySize / 8);
            _iv = key.GetBytes(blockSize / 8);
        }
    }
コード例 #26
0
ファイル: AESK.cs プロジェクト: neerajbattish/files1
 public string Encrypt(string clearText)
  {
      string EncryptionKey = clearText;
      byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
      using (Aes encryptor = Aes.Create())
      {
          Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
          encryptor.Key = pdb.GetBytes(32);
          encryptor.IV = pdb.GetBytes(16);
          using (MemoryStream ms = new MemoryStream())
          {
              using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
              {
                  cs.Write(clearBytes, 0, clearBytes.Length);
                  cs.Close();
              }
              clearText = Convert.ToBase64String(ms.ToArray());
          }
      }
      var randoma = new Random();
      var resulta = new string(Enumerable.Repeat(clearText, 16).Select(s => s[randoma.Next(s.Length)]).ToArray());
      return resulta;
  }
コード例 #27
0
ファイル: Encrypt.cs プロジェクト: eddy8/eddy
 // Methods
 public static string sEncrypt(string input)
 {
     try
     {
         byte[] buffer = Encoding.UTF8.GetBytes(input);
         byte[] salt = Encoding.UTF8.GetBytes("JvghbGSkkss");
         AesManaged managed = new AesManaged();
         Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes("eegclub", salt);
         managed.BlockSize = managed.LegalBlockSizes[0].MaxSize;
         managed.KeySize = managed.LegalKeySizes[0].MaxSize;
         managed.Key = bytes.GetBytes(managed.KeySize / 8);
         managed.IV = bytes.GetBytes(managed.BlockSize / 8);
         ICryptoTransform transform = managed.CreateEncryptor();
         MemoryStream stream = new MemoryStream();
         CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write);
         stream2.Write(buffer, 0, buffer.Length);
         stream2.Close();
         return Convert.ToBase64String(stream.ToArray());
     }
     catch
     {
         return "";
     }
 }
コード例 #28
0
    public static SqlString HashPassword(string password)
    {
        if (password == null) throw new ArgumentNullException("password");
        byte[] salt;
        byte[] bytes;
        Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, 16, 1000);

        salt = rfc2898DeriveBytes.Salt;
        bytes = rfc2898DeriveBytes.GetBytes(32);

        byte[] array = new byte[49];
        Buffer.BlockCopy(salt, 0, array, 1, 16);
        Buffer.BlockCopy(bytes, 0, array, 17, 32);

        return new SqlString(Convert.ToBase64String(array));
    }
コード例 #29
0
ファイル: DESEncryption.cs プロジェクト: Doychev/RunningBack
    public bool TryDecrypt(string cipherText, string password, out string plainText)
    {
        // its pointless trying to decrypt if the cipher text
        // or password has not been supplied
        if (string.IsNullOrEmpty(cipherText) ||
            string.IsNullOrEmpty(password))
        {
            plainText = "";
            return false;
        }

        try
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);

            using (var memoryStream = new MemoryStream(cipherBytes))
            {
                // create instance of the DES crypto provider
                var des = new DESCryptoServiceProvider();

                // get the IV
                byte[] iv = new byte[8];
                memoryStream.Read(iv, 0, iv.Length);

                // use derive bytes to generate key from password and IV
                var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, iv, Iterations);

                byte[] key = rfc2898DeriveBytes.GetBytes(8);

                using (var cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream))
                {
                    plainText = streamReader.ReadToEnd();
                    return true;
                }
            }
        }
        catch (Exception ex)
        {
            // TODO: log exception
            Console.WriteLine(ex);

            plainText = "";
            return false;
        }
    }
コード例 #30
0
        public string Decrypt(string password)
        {
            var saltSize   = 16;
            var keySize    = 32;
            var iterations = 10000;

            byte[] key;
            byte[] data = Convert.FromBase64String(password);

            using (var algorithm = new Rfc2898DeriveBytes(password, saltSize, iterations, HashAlgorithmName.SHA512))
            {
                key = algorithm.GetBytes(keySize);
            }

            using (TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider())
            {
                tdes.Key     = key;
                tdes.Mode    = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;
                byte[] output = tdes.CreateDecryptor().TransformFinalBlock(data, 0, data.Length);
                tdes.Clear();
                return(UTF32Encoding.UTF32.GetString(output));
            }
        }
コード例 #31
0
    /// <summary>
    /// verify a password against a hash
    /// </summary>
    /// <param name="password">the password</param>
    /// <param name="hashedPassword">the hash</param>
    /// <returns>could be verified?</returns>
    public static bool Verify(string password, string hashedPassword)
    {
        //check hash
        if (!IsHashSupported(hashedPassword))
        {
            throw new NotSupportedException("The hashtype is not supported");
        }

        //extract iteration and Base64 string
        var splittedHashString = hashedPassword.Replace("$FIXHASH$V1$", "").Split('$');
        var iterations         = int.Parse(splittedHashString[0]);
        var base64Hash         = splittedHashString[1];

        //get hashbytes
        var hashBytes = Convert.FromBase64String(base64Hash);

        //get salt
        var salt = new byte[SaltSize];

        Array.Copy(hashBytes, 0, salt, 0, SaltSize);

        //create hash with given salt
        var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);

        byte[] hash = pbkdf2.GetBytes(HashSize);

        //get result
        for (var i = 0; i < HashSize; i++)
        {
            if (hashBytes[i + SaltSize] != hash[i])
            {
                return(false);
            }
        }
        return(true);
    }
コード例 #32
0
        public byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)
        {
            //User Error Checks
            if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
            {
                throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");
            }

            if (encryptedMessage == null || encryptedMessage.Length == 0)
            {
                throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
            }

            var cryptSalt = new byte[SaltBitSize / 8];
            var authSalt  = new byte[SaltBitSize / 8];

            //Grab Salt from Non-Secret Payload
            Array.Copy(encryptedMessage, nonSecretPayloadLength, cryptSalt, 0, cryptSalt.Length);
            Array.Copy(encryptedMessage, nonSecretPayloadLength + cryptSalt.Length, authSalt, 0, authSalt.Length);

            byte[] cryptKey;
            byte[] authKey;

            //Generate crypt key
            using (var generator = new Rfc2898DeriveBytes(password, cryptSalt, Iterations))
            {
                cryptKey = generator.GetBytes(KeyBitSize / 8);
            }
            //Generate auth key
            using (var generator = new Rfc2898DeriveBytes(password, authSalt, Iterations))
            {
                authKey = generator.GetBytes(KeyBitSize / 8);
            }

            return(SimpleDecrypt(encryptedMessage, cryptKey, authKey, cryptSalt.Length + authSalt.Length + nonSecretPayloadLength));
        }
コード例 #33
0
        public static string Hash(string password)
        {
            // salt
            int iterations = 10000;

            byte[] salt;
            new RNGCryptoServiceProvider().GetBytes(salt = new byte[SaltSize]);

            // hash
            var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
            var hash   = pbkdf2.GetBytes(HashSize);

            // combine salt and hash
            var hashBytes = new byte[SaltSize + HashSize];

            Array.Copy(salt, 0, hashBytes, 0, SaltSize);
            Array.Copy(hash, 0, hashBytes, SaltSize, HashSize);

            // convert to base64
            var base64Hash = Convert.ToBase64String(hashBytes);

            //format hash
            return(iterations.ToString() + "$" + base64Hash.ToString());
        }
コード例 #34
0
        /// <summary>
        /// Retuns whether password and hash match
        /// </summary>
        /// <param name="entry_password"></param>
        /// <param name="saved_hash"></param>
        /// <returns></returns>
        public static bool Verify(string entry_password, string saved_hash)
        {
            try
            {
                byte[] hashBytes = Convert.FromBase64String(saved_hash);
                byte[] salt      = new byte[SaltSize];
                Array.Copy(hashBytes, 0, salt, 0, SaltSize);
                var    pbkdf2 = new Rfc2898DeriveBytes(entry_password, salt, HashIter);
                byte[] hash   = pbkdf2.GetBytes(HashSize);

                for (int i = 0; i < HashSize; i++)
                {
                    if (hashBytes[i + SaltSize] != hash[i])
                    {
                        return(false);
                    }
                }
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
コード例 #35
0
        internal string Decrypt(string cipherText, string password, string saltBase64Text, int passwordIterations,
                                string initializationVector, KeySize keySize)
        {
            if (initializationVector.Length != 16)
            {
                throw new ArgumentException("initializationVector parameter length must be 16.");
            }
            var initializationVectorBytes = Encoding.ASCII.GetBytes(initializationVector);
            var saltValueBytes            = Encoding.ASCII.GetBytes(saltBase64Text);
            var cipherTextBytes           = Convert.FromBase64String(cipherText);
            var derivedPassword           = new Rfc2898DeriveBytes(password, saltValueBytes, passwordIterations);
            var keyBytes = derivedPassword.GetBytes((int)keySize / 8);

            var symmetricKey = new RijndaelManaged
            {
                Mode = CipherMode.CBC
            };

            var plainTextBytes = new byte[cipherTextBytes.Length];
            int byteCount;

            using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, initializationVectorBytes))
            {
                using (var memStream = new MemoryStream(cipherTextBytes))
                {
                    using (var cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
                    {
                        byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }

            return(Encoding.UTF8.GetString(plainTextBytes, 0, byteCount));
        }
コード例 #36
0
        public static bool Validate(string dbPassword, string inputText)
        {
            var returnValue = true;

            //Extract the bytes
            byte[] hashBytes = Convert.FromBase64String(dbPassword);
            //Get the salt
            byte[] salt = new byte[16];
            Array.Copy(hashBytes, 0, salt, 0, 16);
            //Compute the hash on the password the user entered
            var pbkdf2 = new Rfc2898DeriveBytes(inputText, salt, 10000);

            byte[] hash = pbkdf2.GetBytes(20);
            //Compare the results
            for (int i = 0; i < 20; i++)
            {
                if (hashBytes[i + 16] != hash[i])
                {
                    returnValue = false;
                    break;
                }
            }
            return(returnValue);
        }
コード例 #37
0
        public static string HashWithSalt(string password, byte[] salt)
        {
            if (password == null)
            {
                return("");
            }

            /* hash and salt it using PBKDF2 */
            var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000);

            // place the string in the byte array (that's what getbytes does)
            byte[] hash = pbkdf2.GetBytes(20);

            // make new byte array where to store the hashed password+salt
            // why 36? cause 20 are for the hash and 16 for the salt
            byte[] hashBytes = new byte[36];

            // place the hash and salt in their respective places
            Array.Copy(salt, 0, hashBytes, 0, 16);
            Array.Copy(hash, 0, hashBytes, 16, 20);

            // now, convert our fancy byte array to a string
            return(Convert.ToBase64String(hashBytes));
        }
コード例 #38
0
        /// <summary>
        /// Verifies a password against a hash.
        /// </summary>
        /// <param name="password">The password.</param>
        /// <param name="hashedPassword">The hash.</param>
        /// <returns>Could be verified?</returns>
        public static bool Verify(string password, string hashedPassword)
        {
            // 1. 检查是否符合版本
            if (!IsHashSupported(hashedPassword))
            {
                throw new NotSupportedException("The hashtype is not supported");
            }

            // 2. 把迭代次数跟哈希取出来
            var splittedHashString = hashedPassword.Replace(HashVersion, "").Split('$');
            var iterations         = int.Parse(splittedHashString[0]);
            var base64Hash         = splittedHashString[1];

            // 3. Get hash bytes
            var hashBytes = Convert.FromBase64String(base64Hash);

            // 4. Get salt
            var salt = new byte[SaltSize];

            Array.Copy(hashBytes, 0, salt, 0, SaltSize);

            // 5. Create hash with given salt
            var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);

            byte[] hash = pbkdf2.GetBytes(HashSize);

            // 6. 对比
            for (var i = 0; i < HashSize; i++)
            {
                if (hashBytes[i + SaltSize] != hash[i])
                {
                    return(false);
                }
            }
            return(true);
        }
コード例 #39
0
        public static string ComputePBKDF2Hash(byte[] input, byte[] salt, int iterations)
        {
            if (input == null || input.Length == 0)
            {
                throw new ArgumentException("input is null or empty");
            }

            if (input == null || input.Length == 0)
            {
                throw new ArgumentException("input is null or empty");
            }

            if (iterations < 1)
            {
                throw new ArgumentException("You must have 1 or more password iterations");
            }

            using (var deriveBytes = new Rfc2898DeriveBytes(input, salt, iterations))
            {
                // specify that we want to randomly generate a 20-byte salt
                byte[] result = deriveBytes.GetBytes(20);
                return(Convert.ToBase64String(result));
            }
        }
コード例 #40
0
        public static string Encrypt(string plainText, string passPhrase)
        {
            // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
            // so that the same Salt and IV values can be used when decrypting.
            byte[] saltStringBytes = SimpleStringCipher.Generate256BitsOfRandomEntropy();
            byte[] ivStringBytes   = SimpleStringCipher.Generate256BitsOfRandomEntropy();
            byte[] plainTextBytes  = Encoding.UTF8.GetBytes(plainText);

            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, SimpleStringCipher.DerivationIterations)) {
                byte[] keyBytes = password.GetBytes(Keysize / 8);

                using (var symmetricKey = new RijndaelManaged()) {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode      = CipherMode.CBC;
                    symmetricKey.Padding   = PaddingMode.PKCS7;

                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes)) {
                        using (var memoryStream = new MemoryStream()) {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();

                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                byte[] cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();

                                memoryStream.Close();
                                cryptoStream.Close();
                                return(Convert.ToBase64String(cipherTextBytes));
                            }
                        }
                    }
                }
            }
        }
コード例 #41
0
        /* Verify the plain password againts the stored hash for a user */
        public static bool VerifyPassword(string plainPassword, string storedHash)
        {
            /* Fetch the stored value & Extract the bytes */
            byte[] hashBytes = Convert.FromBase64String(storedHash);

            /* Get the salt */
            byte[] salt = new byte[16];
            Array.Copy(hashBytes, 0, salt, 0, 16);

            /* Compute the hash on the password the user entered */
            var pbkdf2 = new Rfc2898DeriveBytes(plainPassword, salt, 10000);

            byte[] hash = pbkdf2.GetBytes(20);

            /* Compare the results */
            for (int i = 0; i < 20; i++)
            {
                if (hashBytes[i + 16] != hash[i])
                {
                    return(false);
                }
            }
            return(true);
        }
コード例 #42
0
        public static string Decrypt(string cipherText, string passPhrase)
        {
            var cipherTextSplited = cipherText.Split('.');
            var hashString        = cipherTextSplited[0];
            var ivString          = cipherTextSplited[1];
            var saltString        = cipherTextSplited[2];

            var cipherTextBytes = GetBytes(hashString);
            var ivStringBytes   = GetBytes(ivString);
            var saltStringBytes = GetBytes(saltString);

            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode      = CipherMode.CBC;
                    symmetricKey.Padding   = PaddingMode.PKCS7;
                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            {
                                var plainTextBytes     = new byte[cipherTextBytes.Length];
                                var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                memoryStream.Close();
                                cryptoStream.Close();
                                return(Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount));
                            }
                        }
                    }
                }
            }
        }
コード例 #43
0
        public bool Check(string hash, string password)
        {
            var parts = hash.Split('.');

            if (parts.Length != 3)
            {
                throw new FormatException("unexpected hash format");
            }

            var iterations = Convert.ToInt32(parts[0]);
            var salt       = Convert.FromBase64String(parts[1]);
            var key        = Convert.FromBase64String(parts[2]);

            using (var algorithm = new Rfc2898DeriveBytes(
                       password,
                       salt,
                       iterations
                       //HashAlgorithmName.SHA512
                       ))
            {
                var keyToCheck = algorithm.GetBytes(_passwordOptions.KeySize);
                return(keyToCheck.SequenceEqual(key));
            }
        }
コード例 #44
0
        public string Encrypt(string plainText, string passPhrase)
        {
            byte[] saltStringBytes = GenerateBitsOfRandomEntropy(32);
            byte[] ivStringBytes   = GenerateBitsOfRandomEntropy(16);
            byte[] plainTextBytes  = Encoding.UTF8.GetBytes(plainText);

            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                byte[] keyBytes = password.GetBytes(saltBytes);
                using (var symmetricKey = new AesCryptoServiceProvider())
                {
                    symmetricKey.BlockSize = 128;
                    symmetricKey.Mode      = CipherMode.CBC;
                    symmetricKey.Padding   = PaddingMode.PKCS7;
                    using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();


                                byte[] cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return(Convert.ToBase64String(cipherTextBytes));
                            }
                        }
                    }
                }
            }
        }
コード例 #45
0
        public string Encrypt(string data, string salt)
        {
            // Salt and IV is randomly generated each time, but is preprended to encrypted cipher
            // text so that the same Salt and IV values can be used when decrypting.
            var saltStringBytes = Generate128BitsOfRandomEntropy();
            var ivStringBytes   = Generate128BitsOfRandomEntropy();

            using (var password = new Rfc2898DeriveBytes(salt, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(_keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = _blockSize;
                    symmetricKey.Mode      = CipherMode.CBC;
                    symmetricKey.Padding   = PaddingMode.PKCS7;

                    byte[] cipherTextBytes = saltStringBytes;

                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                        using (MemoryStream memoryStream = new MemoryStream())
                            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                var plainTextBytes = Encoding.UTF8.GetBytes(data);
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt
                                // bytes, the random iv bytes and the cipher bytes.

                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                            }
                    var result = Convert.ToBase64String(cipherTextBytes);
                    return(result);
                }
            }
        }
コード例 #46
0
        private bool VerifyHashedPassword(string hashedPassword, string password)
        {
            if (hashedPassword == null)
            {
                throw new ArgumentNullException("hashedPassword");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            int SaltSize           = 16;
            int PBKDF2SubkeyLength = 32;
            int PBKDF2IterCount    = 5;

            byte[] hashedPasswordBytes = Convert.FromBase64String(hashedPassword);


            if (hashedPasswordBytes.Length != (1 + SaltSize + PBKDF2SubkeyLength) || hashedPasswordBytes[0] != 0x00)
            {
                return(false);
            }

            byte[] salt = new byte[SaltSize];
            Array.Copy(hashedPasswordBytes, 1, salt, 0, SaltSize);
            byte[] storedSubkey = new byte[PBKDF2SubkeyLength];
            Array.Copy(hashedPasswordBytes, 1 + SaltSize, storedSubkey, 0, PBKDF2SubkeyLength);

            byte[] generatedSubkey;
            using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, PBKDF2IterCount))
            {
                generatedSubkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);
            }

            return(storedSubkey.SequenceEqual(generatedSubkey));
        }
コード例 #47
0
 public override PasswordVerificationResult VerifyHashedPassword(ApplicationUser user, string hashedPassword, string providedPassword)
 {
     // if it's new algorithm version, delegate the call to parent class
     if (user.HashVersion == PasswordHashVersion.Core)
     {
         return(base.VerifyHashedPassword(user, hashedPassword, providedPassword));
     }
     byte[] buffer4;
     if (hashedPassword == null)
     {
         return(PasswordVerificationResult.Failed);
     }
     if (providedPassword == null)
     {
         throw new ArgumentNullException("providedPassword");
     }
     byte[] src = Convert.FromBase64String(hashedPassword);
     if ((src.Length != 0x31) || (src[0] != 0))
     {
         return(PasswordVerificationResult.Failed);
     }
     byte[] dst = new byte[0x10];
     Buffer.BlockCopy(src, 1, dst, 0, 0x10);
     byte[] buffer3 = new byte[0x20];
     Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
     using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(providedPassword, dst, 0x3e8))
     {
         buffer4 = bytes.GetBytes(0x20);
     }
     if (AreHashesEqual(buffer3, buffer4))
     {
         user.HashVersion = PasswordHashVersion.Core;
         return(PasswordVerificationResult.SuccessRehashNeeded);
     }
     return(PasswordVerificationResult.Failed);
 }
コード例 #48
0
        public static string DecryptString(string cipherText, string sharedSecret)
        {
            string          result = null;
            RijndaelManaged aesAlg = null;

            try
            {
                Rfc2898DeriveBytes key   = new Rfc2898DeriveBytes(sharedSecret, salt);
                byte[]             bytes = Convert.FromBase64String(cipherText);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    aesAlg     = new RijndaelManaged();
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    aesAlg.IV  = ReadByteArray(msDecrypt);
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            result = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            finally
            {
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            return(result);
        }
コード例 #49
0
        /// <summary>
        /// Verfies the password a user entered against the hashcode of
        /// the originally stored user password.
        /// </summary>
        /// <param name="password">Password a user entered.</param>
        /// <param name="hashcode">Hashcode of the originally stored user password.</param>
        /// <param name="throwOnIllegalArgs">If True, Exceptions will be thrown</param>
        public static bool Verify(string password, string hashcode, bool throwOnIllegalArgs = false)
        {
            try
            {
                // extract the bytes
                var hashBytes = Convert.FromBase64String(hashcode);

                // Get the salt
                var salt = new byte[16];
                Array.Copy(hashBytes, 0, salt, 0, 16);

                // Compute the hash on the password
                var pbkdf2 = new Rfc2898DeriveBytes(new UTF8Encoding(false).GetBytes(password), salt, _numOfIerations);
                var hash   = pbkdf2.GetBytes(20);

                // Compare the results
                for (var i = 0; i < 20; i++)
                {
                    if (hashBytes[i + 16] != hash[i])
                    {
                        return(false);
                    }
                }
            }
            catch (Exception e)
            {
                if (throwOnIllegalArgs)
                {
                    throw;
                }

                return(false);
            }

            return(true);
        }
コード例 #50
0
        public static bool VerifyHashedPassword(string hashedPassword, string password)
        {
            byte[] _passwordHashBytes;

            int _arrayLen = (SaltByteSize + HashByteSize) + 1;

            if (hashedPassword == null)
            {
                return(false);
            }

            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            byte[] src = Convert.FromBase64String(hashedPassword);

            if ((src.Length != _arrayLen) || (src[0] != 0))
            {
                return(false);
            }

            byte[] _currentSaltBytes = new byte[SaltByteSize];
            Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);

            byte[] _currentHashBytes = new byte[HashByteSize];
            Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);

            using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
            {
                _passwordHashBytes = bytes.GetBytes(SaltByteSize);
            }

            return(AreHashesEqual(_currentHashBytes, _passwordHashBytes));
        }
コード例 #51
0
        public static HashSalt GenerateSaltedHash(int size, string password)
        {
            var saltBytes = new byte[size];
            var provider  = new RNGCryptoServiceProvider();

            provider.GetNonZeroBytes(saltBytes);
            var salt = Convert.ToBase64String(saltBytes);

            var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, saltBytes, 10000);

            /*
             * Rfc2898DeriveBytes class is used to generate the hash using the RFC2898 specification,
             * which uses a method known as PBKDF2 (Password Based Key Derivation Function #2)
             * and is currently recommend by the IETF (Internet Engineering Task Force) for new applications.
             */

            var hashPassword = Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(256));

            HashSalt hashSalt = new HashSalt {
                Hash = hashPassword, Salt = salt
            };

            return(hashSalt);
        }
コード例 #52
0
        public string Encrypt(string plainText)
        {
            using (var outputStream = new MemoryStream())
            {
                using (Aes aes = new AesCryptoServiceProvider())
                {
                    Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Password, Encoding.UTF8.GetBytes(Salt));
                    aes.Key = deriveBytes.GetBytes(128 / 8);

                    outputStream.Write(BitConverter.GetBytes(aes.IV.Length), 0, sizeof(int));
                    outputStream.Write(aes.IV, 0, aes.IV.Length);

                    using (CryptoStream cs = new CryptoStream(outputStream, aes.CreateEncryptor(),
                                                              CryptoStreamMode.Write))
                    {
                        byte[] rawPlaintext = Encoding.Unicode.GetBytes(plainText);
                        cs.Write(rawPlaintext, 0, rawPlaintext.Length);
                        cs.FlushFinalBlock();
                    }
                }

                return(Convert.ToBase64String(outputStream.ToArray()));
            }
        }
コード例 #53
0
        public string Decrypt(string codedData, string salt)
        {
            // Get the complete stream of bytes that represent: [32 bytes of Salt] + [32 bytes of
            // IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(codedData);
            // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(_keysize / 8).ToArray();
            // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(_keysize / 8).Take(_keysize / 8).ToArray();
            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
            var cipherTextBytes = cipherTextBytesWithSaltAndIv
                                  .Skip((_keysize / 8) * 2)
                                  .Take(cipherTextBytesWithSaltAndIv.Length - ((_keysize / 8) * 2))
                                  .ToArray();

            var resultPassword = string.Empty;

            using (var password = new Rfc2898DeriveBytes(salt, saltStringBytes, DerivationIterations))
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = _blockSize;
                    symmetricKey.Mode      = CipherMode.CBC;
                    symmetricKey.Padding   = PaddingMode.PKCS7;

                    var keyBytes = password.GetBytes(_keysize / 8);
                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                        using (var memoryStream = new MemoryStream(cipherTextBytes))
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            {
                                var plainTextBytes     = new byte[cipherTextBytes.Length];
                                var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                resultPassword = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                            }
                }
            return(resultPassword);
        }
コード例 #54
0
ファイル: User.cs プロジェクト: korikori10/DAKAmobile
    private bool decryptPass(string pass, string password)
    {
        /* Fetch the stored value */
        string savedPasswordHash = pass;

        /* Extract the bytes */
        byte[] hashBytes = Convert.FromBase64String(savedPasswordHash);
        /* Get the salt */
        byte[] salt = new byte[16];
        Array.Copy(hashBytes, 0, salt, 0, 16);
        /* Compute the hash on the password the user entered */
        var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000);

        byte[] hash = pbkdf2.GetBytes(20);
        /* Compare the results */
        for (int i = 0; i < 20; i++)
        {
            if (hashBytes[i + 16] != hash[i])
            {
                return(false);
            }
        }
        return(true);
    }
コード例 #55
0
ファイル: HashHelper.cs プロジェクト: AAmanzi/fali-jedan
        public static bool ValidatePassword(string password, string hashedPassword)
        {
            //get hash-bytes
            var hashBytes = Convert.FromBase64String(hashedPassword);

            //get salt
            var salt = new byte[SaltSize];

            Array.Copy(hashBytes, 0, salt, 0, SaltSize);

            //create hash with given salt
            var pbkdf2 = new Rfc2898DeriveBytes(password, salt, NumberOfIterations);
            var hash   = pbkdf2.GetBytes(HashSize);

            //get result
            for (var i = 0; i < HashSize; i++)
            {
                if (hashBytes[i + SaltSize] != hash[i])
                {
                    return(false);
                }
            }
            return(true);
        }
コード例 #56
0
        public bool CheckPassword(string testPassword)
        {
            if (string.IsNullOrWhiteSpace(testPassword))
            {
                return(false);
            }
            if (passwordSaltBase64 == null)
            {
                throw new InvalidOperationException($"No password salt is present on the player {id}");
            }
            if (passwordHashBase64 == null)
            {
                throw new InvalidOperationException($"No password hash is present on the player {id}");
            }

            var salt     = Convert.FromBase64String(passwordSaltBase64);
            var realHash = Convert.FromBase64String(passwordHashBase64);

            // Generate the test hash
            using var pbkdf2 = new Rfc2898DeriveBytes(testPassword, salt, iterations: 10000);
            var testHash = pbkdf2.GetBytes(20); //20 bytes length is 160 bits

            return(testHash.SequenceEqual(realHash));
        }
コード例 #57
0
        /// <summary>
        /// Gets encrypted write stream
        /// </summary>
        /// <returns>The write stream.</returns>
        protected override StreamWriter GetWriteStream()
        {
            FileStream   underlyingStream;
            CryptoStream encryptedStream;

            underlyingStream = new FileStream(GetSaveFilename(), FileMode.Create);

            Rfc2898DeriveBytes       byteGenerator = new Rfc2898DeriveBytes(GetUniqueDeviceBytes(), s_Salt, 1000);
            RNGCryptoServiceProvider random        = new RNGCryptoServiceProvider();

            byte[] key = byteGenerator.GetBytes(32);
            byte[] iv  = new byte[16];
            random.GetBytes(iv);

            Rijndael rijndael = Rijndael.Create();

            rijndael.Key = key;
            rijndael.IV  = iv;

            underlyingStream.Write(iv, 0, 16);
            encryptedStream = new CryptoStream(underlyingStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write);

            return(new StreamWriter(encryptedStream));
        }
コード例 #58
0
        public static bool RegisterUser(tblLeitor user, string plaintextPassword)
        {
            Rfc2898DeriveBytes hash;
            var generatedSaltBytes = new byte[16];

            rng.GetBytes(generatedSaltBytes);

            hash = new Rfc2898DeriveBytes(plaintextPassword, generatedSaltBytes, ITERATIONS);

            var digestedHashedPassword = BitConverter.ToString(hash.GetBytes(16)).Replace("-", "").ToLower();

            hash.Dispose();

            using (var db = new TccSettings())
            {
                var leitor = db.tblLeitor.First(l => l.IDLeitor == user.IDLeitor);
                leitor.Salt  = BitConverter.ToString(generatedSaltBytes).Replace("-", "").ToLower();
                leitor.Senha = digestedHashedPassword;

                db.SaveChanges();
            }

            return(true);
        }
        private async Task InitAsync(Stream originalStream, string sharedSecret, string salt)
        {
            originalStream.Position = 0;
            var saltBytes = Encoding.UTF8.GetBytes(salt);

            var memStream = new MemoryStream();
            // generates the key from the shared secret and the salt
            var key = new Rfc2898DeriveBytes(sharedSecret, saltBytes);

            // Creates a RijndaelManaged object
            using (var aesAlg = new RijndaelManaged())
            {
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

                // Creates an encryptor to perform the stream transform.
                using (var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV))
                {
                    // prepends the IV
                    memStream.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int)); //async won't matter here (MemoryStream)
                    memStream.Write(aesAlg.IV, 0, aesAlg.IV.Length);                          //async won't matter here (MemoryStream)

                    var _CryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write);
                    await originalStream.CopyToAsync(_CryptoStream)
                    .IgnoreContext();

                    _CryptoStream.Flush(); //async won't matter here (MemoryStream)
                    if (!_CryptoStream.HasFlushedFinalBlock)
                    {
                        _CryptoStream.FlushFinalBlock();
                    }
                }
            }

            memStream.Position = 0;
            this.SetInnerStream(memStream);
        }
コード例 #60
-1
ファイル: EncryptDecrypt.cs プロジェクト: swapneshpal/HRIMS
        public static string Decrypt(string cipherText)
        {

            try
            {
                string EncryptionKey = "MAKV2SPBNI99212";
                cipherText = cipherText.Replace(" ", "+");
                byte[] cipherBytes = Convert.FromBase64String(cipherText);
                using (Aes encryptor = Aes.Create())
                {
                    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                    encryptor.Key = pdb.GetBytes(32);
                    encryptor.IV = pdb.GetBytes(16);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(cipherBytes, 0, cipherBytes.Length);
                            cs.Close();
                        }
                        cipherText = Encoding.Unicode.GetString(ms.ToArray());
                    }
                }
                return cipherText;
            }
            catch (Exception ex)
            {

                return "0";
            }
        }