Example #1
1
 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.
     var saltStringBytes = Generate256BitsOfRandomEntropy();
     var ivStringBytes = Generate256BitsOfRandomEntropy();
     var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     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 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.
                     var cipherTextBytes = saltStringBytes;
                     cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                     cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                     memoryStream.Close();
                     cryptoStream.Close();
                     return Convert.ToBase64String(cipherTextBytes);
                 }
             }
         }
     }
 }
Example #2
1
        public static string Decrypt(string cipherText, string passPhrase)
        {
            // Get the complete stream of bytes that represent:
            // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            // 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 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);
                        }
                    }
                }
            }
        }
Example #3
1
        public static string Descriptografar(string codigo)
        {
            try
            {
                if (string.IsNullOrEmpty(codigo))
                    return String.Empty;
                string retorno;
                var chave = new Rfc2898DeriveBytes(Segredo, Complemento);

                var algoritimo = new RijndaelManaged();
                algoritimo.Key = chave.GetBytes(algoritimo.KeySize / 8);
                algoritimo.IV = chave.GetBytes(algoritimo.BlockSize / 8);

                var descriptografor = algoritimo.CreateDecryptor(algoritimo.Key, algoritimo.IV);
                var bytes = Convert.FromBase64String(codigo);

                using (var memoryStream = new MemoryStream(bytes))
                using (var cryptoStream = new CryptoStream(memoryStream, descriptografor, CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream))
                    retorno = streamReader.ReadToEnd();

                algoritimo.Clear();

                return retorno;
            }
            catch (Exception)
            {
                return "DEU PAU";
            }
        }
Example #4
1
        public static string Criptografar(string texto)
        {
            if(string.IsNullOrEmpty(texto))
                return String.Empty;

            string outStr;

            RijndaelManaged aesAlg = null;
            try
            {
                var key = new Rfc2898DeriveBytes(Segredo, Complemento);
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(texto);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            return outStr;
        }
Example #5
1
        public 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;
        }
Example #6
1
 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);
 }
Example #7
0
        public bool AddUser(string userPassword, UsersDTO user)
        {
            try
            {
                var userentity = user.ToUser();
                var salt       = new Byte[32];
                using (var provider = new System.Security.Cryptography.RNGCryptoServiceProvider())
                {
                    provider.GetBytes(salt); // Generated salt
                }
                var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(userPassword, salt);
                pbkdf2.IterationCount = 1000;
                byte[] hash = pbkdf2.GetBytes(32); // Hashed and salted password
                userentity.Salt        = salt;
                userentity.EncPassword = hash;

                operationalDataContext.Users.Add(userentity);

                return(operationalDataContext.SaveChanges() > 0);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Example #8
0
        /// <summary>
        /// Creates a new and initialized instance of the TripleSec RNG (no parameters).
        /// </summary>
        public RNGV4()
        {
            // sure, the .NET RNG is pretty good, but lets make an attacker's life miserable
            // and also guard against a compromised RNG
            SSC.RNGCryptoServiceProvider rng = new SSC.RNGCryptoServiceProvider();
            byte[] tempKey  = new byte[512];
            byte[] tempSalt = new byte[512];
            rng.GetBytes(tempKey);
            rng.GetBytes(tempSalt);
            byte[] interim = new SSC.Rfc2898DeriveBytes(tempKey, tempSalt, 64).GetBytes(1024);
            rng.GetBytes(tempSalt);
            byte[] final = new SSC.Rfc2898DeriveBytes(interim, tempSalt, 64).GetBytes(56);
            tempKey.Wipe();
            tempSalt.Wipe();
            interim.Wipe(); // DON'T LEAK!!
            _salt       = new byte[16];
            _aesIV      = new byte[16];
            _xsalsa20IV = new byte[24];
            Buffer.BlockCopy(final, 0, _salt, 0, _salt.Length);
            Buffer.BlockCopy(final, 16, _aesIV, 0, _aesIV.Length);
            Buffer.BlockCopy(final, 16 + 16, _xsalsa20IV, 0, _xsalsa20IV.Length);
            _ready = true;
//#if DEBUG
//            System.Diagnostics.Debug.Print("RNGV4:-------------------------------------");
//            System.Diagnostics.Debug.Print("salt:        " + BitConverter.ToString(_salt).Replace("-", "").ToLowerInvariant());
//            System.Diagnostics.Debug.Print("aesIV:       " + BitConverter.ToString(_salt).Replace("-", "").ToLowerInvariant());
//            System.Diagnostics.Debug.Print("xsalsa20IV:  " + BitConverter.ToString(_salt).Replace("-", "").ToLowerInvariant());
//            System.Diagnostics.Debug.Print("final array: " + BitConverter.ToString(final).Replace("-", "").ToLowerInvariant());
//#endif
            final.Wipe(); // DON'T LEAVE COPIES LAYING AROUND!
        }
        /// <summary>
        /// Decrypts the value <paramref name="toDecrypt"/> using the <paramref name="password"/>.
        /// </summary>
        /// <param name="password">The password.</param>
        /// <param name="toDecrypt">The value to decrypt.</param>
        /// <returns>Decrypted value</returns>
        public static string Decrypt(string password, string toDecrypt)
        {
            Rijndael rinedal = null;
              byte[] toDecBytes = Convert.FromBase64String(toDecrypt);
              try
              {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, GenerateSalt(password));

            rinedal = Rijndael.Create();
            rinedal.Padding = PaddingMode.ISO10126;

            ICryptoTransform tx = rinedal.CreateDecryptor(pdb.GetBytes(32), pdb.GetBytes(16));

            byte[] decrypted = tx.TransformFinalBlock(toDecBytes, 0, toDecBytes.Length);

            return Encoding.Default.GetString(decrypted);
              }
              finally
              {
            if (rinedal != null)
            {
              rinedal.Clear();
            }
              }
        }
 public bool Matches(string password)
 {
     using (var deriveBytes = new Rfc2898DeriveBytes(password, _salt))
     {
         return deriveBytes.GetBytes(20).SequenceEqual(_hash);
     }
 }
Example #11
0
        /// <summary>
        /// 解密
        /// </summary>
        public static string AESDecrypt(string input)
        {
            byte[] encryptBytes = Convert.FromBase64String(input);
            byte[] salt         = Encoding.UTF8.GetBytes(saltValue);
            System.Security.Cryptography.AesManaged         aes = new System.Security.Cryptography.AesManaged( );
            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);

            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize   = aes.LegalKeySizes[0].MaxSize;
            aes.Key       = rfc.GetBytes(aes.KeySize / 8);
            aes.IV        = rfc.GetBytes(aes.BlockSize / 8);

            // 用当前的 Key 属性和初始化向量 IV 创建对称解密器对象
            System.Security.Cryptography.ICryptoTransform decryptTransform = aes.CreateDecryptor( );
            // 解密后的输出流
            System.IO.MemoryStream decryptStream = new System.IO.MemoryStream( );

            // 将解密后的目标流(decryptStream)与解密转换(decryptTransform)相连接
            System.Security.Cryptography.CryptoStream decryptor = new System.Security.Cryptography.CryptoStream(
                decryptStream, decryptTransform, System.Security.Cryptography.CryptoStreamMode.Write);
            // 将一个字节序列写入当前 CryptoStream (完成解密的过程)
            decryptor.Write(encryptBytes, 0, encryptBytes.Length);
            decryptor.Close( );

            // 将解密后所得到的流转换为字符串
            byte[] decryptBytes    = decryptStream.ToArray( );
            string decryptedString = UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);

            return(decryptedString);
        }
Example #12
0
        /// <summary>
        /// 加密
        /// </summary>
        public static string AESEncrypt(string input)
        {
            byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input);
            byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue);

            // AesManaged - 高级加密标准(AES) 对称算法的管理类
            System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged( );
            // Rfc2898DeriveBytes - 通过使用基于 HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2 - 一种基于密码的密钥派生函数)
            // 通过 密码 和 salt 派生密钥
            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);

            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize   = aes.LegalKeySizes[0].MaxSize;
            aes.Key       = rfc.GetBytes(aes.KeySize / 8);
            aes.IV        = rfc.GetBytes(aes.BlockSize / 8);

            // 用当前的 Key 属性和初始化向量 IV 创建对称加密器对象
            System.Security.Cryptography.ICryptoTransform encryptTransform = aes.CreateEncryptor( );
            // 加密后的输出流
            System.IO.MemoryStream encryptStream = new System.IO.MemoryStream( );
            // 将加密后的目标流(encryptStream)与加密转换(encryptTransform)相连接
            System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream
                                                                      (encryptStream, encryptTransform, System.Security.Cryptography.CryptoStreamMode.Write);

            // 将一个字节序列写入当前 CryptoStream (完成加密的过程)
            encryptor.Write(data, 0, data.Length);
            encryptor.Close( );
            // 将加密后所得到的流转换成字节数组,再用Base64编码将其转换为字符串
            string encryptedString = Convert.ToBase64String(encryptStream.ToArray( ));

            return(encryptedString);
        }
Example #13
0
 public string Encrypt(string clearText, string EncryptionKey)
 {
     byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
     using (Aes encryptor = Aes.Create())
     {
         System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.Rfc2898DeriveBytes(EncryptionKey, new byte[]
         {
             73,
             118,
             97,
             110,
             32,
             77,
             101,
             100,
             118,
             101,
             100,
             101,
             118
         });
         encryptor.Key = pdb.GetBytes(32);
         encryptor.IV  = pdb.GetBytes(16);
         using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
         {
             using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
             {
                 cs.Write(clearBytes, 0, clearBytes.Length);
                 cs.Close();
             }
             clearText = System.Convert.ToBase64String(ms.ToArray());
         }
     }
     return(clearText);
 }
		/// <summary>
		/// Creates an initialization vector from a string and sets it for the algorithm.8
		/// </summary>
		/// <param name="IV">The IV string</param>
		/// <remarks>Uses the RFC 2898 algorithm to generate the key</remarks>
		public override void SetIV(String IV)
		{
			Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes(IV, new byte[8] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 });
            _algorithm.IV = generator.GetBytes(_algorithm.BlockSize / 8);//generator.GetBytes(24);

			_IVSet = true;
		}
Example #15
0
        public static string Encrypt(string plainText)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            byte[] keyBytes     = new System.Security.Cryptography.Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var    symmetricKey = new RijndaelManaged()
            {
                Mode = CipherMode.CBC, Padding = PaddingMode.Zeros
            };
            var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

            byte[] cipherTextBytes;

            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                    cryptoStream.Close();
                }
                memoryStream.Close();
            }
            return(Convert.ToBase64String(cipherTextBytes));
        }
        public static void DecryptAes(Stream inStream, Stream outStream, string password)
        {
            if (inStream == null)
            {
                throw new ArgumentNullException("inStream");
            }
            if (outStream == null)
            {
                throw new ArgumentNullException("outStream");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            // generate an encryption key with the shared secret and salt
            using (var key = new Rfc2898DeriveBytes(password, Salt))
            {
                using (var aesAlg = new RijndaelManaged())
                {
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

                    using (var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV))
                    {
                        using (var csEncrypt = new CryptoStream(inStream, decryptor, CryptoStreamMode.Read))
                        {
                            csEncrypt.CopyTo(outStream);
                        }
                    }
                }
            }
        }
        /// <inheritdoc />
        protected internal override byte[] DeriveKeyMaterial(IKeyDerivationParameters parameters, int desiredKeySize)
        {
            // Right now we're assuming that KdfGenericBinary is directly usable as a salt
            // in RFC2898. When our KeyDerivationParametersFactory class supports
            // more parameter types than just BuildForPbkdf2, we might need to adjust this code
            // to handle each type of parameter.
            byte[] salt = parameters.KdfGenericBinary;
#pragma warning disable CA5379 // Do Not Use Weak Key Derivation Function Algorithm
            switch (this.Algorithm)
            {
            case KeyDerivationAlgorithm.Pbkdf2Sha1:
                using (var deriveBytes = new Platform.Rfc2898DeriveBytes(this.Key, salt, parameters.IterationCount))
                {
                    return(deriveBytes.GetBytes(desiredKeySize));
                }

            default:
#if NETSTANDARD2_0
                throw new NotImplementedByReferenceAssemblyException();
#else
                using (var deriveBytes = new Platform.Rfc2898DeriveBytes(this.Key, salt, parameters.IterationCount, GetHashAlgorithm(this.Algorithm)))
                {
                    return(deriveBytes.GetBytes(desiredKeySize));
                }
#endif
            }
#pragma warning restore CA5379 // Do Not Use Weak Key Derivation Function Algorithm
        }
Example #18
0
        private static Aes CreateAes(ProgramOptions options, byte[] iv = null)
        {
            if (!options.EncryptionEnabled)
                return null;

            var salt = Convert.FromBase64String("hkuDTnecxj+oDytliJ69BQ==");
            using (var kdf = new Rfc2898DeriveBytes(options.EncryptionPassword, salt))
            {
                var aes = new AesCryptoServiceProvider();
                var keyLen = aes.KeySize/8;

                if (iv != null)
                {
                    aes.Key = kdf.GetBytes(keyLen);
                    aes.IV = iv;
                    return aes;
                }

                var ivLength = aes.BlockSize/8;
                var bytes = kdf.GetBytes(keyLen + ivLength);
                aes.Key = bytes.SubArray(0, keyLen);
                aes.IV = bytes.SubArray(keyLen, ivLength);
                return aes;
            }
        }
Example #19
0
 public static byte[][] GenerateKeys(byte[] password, byte[] nonce)
 {
     byte[][] array = new byte[4][];
     byte[][] array2 = array;
     byte[] array3 = new byte[]
     {
         1,
         2,
         3,
         4
     };
     byte[] array4 = new byte[nonce.Length + 1];
     for (int i = 0; i < nonce.Length; i++)
     {
         array4[i] = nonce[i];
     }
     nonce = array4;
     for (int j = 0; j < array2.Length; j++)
     {
         nonce[nonce.Length - 1] = array3[j];
         Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, nonce, 2);
         array2[j] = rfc2898DeriveBytes.GetBytes(20);
     }
     return array2;
 }
Example #20
0
        public static string Encrypt(string plainText, string key)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException("plainText");
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            using (var keyDerivationFunction = new Rfc2898DeriveBytes(key, _saltSize))
            {
                var saltBytes = keyDerivationFunction.Salt;
                var keyBytes = keyDerivationFunction.GetBytes(32);
                var ivBytes = keyDerivationFunction.GetBytes(16);

                using (var aesManaged = new AesManaged())
                using (var encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes))
                using (var memoryStream = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    using (var streamWriter = new StreamWriter(cryptoStream))
                        streamWriter.Write(plainText);

                    var cipherTextBytes = memoryStream.ToArray();
                    Array.Resize(ref saltBytes, saltBytes.Length + cipherTextBytes.Length);
                    Array.Copy(cipherTextBytes, 0, saltBytes, _saltSize, cipherTextBytes.Length);

                    return Convert.ToBase64String(saltBytes);
                }
            }
        }
Example #21
0
 public bool Verify(string stringtoCheck, HashBytes hash)
 {
     using (var deriveBytes = new Rfc2898DeriveBytes(stringtoCheck, _saltLength, _iteration))
     {
         return deriveBytes.GetBytes(hash.Key.Length).SequenceEqual(hash.Key);
     }
 }
        /// <summary>
        /// 检查
        /// </summary>
        /// <param name="pass"></param>
        /// <param name="hashedPass"></param>
        /// <returns></returns>
        public static bool CheckEqual(string pass, string hashedPass)
        {
            /* Extract the bytes */
            byte[] hashBytes;
            try
            {
                hashBytes = Convert.FromBase64String(hashedPass);
            }
            catch (Exception ex)
            {
                var logger = LoggerManager.Current();
                logger.Error(ex);

                return false;
            }
            /* Get the salt */
            var salt = new byte[16];
            Array.Copy(hashBytes, 0, salt, 0, 16);
            /* Compute the hash on the password the user entered */
            var pbkdf2 = new Rfc2898DeriveBytes(pass, salt, 10000);
            var hash = pbkdf2.GetBytes(20);
            /* Compare the results */
            for (var i = 0; i < 20; i++)
            {
                if (hashBytes[i + 16] != hash[i])
                    return false;
            }

            return true;
        }
    public string HashPassword(string password) //Takes a string and creates hash of the string
    {
        //STEP 1 Create the salt value with a cryptographic PRNG:

        byte[] salt;
        new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(salt = new byte[16]);

        //STEP 2 Create the Rfc2898DeriveBytes and get the hash value:

        var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 10000);

        //Note: Depending on the performance requirements of your specific application, the value '10000' can be reduced.
        //      A minimum value should be around 1000.
        byte[] hash = pbkdf2.GetBytes(20);

        //STEP 3 Combine the salt and password bytes for later use:

        byte[] hashBytes = new byte[36];
        System.Array.Copy(salt, 0, hashBytes, 0, 16);
        System.Array.Copy(hash, 0, hashBytes, 16, 20);

        //STEP 4 Turn the combined salt+hash into a string for storage

        string savedPasswordHash = System.Convert.ToBase64String(hashBytes);

        //STEP 5 Return hashed password (It will be 48 characters long)
        return(savedPasswordHash);
    }
Example #24
0
        private const int IterateDecoding = 1000;   //Try to think of a less terrible name for this.

        public static string EncryptPassword(string plainText, string passPhrase)
        {
            var rand1StringBytes = Generate256BitsOfStuff();    //256 bits of random ****.
            var rand2StringBytes = Generate256BitsOfStuff();    //Two * 256 bits of random ****. You'll see why!
            var unencryptedTextBytes = Encoding.UTF8.GetBytes(plainText);     //unencrypted plain text. I hope we're not getting marked on the conciseness of our variable declerations...
            using (var password = new Rfc2898DeriveBytes(passPhrase, rand1StringBytes, IterateDecoding))
            {
                var keyBytes = password.GetBytes(KeySize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = KeySize;       //There's no need to use more RAM than we need now is there?
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, rand2StringBytes))
                    {
                        using (var memoryStream = new MemoryStream())       //Using memory stream is a great way of keeping information volitile/difficult to intercept.
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(unencryptedTextBytes, 0, unencryptedTextBytes.Length);       //There's no point in encrypting characters that aren't there.
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                var cipherTextBytes = rand1StringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(rand2StringBytes).ToArray();       //Stores how we've encrypted everything in an array so we can decrypt it when needed.
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Convert.ToBase64String(cipherTextBytes);
                            }
                        }
                    }
                }
            }
        }   //End of encrypt method.
Example #25
0
        public void Test_Pbkdf2()
        {
            byte[] password = new byte[256];
            byte[] salt     = new byte[256];

            _random.NextBytes(password);
            _random.NextBytes(salt);

            using (var hmac = new System.Security.Cryptography.HMACSHA1())
            {
                Pbkdf2 pbkdf2 = new Pbkdf2(hmac, password, salt, 1024);
                System.Security.Cryptography.Rfc2898DeriveBytes rfc2898DeriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 1024);

                Assert.IsTrue(CollectionUtilities.Equals(pbkdf2.GetBytes(1024), rfc2898DeriveBytes.GetBytes(1024)), "Pbkdf2 #1");
            }

            //_random.NextBytes(password);
            //_random.NextBytes(salt);

            //using (var hmac = new System.Security.Cryptography.HMACSHA256())
            //{
            //    CryptoConfig.AddAlgorithm(typeof(SHA256Cng),
            //        "SHA256",
            //        "SHA256Cng",
            //        "System.Security.Cryptography.SHA256",
            //        "System.Security.Cryptography.SHA256Cng");

            //    hmac.HashName = "System.Security.Cryptography.SHA256";

            //    Pbkdf2 pbkdf2 = new Pbkdf2(hmac, password, salt, 1024);
            //    var h = pbkdf2.GetBytes(10);
            //}
        }
Example #26
0
        public static string HashTextWithSalt(string text, string salt)
        {
            Rfc2898DeriveBytes hasher = new Rfc2898DeriveBytes(text, Convert.FromBase64String(salt));
            hasher.IterationCount = HashIterations;

            return Convert.ToBase64String(hasher.GetBytes(HashByteSize));
        }
Example #27
0
 private static byte[] CalculatePasswordHash(byte[] password, byte[] salt, int iterations, int length)
 {
     using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, iterations))
     {
         return deriveBytes.GetBytes(length);
     }
 }
Example #28
0
File: AES.cs Project: reserad/D.E.D
        protected static byte[] encoded(byte[] bytesToBeEncrypted, byte[] passwordBytes)
        {
            byte[] encryptedBytes = null;
            byte[] saltBytes = new byte[] { 2, 15, 240, 232, 39, 204, 190, 33, 226, 206, 110, 107, 61, 25, 87, 196 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;
                    AES.Padding = PaddingMode.Zeros;
                    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);
                    }
                    encryptedBytes = ms.ToArray();
                }
            }
            return encryptedBytes;
        }
        private ICryptoTransform GetTransform(string password, bool encrypt)
        {
            // Create an instance of the Rihndael class.
            RijndaelManaged cipher = new System.Security.Cryptography.RijndaelManaged();

            // Calculate salt to make it harder to guess key by using a dictionary attack.
            byte[] salt = SaltFromPassword(password);
            WriteLog("// salt = " + System.BitConverter.ToString(salt).Replace("-", ""));
            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            Rfc2898DeriveBytes secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 10);

            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            byte[] key = secretKey.GetBytes(32);
            byte[] iv  = secretKey.GetBytes(16);
            WriteLog("// key = " + System.BitConverter.ToString(key).Replace("-", ""));
            WriteLog("// iv = " + System.BitConverter.ToString(iv).Replace("-", ""));
            ICryptoTransform cryptor = null;

            if (encrypt)
            {
                cryptor = cipher.CreateEncryptor(key, iv);
            }
            else
            {
                cryptor = cipher.CreateDecryptor(key, iv);
            }
            return(cryptor);
        }
Example #30
0
        /// <summary>
        /// Cryptographic transformation
        /// </summary>
        /// <param name="password"></param>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        private static ICryptoTransform GetTransform(bool Encrypt)
        {
            // Create an instance of the Rihndael class.
            RijndaelManaged Cipher = new System.Security.Cryptography.RijndaelManaged();

            // Calculate salt to make it harder to guess key by using a dictionary attack.
            byte[] Salt = SaltFromPassword();

            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            Rfc2898DeriveBytes SecretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(Keys.KEY, Salt, 10);

            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            byte[]           SecretKeyBytes            = SecretKey.GetBytes(32);
            byte[]           InitializationVectorBytes = SecretKey.GetBytes(16);
            ICryptoTransform Cryptor = null;

            if (Encrypt)
            {
                Cryptor = Cipher.CreateEncryptor(SecretKeyBytes, InitializationVectorBytes);
            }
            else
            {
                Cryptor = Cipher.CreateDecryptor(SecretKeyBytes, InitializationVectorBytes);
            }
            return(Cryptor);
        }
Example #31
0
        private static byte[] Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
        {
            byte[] encryptedBytes = null;
            var    saltBytes      = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (System.IO.MemoryStream ms = new MemoryStream())
            {
                using (System.Security.Cryptography.RijndaelManaged AES = new RijndaelManaged())
                {
                    var key = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);

                    AES.KeySize   = 256;
                    AES.BlockSize = 128;
                    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);
        }
        public static string UserSecretkey()

        {
            string user     = "******";
            string password = "******";

            byte[] salt   = { 65, 66, 67, 68, 69, 70, 71 };
            string Haskey = "";


            using (var derivedBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(user, salt, iterations: 49999))
            {
                //salt = derivedBytes.Salt;
                //byte[] key = derivedBytes.GetBytes(16); // 128 bits key
                Haskey = Convert.ToBase64String(salt);
            }

            using (var derivedBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, iterations: 49999))
            {
                // salt = derivedBytes.Salt;
                byte[] key = derivedBytes.GetBytes(16); // 128 bits key
                Haskey = Haskey + "-" + Convert.ToBase64String(key);
            }

            return(Haskey);
        }
Example #33
0
 public static byte[] smethod_3(byte[] byte_0, string string_0)
 {
     System.Security.Cryptography.Rijndael           rijndael           = System.Security.Cryptography.Rijndael.Create();
     System.Security.Cryptography.Rfc2898DeriveBytes rfc2898DeriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(string_0, new byte[]
     {
         38,
         220,
         255,
         0,
         173,
         237,
         122,
         238,
         197,
         254,
         7,
         175,
         77,
         8,
         34,
         60
     });
     rijndael.Key = rfc2898DeriveBytes.GetBytes(32);
     rijndael.IV  = rfc2898DeriveBytes.GetBytes(16);
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rijndael.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(byte_0, 0, byte_0.Length);
     cryptoStream.Close();
     return(memoryStream.ToArray());
 }
Example #34
0
 public HashBytes Hash(string stringtoHash, int keyLength)
 {
     using (var deriveBytes = new Rfc2898DeriveBytes(stringtoHash, _saltLength, _iteration))
     {
         return new HashBytes(deriveBytes.Salt, deriveBytes.GetBytes(keyLength));
     }
 }
		/// <summary>
		/// Creates a key from a string and sets it for the algorithm.24λ
		/// </summary>
		/// <param name="key">The key string</param>
		/// <remarks>Uses the RFC 2898 algorithm to generate the key</remarks>
		public override void SetKey(String key)
		{
			Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes(key, new byte[8] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 });
			_algorithm.Key = generator.GetBytes(24);

			_keySet = true;
		}
        public void DecryptFile(string sourceFilename, string destinationFilename, string password)
        {
            AesManaged aes = new AesManaged();
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;
            // NB: Rfc2898DeriveBytes initialization and subsequent calls to   GetBytes   must be eactly the same, including order, on both the encryption and decryption sides.
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
            aes.Key = key.GetBytes(aes.KeySize / 8);
            aes.IV = key.GetBytes(aes.BlockSize / 8);
            aes.Mode = CipherMode.CBC;
            ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);

            using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
                {
                    try
                    {
                        using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            source.CopyTo(cryptoStream);
                        }
                    }
                    catch (CryptographicException exception)
                    {
                        if (exception.Message == "Padding is invalid and cannot be removed.")
                            throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
                        else
                            throw;
                    }
                }
            }
        }
Example #37
0
File: AES.cs Project: 2nfro/dotNet
        public static string Encrypt(string plainText, string key)
        {
            if(string.IsNullOrEmpty(plainText)) {
                throw new ArgumentNullException("plainText");
            }

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

            using(var keyDerivationFunction = new Rfc2898DeriveBytes(key, SALT_SIZE)) {
                byte[] saltBytes = keyDerivationFunction.Salt;
                byte[] keyBytes = keyDerivationFunction.GetBytes(32);
                byte[] ivBytes = keyDerivationFunction.GetBytes(16);

                using(var aesManaged = new AesManaged()) {
                    aesManaged.KeySize = 256;

                    using(var encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes)) {
                        MemoryStream memoryStream = null;
                        CryptoStream cryptoStream = null;

                        return WriteMemoryStream(plainText, ref saltBytes, encryptor, ref memoryStream, ref cryptoStream);
                    }
                }
            }
        }
Example #38
0
 /// <summary>
 /// Encrypts the specified string.
 /// </summary>
 /// <param name="clearText">The string to be encrypted.</param>
 /// <param name="key">The key.</param>
 /// <returns></returns>
 public static string Encrypt(this string clearText, string key)
 {
     byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
     Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
     byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
     return Convert.ToBase64String(encryptedData);
 }
Example #39
0
        public static void EncryptAndUpload(string file, string awsPath, string key)
        {
            if (bool.Parse(ConfigurationManager.AppSettings["ManagedEncryption"]))
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(key, appKey);
                using (var aes = new AesCryptoServiceProvider())
                {
                    aes.Key = deriveBytes.GetBytes(aes.KeySize / 8);
                    aes.IV = deriveBytes.GetBytes(aes.BlockSize / 8);
                    using (var temp = new FileStream(file + "_encrypted", FileMode.Create))
                    {
                        using (var stream = new CryptoStream(new FileStream(file, FileMode.Open), aes.CreateEncryptor(), CryptoStreamMode.Read))
                        {
                            stream.CopyTo(temp);
                        }
                    }

                    UploadFile(file + "_encrypted", awsPath);

                    File.Delete(file + "_encrypted");
                }
            }
            else
                UploadFile(file, awsPath);
        }
Example #40
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="cipherText">要解密的字串</param>
        /// <returns>解密后的字串</returns>
        public static string DecryptStringAES(string cipherText)
        {
            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentNullException("cipherText");
            RijndaelManaged aesAlg = null;
            string plaintext = null;

            try
            {
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(_secret, _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))
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            return plaintext;
        } 
Example #41
0
 /// <summary>
 /// Decrypts the specified string.
 /// </summary>
 /// <param name="cipherText">The string to be decrypted.</param>
 /// <param name="key">The key.</param>
 /// <returns></returns>
 public static string Decrypt(this string cipherText, string key)
 {
     byte[] cipherBytes = Convert.FromBase64String(cipherText);
     Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
     byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
     return Encoding.Unicode.GetString(decryptedData);
 }
Example #42
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="plainText">要加密的字串</param>
        /// <returns>加密后的字串</returns>
        public static string EncryptStringAES(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException("plainText");

            string outStr = null;
            RijndaelManaged aesAlg = null;

            try
            {
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(_secret, _salt);
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            return outStr;
        } 
Example #43
0
        public static string Decrypt(string ciphertext, string key)
        {
            if (string.IsNullOrEmpty(ciphertext))
                throw new ArgumentNullException("cipherText");
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            var allTheBytes = Convert.FromBase64String(ciphertext);
            var saltBytes = allTheBytes.Take(_saltSize).ToArray();
            var ciphertextBytes = allTheBytes.Skip(_saltSize).Take(allTheBytes.Length - _saltSize).ToArray();

            using (var keyDerivationFunction = new Rfc2898DeriveBytes(key, saltBytes))
            {
                var keyBytes = keyDerivationFunction.GetBytes(32);
                var ivBytes = keyDerivationFunction.GetBytes(16);

                using (var aesManaged = new AesManaged())
                using (var decryptor = aesManaged.CreateDecryptor(keyBytes, ivBytes))
                using (var memoryStream = new MemoryStream(ciphertextBytes))
                using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream))
                {
                    return streamReader.ReadToEnd();
                }
            }
        }
Example #44
0
        public static bool ComparePasswords(string PasswordHash, string Password)
        {
            if (string.IsNullOrEmpty(PasswordHash) || string.IsNullOrEmpty(Password)) return false;
            if (PasswordHash.Length < 40 || Password.Length < 1) return false;

            byte[] salt = new byte[20];
            byte[] key = new byte[20];
            byte[] hash = Convert.FromBase64String(PasswordHash);

            try
            {
                Buffer.BlockCopy(hash, 0, salt, 0, 20);
                Buffer.BlockCopy(hash, 20, key, 0, 20);

                using (var hashBytes = new Rfc2898DeriveBytes(Password, salt, 10000))
                {
                    byte[] newKey = hashBytes.GetBytes(20);

                    if (newKey != null)
                        if (newKey.SequenceEqual(key))
                            return true;
                }
                return false;
            }
            finally
            {
                if (salt != null)
                    Array.Clear(salt, 0, salt.Length);
                if (key != null)
                    Array.Clear(key, 0, key.Length);
                if (hash != null)
                    Array.Clear(hash, 0, hash.Length);
            }
        }
Example #45
0
        /// <summary>
        /// 根据参数pwd、salt使用Rfc2898DeriveBytes算法生成Pwd的值(判断合法性时使用)
        /// </summary>
        /// <param name="pwd">明文的密码</param>
        /// <param name="salt">密文的salt</param>
        /// <param name="pwdhash">密文的salt</param>
        public static string GetPwdhash(string pwd, string salt)
        {
            string pwdHash = "";

            System.Security.Cryptography.Rfc2898DeriveBytes db;
            db = new System.Security.Cryptography.Rfc2898DeriveBytes(pwd, System.Convert.FromBase64String(salt), 1000);
            return(pwdHash = System.Convert.ToBase64String(db.GetBytes(32)));
        }
Example #46
0
        private byte[] GenerateKey()
        {
            // return new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 };
            var rfc2898 =
                new System.Security.Cryptography.Rfc2898DeriveBytes(this.txtPassPhrase.Text, this.Salt, Int32.Parse(this.txtIterations.Text));

            return(rfc2898.GetBytes(this.KeyLengthInBytes));
        }
Example #47
0
        public static byte[] GetBytes(string key, int size)
        {
            var salt = Encoding.UTF8.GetBytes("does_not_matter");

            using (var derivedBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(key, salt: salt, iterations: 50000, HashAlgorithmName.SHA256))
            {
                return(derivedBytes.GetBytes(size));
            }
        }
Example #48
0
 /// <summary>
 /// 使用Rfc2898DeriveBytes算法分别生成Salt和Pwd的值(新增时使用)
 /// </summary>
 /// <param name="pwd">明文的密码</param>
 /// <param name="salt">密文后的salt</param>
 /// <param name="pwdhash">密文后的pwd</param>
 public static void GetPwdhashAndSalt(string pwd, out string salt, out string pwdHash)
 {
     //salt = "MJvwQJ/T8gJ5cjen0pMBmTHXugdhuTuZ5DRyZMhs1zg=";
     System.Security.Cryptography.Rfc2898DeriveBytes db;
     db      = new System.Security.Cryptography.Rfc2898DeriveBytes(pwd, 32, 1000);
     salt    = System.Convert.ToBase64String(db.Salt);
     pwdHash = System.Convert.ToBase64String(db.GetBytes(32));
     //如果需要添加用户,保存salt和散列侯的密码到数据存储设备
     //如果需要验证用户,从数据存储设备中读取slat,使用salt来计算出密码的散列值,并且与保存在数据存储设备中的密文密码进行比较
 }
        private static byte[] Hi1(UsernamePasswordCredential credential, byte[] salt, int iterations)
        {
            var passwordDigest = AuthenticationHelper.MongoPasswordDigest(credential.Username, credential.Password);

            using (var deriveBytes = new Rfc2898DeriveBytes(passwordDigest, salt, iterations, HashAlgorithmName.SHA1))
            {
                // 20 is the length of output of a sha-1 hmac
                return(deriveBytes.GetBytes(20));
            }
        }
        public string generateKey(String password, byte[] saltBytes)
        {
            int iterations = 100;
            var rfc2898    =
                new System.Security.Cryptography.Rfc2898DeriveBytes(password, saltBytes, iterations);

            byte[] key    = rfc2898.GetBytes(16);
            String keyB64 = Convert.ToBase64String(key);

            return(keyB64);
        }
Example #51
0
        private void PrepareAesObject(byte[] Salt, Aes aes)
        {
            aes.Padding = PaddingMode.PKCS7;
            aes.KeySize = AesKeySizeInBits;
            int KeyStrengthInBytes = aes.KeySize / 8;

            System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 =
                new System.Security.Cryptography.Rfc2898DeriveBytes(Password, Salt, Rfc2898KeygenIterations);
            aes.Key = rfc2898.GetBytes(KeyStrengthInBytes);
            aes.IV  = rfc2898.GetBytes(KeyStrengthInBytes);
        }
Example #52
0
        public static byte[] EncKeyGeneration()
        {
            byte[] salt       = new byte[] { 0x6e, 0x20, 0x76, 0x49, 0x61, 0x64, 0x65, 0x20, };
            int    iterations = 1024;
            var    rfc2898    =
                new System.Security.Cryptography.Rfc2898DeriveBytes(EncryptionKeyMobileApp, salt, iterations);

            byte[] key    = rfc2898.GetBytes(16);
            String keyB64 = Convert.ToBase64String(key);

            //System.Console.WriteLine("Key: " + keyB64);
            return(key);
        }
Example #53
0
        private void _GenerateCryptoBytes()
        {
            //Console.WriteLine(" provided password: '******'", _Password);

            System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 =
                new System.Security.Cryptography.Rfc2898DeriveBytes(_Password, Salt, Rfc2898KeygenIterations);

            _keyBytes = rfc2898.GetBytes(_KeyStrengthInBytes); // 16 or 24 or 32 ???
            _MacInitializationVector = rfc2898.GetBytes(_KeyStrengthInBytes);
            _generatedPv             = rfc2898.GetBytes(2);

            _cryptoGenerated = true;
        }
Example #54
0
        /// <inheritdoc />
        public byte[] DeriveKeyMaterial(ICryptographicKey key, IKeyDerivationParameters parameters, int desiredKeySize)
        {
            // Right now we're assuming that KdfGenericBinary is directly usable as a salt
            // in RFC2898. When our KeyDerivationParametersFactory class supports
            // more parameter types than just BuildForPbkdf2, we might need to adjust this code
            // to handle each type of parameter.
            var keyMaterial = ((KeyDerivationCryptographicKey)key).Key;

            byte[] salt        = parameters.KdfGenericBinary;
            var    deriveBytes = new Platform.Rfc2898DeriveBytes(keyMaterial, salt, parameters.IterationCount);

            return(deriveBytes.GetBytes(desiredKeySize));
        }
Example #55
0
        static byte[] MFcrypt(byte[] P, byte[] S,
                              int cost, int blockSize, int parallel, int?maxThreads)
        {
            int MFLen = blockSize * 128;

            if (maxThreads == null)
            {
                maxThreads = int.MaxValue;
            }

            if (!BitMath.IsPositivePowerOf2(cost))
            {
                throw Exceptions.ArgumentOutOfRange("cost", "Cost must be a positive power of 2.");
            }
            Check.Range("blockSize", blockSize, 1, int.MaxValue / 128);
            Check.Range("parallel", parallel, 1, int.MaxValue / MFLen);
            Check.Range("maxThreads", (int)maxThreads, 1, int.MaxValue);

#if NO_NATIVE_HMACSHA512
            var mac = new NBitcoin.BouncyCastle.Crypto.Macs.HMac(new NBitcoin.BouncyCastle.Crypto.Digests.Sha256Digest());
            mac.Init(new KeyParameter(P));
            byte[] B = Pbkdf2.ComputeDerivedKey(mac, S, 1, parallel * MFLen);
#elif NO_NATIVE_RFC2898_HMACSHA512
            byte[] B = Pbkdf2.ComputeDerivedKey(new HMACSHA256(P), S, 1, parallel * MFLen);
#else
            byte[] B = null;
            if (S.Length >= 8)
            {
                // While we should be able to use Rfc2898DeriveBytes if salt is less than 8 bytes, it sadly does not accept salt less than 8 bytes needed for BIP38
                using System.Security.Cryptography.Rfc2898DeriveBytes derive = new System.Security.Cryptography.Rfc2898DeriveBytes(P, S, 1, System.Security.Cryptography.HashAlgorithmName.SHA256);
                B = derive.GetBytes(parallel * MFLen);
            }
            else
            {
                B = Pbkdf2.ComputeDerivedKey(new HMACSHA256(P), S, 1, parallel * MFLen);
            }
#endif
            uint[] B0 = new uint[B.Length / 4];
            for (int i = 0; i < B0.Length; i++)
            {
                B0[i] = BitPacking.UInt32FromLEBytes(B, i * 4);
            }             // code is easier with uint[]
            ThreadSMixCalls(B0, MFLen, cost, blockSize, parallel, (int)maxThreads);
            for (int i = 0; i < B0.Length; i++)
            {
                BitPacking.LEBytesFromUInt32(B0[i], B, i * 4);
            }
            Security.Clear(B0);

            return(B);
        }
Example #56
0
        public string ResetPassword(string userName)
        {
            var newPassword = RandomString(8);
            var user        = operationalDataContext.Users.FirstOrDefault(u => u.UserName == userName);
            var pbkdf2      = new System.Security.Cryptography.Rfc2898DeriveBytes(newPassword, user.Salt);

            pbkdf2.IterationCount = 1000;
            byte[] hash = pbkdf2.GetBytes(32); // Hashed and salted password
            user.EncPassword = hash;
            operationalDataContext.Users.Attach(user);
            operationalDataContext.Entry(user).State = EntityState.Modified;
            operationalDataContext.SaveChanges();
            return(newPassword);
        }
Example #57
0
        private static ReadOnlyMemory <byte> DeriveSha256(byte[] passwordBytes, byte[] salt, int iterations, int keySize)
        {
            Rfc2898DeriveBytesAlgorithm algo = TryGetAlgorithm(passwordBytes, salt, iterations, HashAlgorithmName.SHA256);

            if (algo != null)
            {
                return(algo.GetBytes(keySize));
            }

            using (var hmac = CryptoPal.Platform.HmacSha256(passwordBytes))
            {
                return(DeriveManually(salt, iterations, keySize, hmac));
            }
        }
Example #58
0
    void Initialize(string password)
    {
        PBKDF2 kdf = new PBKDF2(password, mySalt);

        // Then you have your algorithm
        // When you need a key: use:
        byte[] key = kdf.GetBytes(16);       // for a 128-bit key (16*8=128)

        // You can specify how many bytes you need. Same for IV.
        byte[] iv = kdf.GetBytes(16);       // 128 bits again.

        // And then call your constructor, etc.
        // ...
    }
Example #59
0
        private void SetEncPassword(ref User user)
        {
            var salt = new Byte[32];

            using (var provider = new System.Security.Cryptography.RNGCryptoServiceProvider())
            {
                provider.GetBytes(salt); // Generated salt
            }
            var pbkdf2 = new System.Security.Cryptography.Rfc2898DeriveBytes(user.Password, salt);

            pbkdf2.IterationCount = 1000;
            byte[] hash = pbkdf2.GetBytes(32); // Hashed and salted password
            user.Salt        = salt;
            user.EncPassword = hash;
        }
Example #60
0
        public Context(string keyPrefix, int keySize = 256, int blockSize = 128)
        {
            TestData.TestVersion = 1;

            //keyとivはネイティブ側やランタイムで動的生成を行い
            //解析されずらくしてください。

            byte[] salt        = System.Text.Encoding.UTF8.GetBytes("ソルト生成");
            var    deriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes("ILbSave", salt);
            var    key         = System.Convert.ToBase64String(deriveBytes.GetBytes(keySize / 8));
            var    iv          = System.Convert.ToBase64String(deriveBytes.GetBytes(blockSize / 8));

            Debug.Log($"key:{key},iv:{iv}");
            Save = new SaveData <SaveKey>(iv, key, () => keyPrefix);
        }