private static Aes CreateAes(SecureString securePassword) { Aes aes; byte[] password = null; Rfc2898DeriveBytes deriveBytes = null; try { password = securePassword.ToByteArray(); deriveBytes = new Rfc2898DeriveBytes(password, Salt, Iterations); aes = new AesManaged { KeySize = 256, Key = deriveBytes.GetBytes(32), IV = deriveBytes.GetBytes(16), Mode = CipherMode.CBC, Padding = PaddingMode.ISO10126 }; } finally { if (null != password) { Array.Clear(password, 0, password.Length); } deriveBytes?.Dispose(); } return(aes); }
/// <summary> /// Verifies a password against a hash. /// </summary> /// <param name="password">The password to verify</param> /// <param name="hashedPassword">The hash value to verify against</param> /// <returns>Could be verified?</returns> public static bool Verify(string password, string hashedPassword) { // Check hash if (!IsHashSupported(hashedPassword)) { throw new NotSupportedException("The hash type is not supported"); } // Extract iteration and Base64 string var splitHashString = hashedPassword.Replace(HashType, "").Split('$'); var iterations = int.Parse(splitHashString[0]); var base64Hash = splitHashString[1]; // Get hash bytes 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); var hash = pbkdf2.GetBytes(HashSize); //tidy-up pbkdf2.Dispose(); // Get result for (var i = 0; i < HashSize; i++) { if (hashBytes[i + SaltSize] != hash[i]) { return(false); } } return(true); }
/*================================================================================================= * PUBLIC METHODS *================================================================================================*/ /*************************************************************************************************/ public UserEncrypedData GenerateNewUserEncryptedDataFromPassword(string password) { // Salt RNGCryptoServiceProvider saltCellar = new RNGCryptoServiceProvider(); byte[] salt = new byte[_saltArraySize]; saltCellar.GetBytes(salt); string saltString = Convert.ToBase64String(salt); saltCellar.Dispose(); // Hash #pragma warning disable CA5379 // Do Not Use Weak Key Derivation Function Algorithm Rfc2898DeriveBytes hashTool = new Rfc2898DeriveBytes(password, salt) { #pragma warning restore CA5379 // Do Not Use Weak Key Derivation Function Algorithm IterationCount = _hashIterationCount }; byte[] hash = hashTool.GetBytes(_hashArraySize); string hashString = Convert.ToBase64String(hash); hashTool.Dispose(); // Iterations int iterations = _hashIterationCount; // Guid var uniqueID = Guid.NewGuid().ToString(); // Random Key string randomGeneratedKey = GenerateRandomKey(); return(new UserEncrypedData(saltString, hashString, iterations, uniqueID, randomGeneratedKey)); }
private static string DecryptCypherText(string cypherText) { const string encryptionKey = "123g2910a3qw34b1986rf9k8n63y3d1i"; var cipherBytes = Convert.FromBase64String(cypherText); using (var encryptor = Aes.Create()) { var 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 (var memStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memStream, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(cipherBytes, 0, cipherBytes.Length); cryptoStream.Close(); } cypherText = Encoding.Unicode.GetString(memStream.ToArray()); } // end using pdb.Dispose(); } // end using return(cypherText); } // end DecryptCypherText
private static byte[] Decrypt(byte[] cipherBytes, byte[] keyBytes, byte[] saltBytes, bool decompressData) { byte[] decryptedBytes = null; using (MemoryStream MS = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { var keyInfo = new Rfc2898DeriveBytes(SHA256.Create().ComputeHash(keyBytes), saltBytes, 1000); AES.KeySize = 256; AES.BlockSize = 128; AES.Key = keyInfo.GetBytes(AES.KeySize / 8); AES.IV = keyInfo.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; using (var CS = new CryptoStream(MS, AES.CreateDecryptor(), CryptoStreamMode.Write)) { CS.Write(cipherBytes, 0, cipherBytes.Length); CS.Close(); } decryptedBytes = decompressData ? Decompress(MS.ToArray()) : MS.ToArray(); keyInfo.Dispose(); } } return(decryptedBytes); }
public void Dispose() { _DerivedBytes.Dispose(); _CryptoStream.Dispose(); _CryptoTransform.Dispose(); _Aes.Dispose(); }
public string Decrypt(string cipherText) { string EncryptionKey = "IAmNotPrettySureIfIAmGonnaUseThatCrypting"; cipherText = cipherText.Replace(" ", "+"); try { 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()); } pdb.Dispose(); } } catch (Exception) { throw; } return(cipherText); }
public string DecryptPassword(string hashedPassword, string password) { //1. Fetch the stored value string savedPasswordHash = hashedPassword; //2. Extract the bytes byte[] hashBytes = Convert.FromBase64String(savedPasswordHash); //3. Get the salt //salt = new byte[16]; Array.Copy(hashBytes, 0, salt, 0, 16); //4. Compute the hash on the password the user entered var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000); byte[] hash = pbkdf2.GetBytes(20); //5. Compare the results for (int i = 0; i < 20; i++) { if (hashBytes[i + 16] != hash[i]) { throw new UnauthorizedAccessException(); } } //6. Return decrypted password pbkdf2.Dispose(); return(password); }
// 참고 사이트 // Coded By [email protected] : http://blog.naver.com/retn0 // Original Source Code : http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt private static byte[] Encrypt(byte[] plainBytes, byte[] keyBytes, byte[] saltBytes, bool compressData) { byte[] encryptedBytes = null; byte[] plainData = compressData ? Compress(plainBytes) : plainBytes; using (MemoryStream MS = new MemoryStream()) { using (RijndaelManaged AES = new RijndaelManaged()) { var keyInfo = new Rfc2898DeriveBytes(SHA256.Create().ComputeHash(keyBytes), saltBytes, 1000); AES.KeySize = 256; AES.BlockSize = 128; AES.Key = keyInfo.GetBytes(AES.KeySize / 8); AES.IV = keyInfo.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; using (var CS = new CryptoStream(MS, AES.CreateEncryptor(), CryptoStreamMode.Write)) { CS.Write(plainData, 0, plainData.Length); CS.Close(); } encryptedBytes = MS.ToArray(); keyInfo.Dispose(); } } return(encryptedBytes); }
// Token: 0x06000069 RID: 105 public static byte[] EncryptFile(byte[] byte_0, byte[] byte_1, byte[] byte_2) { byte[] result = null; Rfc2898DeriveBytes rfc2898DeriveBytes = Encryption.DeriveBytes(byte_1, byte_2); byte_1 = null; GC.Collect(); using (Aes aes = new AesManaged()) { aes.KeySize = 256; aes.Key = rfc2898DeriveBytes.GetBytes(aes.KeySize / 8); aes.IV = rfc2898DeriveBytes.GetBytes(aes.BlockSize / 8); aes.Padding = PaddingMode.None; aes.Mode = CipherMode.CBC; using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(byte_0, 0, byte_0.Length); cryptoStream.Close(); } result = memoryStream.ToArray(); } rfc2898DeriveBytes.Dispose(); } return(result); }
public static string Decrypt(string encyrptedText, string key) { byte[] cipherTextBytesWithSaltAndIv = Convert.FromBase64String(encyrptedText); byte[] saltStringBytes = cipherTextBytesWithSaltAndIv.Take(KEY_SIZE / 8).ToArray(); byte[] ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(KEY_SIZE / 8) .Take(KEY_SIZE / 8).ToArray(); byte[] cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip(KEY_SIZE / 8 * 2) .Take(cipherTextBytesWithSaltAndIv.Length - KEY_SIZE / 8 * 2).ToArray(); Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(key, saltStringBytes, ITERATIONS_COUNT); byte[] keyBytes = password.GetBytes(KEY_SIZE / 8); RijndaelManaged symmetricKey = new RijndaelManaged { BlockSize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes); MemoryStream memoryStream = new MemoryStream(cipherTextBytes); CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); byte[] plainTextBytes = new byte[cipherTextBytes.Length]; int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); password.Dispose(); symmetricKey.Dispose(); decryptor.Dispose(); memoryStream.Dispose(); cryptoStream.Dispose(); return(Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)); }
public static string Encrypt(string plainText, string key) { byte[] saltStringBytes = Generate256BitsOfRandomEntropy(); byte[] ivStringBytes = Generate256BitsOfRandomEntropy(); byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(key, saltStringBytes, ITERATIONS_COUNT); byte[] keyBytes = password.GetBytes(KEY_SIZE / 8); RijndaelManaged symmetricKey = new RijndaelManaged { BlockSize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }; ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes); MemoryStream memoryStream = new MemoryStream(); CryptoStream 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(); cryptoStream.Dispose(); memoryStream.Dispose(); encryptor.Dispose(); symmetricKey.Dispose(); password.Dispose(); return(Convert.ToBase64String(cipherTextBytes)); }
public static string Decrypt(string cipherText, string salt) { if (string.IsNullOrEmpty(Key)) { throw new ArgumentException("You must set 'Key' value for Cryptography"); } cipherText = cipherText.Replace(" ", "+"); byte[] cipherBytes = Convert.FromBase64String(cipherText); using (var encryptor = Aes.Create()) { var pdb = new Rfc2898DeriveBytes(Key, Encoding.ASCII.GetBytes(salt)); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); pdb.Dispose(); using var memoryStream = new MemoryStream(); using (var cs = new CryptoStream(memoryStream, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); } cipherText = Encoding.Unicode.GetString(memoryStream.ToArray()); } return(cipherText); }
/// <summary> /// Uses the Rijndael class to encrypt the application key file. /// </summary> /// <param name="filePath">Application key file path.</param> /// <param name="password">Password for encrypting the application key file.</param> public static void EncryptKey(string filePath, string password) { FileInfo fi = new FileInfo(filePath); if (IsEncrypted(filePath) == true) { RemoveFilePadding(filePath); } var keyGenerator = new Rfc2898DeriveBytes(password, saltSize); var rijndael = Rijndael.Create(); // BlockSize, KeySize in bit --> divide by saltSize. rijndael.IV = keyGenerator.GetBytes(rijndael.BlockSize / saltSize); rijndael.Key = keyGenerator.GetBytes(rijndael.KeySize / saltSize); string plaintext = File.ReadAllText(filePath); FileStream fs = fi.Create(); // Write random salt. fs.Write(keyGenerator.Salt, 0, saltSize); CryptoStream cs = new CryptoStream(fs, rijndael.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(Encoding.UTF8.GetBytes(plaintext), 0, plaintext.Length); cs.FlushFinalBlock(); cs.Close(); AddFilePadding(filePath); keyGenerator.Dispose(); rijndael.Dispose(); }
/// <summary> /// Creates a hash from a password. /// </summary> /// <param name="password">The password.</param> /// <param name="iterations">Number of iterations.</param> /// <returns>The hash.</returns> private static string Hash(string password, int iterations) { // Create salt byte[] salt = new byte[SaltSize]; var rngCryptoServiceProvider = new RNGCryptoServiceProvider(); rngCryptoServiceProvider.GetBytes(salt); rngCryptoServiceProvider.Dispose(); // Create hash var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations, HashAlgorithmName.SHA256); var hash = pbkdf2.GetBytes(HashSize); pbkdf2.Dispose(); // 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 with extra information return(string.Format(CultureInfo.InvariantCulture, "$awdware$v1${0}${1}", iterations, base64Hash)); }
public static string EncryptStringAES(string plainText) { if (string.IsNullOrEmpty(plainText)) { throw new ArgumentNullException("plainText"); } string encryptedString = null; // Encrypted string to return. RijndaelManaged aesAlgorithm = null; // RijndaelManaged object used to encrypt the data. try { // Generate the key from a shared secret and initilization vector. Rfc2898DeriveBytes key = new Rfc2898DeriveBytes("https://github.com/R-Smith/vmPing" + Environment.MachineName, Encoding.ASCII.GetBytes(Environment.UserName + "@@vmping-salt@@")); // Create a RijndaelManaged object. aesAlgorithm = new RijndaelManaged(); aesAlgorithm.Padding = PaddingMode.PKCS7; aesAlgorithm.Key = key.GetBytes(aesAlgorithm.KeySize / 8); if (key != null) { key.Dispose(); } // Create a decryptor to perform the stream transform. ICryptoTransform encryptor = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV); // Create the streams used for encryption. using (MemoryStream memoryStream = new MemoryStream()) { // Prepend the IV. memoryStream.Write(BitConverter.GetBytes(aesAlgorithm.IV.Length), 0, sizeof(int)); memoryStream.Write(aesAlgorithm.IV, 0, aesAlgorithm.IV.Length); using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { using (StreamWriter streamWriter = new StreamWriter(cryptoStream)) { // Write all data to the stream. streamWriter.Write(plainText); } } encryptedString = Convert.ToBase64String(memoryStream.ToArray()); } } finally { // Clear the RijndaelManaged object. if (aesAlgorithm != null) { aesAlgorithm.Clear(); } aesAlgorithm.Dispose(); } // Return the encrypted bytes from the memory stream. return(encryptedString); }
private static byte[] CreateHash(string password, byte[] salt) { const int keyLength = 24; var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 1000); // 1000 angir hvor mange ganger hash funskjonen skal utføres for økt sikkerhet var b = pbkdf2.GetBytes(keyLength); pbkdf2.Dispose(); return(b); }
/// <inheritdoc /> public void Dispose() { CryptoStream.Flush(); CryptoStream.Dispose(); _transform.Dispose(); _symmetricKey.Dispose(); _key.Dispose(); }
void EncryptFile_Aes(string filePath, string encryptedName) // AES ENCRYPTION { // CHECKING FOR FILENAME AND PASSWORD INPUT try { if (filePath == null || filePath.Length <= 0) { throw new ArgumentNullException("filePath"); } if (encryptedName == null || encryptedName.Length <= 0) { throw new ArgumentNullException("encryptedName"); } if (encryptionPwd.Password == null || encryptionPwd.Password.Length <= 0) { throw new ArgumentNullException("encryptionPwd"); } } catch (Exception e) { System.Windows.MessageBox.Show(String.Format("{0} Exception caught\nMessage: {1}", e, e.Message), "File Name Error!"); return; } // CREATING A KEY FROM THE PASSWORD Rfc2898DeriveBytes keySrc = new Rfc2898DeriveBytes(encryptionPwd.Password, aes.IV); aes.Key = keySrc.GetBytes(aes.KeySize / 8); // CREATING A CRYPTO OBJECT, WHICH WILL BE USED WITH THE CRYPTOSTREAM ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); // CREATING FILE STREAMS FOR THE SRC FILE AND THE ENCRYPTED FILE; try { using (FileStream fSrc = File.Open(filePath, FileMode.Open)) { using (FileStream fEncrypt = File.Create(encryptedName)) { using (CryptoStream csEncrypt = new CryptoStream(fEncrypt, encryptor, CryptoStreamMode.Write)) // CREATING A CRYPTOSTREAM WHICH WORKS AS A PROXY TO ANOTHER STREAM, SETTING THE CRYPTO OBJECT AND THE MODE { using (MemoryStream mStream = new MemoryStream()) // A BUFFER STREAM IS USED TO STORE ALL DATA FROM THE SRC FILE // THEN THE DATA GETS WRITTEN TO THE CRYPTOSTREAM { fSrc.CopyTo(mStream); csEncrypt.Write(mStream.ToArray(), 0, (int)mStream.Length); keySrc.Dispose(); } } } } } catch (Exception e) { System.Windows.MessageBox.Show(String.Format("{0} Exception caught\nMessage: {1}", e, e.Message), "AES Encryption Error!"); } }
/// <summary> /// Uses the Rijndael class to decrypt the application key file. /// </summary> /// <param name="filePath">Application key file path.</param> /// <param name="password">Password to decrypt the application key file.</param> /// <returns>The decrypted string.</returns> public static string DecryptKey(string filePath, string password) { FileInfo fi = new FileInfo(filePath); bool padding = false; if (DomMan.Cryptography.IsEncrypted(filePath) == true) { padding = true; RemoveFilePadding(fi.FullName); } FileStream fs = fi.OpenRead(); byte[] salt = new byte[saltSize]; fs.Read(salt, 0, saltSize); // Initialize the algorithm with salt. Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, salt); Rijndael rijndael = Rijndael.Create(); rijndael.IV = keyGenerator.GetBytes(rijndael.BlockSize / saltSize); rijndael.Key = keyGenerator.GetBytes(rijndael.KeySize / saltSize); CryptoStream cs = new CryptoStream(fs, rijndael.CreateDecryptor(), CryptoStreamMode.Read); keyGenerator.Dispose(); rijndael.Dispose(); string plaintext; try { using (StreamReader sr = new StreamReader(cs)) { plaintext = sr.ReadToEnd(); } } catch (CryptographicException x) { fs.Close(); if (padding == true) { AddFilePadding(filePath); } return("CryptographicException\n\n" + x.Message); } if (padding == true) { AddFilePadding(fi.FullName); } return(plaintext); }
private byte[] Pbkdf2Hash(string password, byte[] saltBytes, int iterations) { byte[] result = null; Rfc2898DeriveBytes pbkdf2 = null; pbkdf2 = new Rfc2898DeriveBytes(password, saltBytes, iterations); result = pbkdf2.GetBytes(_hashSize); pbkdf2.Dispose(); return(result); }
public void InitializePasswordHash() { // Hashed password Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(PrivatePassword, 32, 1000); HMACSHA256 hmac = new HMACSHA256(deriveBytes.GetBytes(256)); PasswordHashSalt = deriveBytes.Salt; PasswordHash = hmac.ComputeHash(deriveBytes.Salt); hmac.Dispose(); deriveBytes.Dispose(); }
private static byte[] CreateHash(string password, byte[] salt, int iterations, int outputBytes) { var pbkdf2 = new Rfc2898DeriveBytes(password, salt); pbkdf2.IterationCount = iterations; var newHash = pbkdf2.GetBytes(outputBytes); pbkdf2.Dispose(); return(newHash); }
/// <summary> /// 文字列のHMACハッシュコード取得 /// </summary> /// <param name="password">パスワード</param> /// <returns>ハッシュデータとソルト</returns> public string[] GetHMAC(string password) { List <string> passData = new List <string>(); Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, 32); HMACSHA256 hmac = new HMACSHA256(deriveBytes.GetBytes(256)); // ハッシュデータの出力 passData.Add(BitConverter.ToString(hmac.ComputeHash(deriveBytes.Salt)).Replace("-", "")); passData.Add(BitConverter.ToString(deriveBytes.Salt).Replace("-", "")); hmac.Dispose(); deriveBytes.Dispose(); return(passData.ToArray()); }
public static string Decrypt(string cipherText) { MemoryStream ms = null; CryptoStream cs = null; string EncryptionKey = "ETLCenter"; Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); try { byte[] cipherBytes = Convert.FromBase64String(cipherText); using (Aes encryptor = Aes.Create()) { encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (ms = new MemoryStream()) { using (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 e) { // ExceptionLog.Log(e, "no ip :login model error decryption "); return("0"); } finally { pdb.Dispose(); ms.Dispose(); cs.Dispose(); } return(cipherText); }
public static string Encryption(string clearText) { MemoryStream ms = null; CryptoStream cs = null; string EncryptionKey = "MAKV2SPBNI99212"; Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); try { byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); using (Aes encryptor = Aes.Create()) { encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (ms = new MemoryStream()) { using (cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); } clearText = Convert.ToBase64String(ms.ToArray()); } } return(clearText); } catch (Exception e) { ExceptionLog.Log(e, "no ip : login model error encryption \n "); } finally { pdb.Dispose(); cs.Dispose(); ms.Dispose(); } return(clearText); }
/// <summary> /// Decrypts data that was encrypted using <see cref="ISymmetricCryptography.EncryptWithPassword(byte[],string)"/>. /// </summary> /// <param name="encryptedBytes">The encrypted data.</param> /// <param name="password">The password that was used to encrypt the data.</param> /// <returns>The decrypted <c>byte[]</c> array.</returns> public byte[] DecryptWithPassword(byte[] encryptedBytes, string password) { int encryptedBytesLength = encryptedBytes?.Length ?? 0; if (encryptedBytesLength <= 32 || string.IsNullOrEmpty(password)) { return(Array.Empty <byte>()); } byte[] decryptedBytes; byte[] salt = new byte[32]; for (int i = 0; i < 32; i++) { salt[i] = encryptedBytes[i]; } AesManaged aes = null; Rfc2898DeriveBytes rfc = null; try { rfc = new Rfc2898DeriveBytes(password, salt, RFC_ITERATIONS); aes = new AesManaged { KeySize = 256, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7, IV = rfc.GetBytes(16), Key = rfc.GetBytes(32) }; using ICryptoTransform decryptor = aes.CreateDecryptor(); decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 32, encryptedBytesLength - 32); } catch { decryptedBytes = null; } finally { aes?.Dispose(); rfc?.Dispose(); } return(decryptedBytes); }
static void Main(string[] args) { var salt = Encoding.ASCII.GetBytes("asdasd12313adavc342gszvswgft 'm;4;jk124"); var totalMethodCalls = 1000; Console.WriteLine($"Optimization results with method class count: {totalMethodCalls}:"); for (var i = 0; i < 4; i++) { string resultNonOptimazed = null; string resultOptimized = null; long timeNonOptimized = 0; long timeOptimized = 0; var pass = GetRandomString(8); var sp = new Stopwatch(); sp.Start(); for (var j = 0; j < totalMethodCalls; j++) { resultNonOptimazed = GeneratePasswordHashUsingSalt(pass, salt); timeNonOptimized += sp.ElapsedMilliseconds; } sp.Restart(); var iterate = 10000; var pbkdf2 = new Rfc2898DeriveBytes(pass, salt, iterate); for (var j = 0; j < totalMethodCalls; j++) { resultOptimized = GeneratePasswordHashUsingSalt_Optimized(ref pbkdf2, salt); timeOptimized += sp.ElapsedMilliseconds; } pbkdf2.Dispose(); if (!string.Equals(resultNonOptimazed, resultOptimized)) { throw new Exception("different result."); } var timeInMs = timeNonOptimized - timeOptimized; var timeInPct = (double)timeInMs / timeNonOptimized * 100; Console.WriteLine($"Time benefit from optimization: {timeInMs} ms or {timeInPct:0.0} %"); } Console.WriteLine("Press any key to exit"); Console.ReadLine(); }
public static void DeriveKey() { SQLiteDatabase database = new SQLiteDatabase(); // Establish AES provider that uses AES 256-bit encryption AESProvider = new AesCryptoServiceProvider(); AESProvider.KeySize = AES_BIT_SIZE; // Generate key using user's password plus the stored salt Rfc2898DeriveBytes deriveKey = new Rfc2898DeriveBytes(ConvertToUnsecureString(SharedObject.encryptedPassword), Convert.FromBase64String(database.SelectSalt()), ITERATION_NUMBER); AESProvider.Key = deriveKey.GetBytes(KEY_SIZE); deriveKey.Dispose(); }
protected override void DisposeResources(bool disposing) { if (!disposing) { return; } if (_provider == null) { return; } _provider.Dispose(); _provider = null; }