static bool IsValidKey(byte[] key) { using (var Aes = new AesManaged()) { var bitLength = key.Length * 8; var maxValidKeyBitLength = Aes.LegalKeySizes.Max(keyLength => keyLength.MaxSize); if (bitLength < maxValidKeyBitLength) { Log.WarnFormat("Encryption key is {0} bits which is less than the maximum allowed {1} bits. Consider using a {1}-bit encryption key to obtain the maximum cipher strength", bitLength, maxValidKeyBitLength); } return(Aes.ValidKeySize(bitLength)); } }
internal AesEncryptionResult EncryptWithMemoryStream(byte[] sourceData, byte[] key = null, byte[] IV = null, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7) { if (sourceData == null || sourceData.Length == 0) { return(new AesEncryptionResult() { Success = false, Message = MessageStrings.Encryption_InputRequired }); } _key = key ?? _key; _IV = IV ?? _IV; byte[] encryptedData = null; try { using (var aesManaged = new AesManaged()) { if (_key == null) { aesManaged.GenerateKey(); _key = aesManaged.Key; } else { if (aesManaged.ValidKeySize((_key.Length * 8))) { aesManaged.Key = _key; } else { return(new AesEncryptionResult() { Success = false, Message = $"{MessageStrings.Common_InvalidKeySizeError} ({(_key.Length * 8)})." }); } } if (_IV == null) { aesManaged.GenerateIV(); _IV = aesManaged.IV; } else { aesManaged.IV = _IV; } aesManaged.Mode = cipherMode; aesManaged.Padding = paddingMode; using (var encryptor = aesManaged.CreateEncryptor(_key, _IV)) { using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { using (var bw = new BinaryWriter(cs)) { bw.Write(sourceData); } } encryptedData = ms.ToArray(); } } } } catch (Exception ex) { return(new AesEncryptionResult() { Success = false, Message = $"{MessageStrings.Encryption_ExceptionError}\n{ex.ToString()}" }); } return(new AesEncryptionResult() { Success = true, Message = MessageStrings.Encryption_EncryptSuccess, EncryptedDataBytes = encryptedData, EncryptedDataBase64String = Convert.ToBase64String(encryptedData), Key = _key, IV = _IV, AesCipherMode = (AesCipherMode)cipherMode, PaddingMode = paddingMode }); }
internal AesEncryptionResult EncryptWithFileStream(string sourceFilePath, string encryptedFilePath, byte[] key = null, byte[] IV = null, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7, bool deleteSourceFile = false, int kBbufferSize = 4) { if (!File.Exists(sourceFilePath)) { return(new AesEncryptionResult() { Success = false, //Message = $"{MessageStrings.Common_FileNotFound} \"{sourceFilePath}\"." Message = $"{MessageStrings.Common_FileNotFound} \"{sourceFilePath}\"." }); } if (string.IsNullOrWhiteSpace(encryptedFilePath)) { return(new AesEncryptionResult() { Success = false, Message = MessageStrings.Encryption_EncryptedFilePathError }); } var destinationDirectory = Path.GetDirectoryName(encryptedFilePath); if (!Directory.Exists(destinationDirectory)) { return(new AesEncryptionResult() { Success = false, Message = $"{MessageStrings.Encryption_DestinationDirectoryNotFound} \"{destinationDirectory}\"." }); } _key = key ?? _key; _IV = IV ?? _IV; var pathsEqual = encryptedFilePath.Equals(sourceFilePath, StringComparison.InvariantCultureIgnoreCase); try { using (var aesManaged = new AesManaged()) { if (_key == null) { aesManaged.GenerateKey(); _key = aesManaged.Key; } else { if (aesManaged.ValidKeySize((_key.Length * 8))) { aesManaged.Key = _key; } else { return(new AesEncryptionResult() { Success = false, Message = $"{MessageStrings.Common_InvalidKeySizeError} ({(_key.Length * 8)})." }); } } if (_IV == null || _IV.Length == 0) { aesManaged.GenerateIV(); _IV = aesManaged.IV; } else { aesManaged.IV = _IV; } aesManaged.Mode = cipherMode; aesManaged.Padding = paddingMode; using (var encryptor = aesManaged.CreateEncryptor(_key, _IV)) { using (var sourceFs = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var encryptedFs = File.Open((pathsEqual ? encryptedFilePath + "_tmpcrypt" : encryptedFilePath), FileMode.Create, FileAccess.Write, FileShare.None)) { using (var cs = new CryptoStream(encryptedFs, encryptor, CryptoStreamMode.Write)) { //plain.CopyTo(cs); var buffer = new byte[kBbufferSize * 1024]; int read; var percentageDone = 0; while ((read = sourceFs.Read(buffer, 0, buffer.Length)) > 0) { cs.Write(buffer, 0, read); var tmpPercentageDone = (int)(sourceFs.Position * 100 / sourceFs.Length); if (tmpPercentageDone != percentageDone) { percentageDone = tmpPercentageDone; RaiseOnEncryptionProgress(percentageDone, (percentageDone != 100 ? $"Encrypting ({percentageDone}%)..." : $"Encrypted ({percentageDone}%).")); } } } } } } } if (pathsEqual) { CommonMethods.ClearFileAttributes(sourceFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below File.Delete(sourceFilePath); File.Move(encryptedFilePath + "_tmpcrypt", encryptedFilePath); } if (deleteSourceFile && !pathsEqual) { CommonMethods.ClearFileAttributes(sourceFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below File.Delete(sourceFilePath); } //var message = $"File \"{sourceFilePath}\" successfully encrypted to \"{encryptedFilePath}\"."; var message = string.Format(MessageStrings.Encryption_FileEncryptSuccess, sourceFilePath, encryptedFilePath); message += (deleteSourceFile && !pathsEqual ? $"\n{string.Format(MessageStrings.Encryption_FileDeleted, sourceFilePath)}" : ""); return(new AesEncryptionResult() { Success = true, Message = message, Key = _key, IV = _IV, AesCipherMode = (AesCipherMode)cipherMode, PaddingMode = paddingMode }); } catch (Exception ex) { return(new AesEncryptionResult() { Success = false, Message = $"{MessageStrings.Encryption_ExceptionError}\n{ex.ToString()}" }); } }
internal AesDecryptionResult DecryptWithMemoryStream(byte[] encryptedData, byte[] key = null, byte[] IV = null, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7) { if (encryptedData == null || encryptedData.Length == 0) { return(new AesDecryptionResult() { Success = false, Message = MessageStrings.Decryption_InputRequired }); } _key = key ?? _key; _IV = IV ?? _IV; if (_key == null) { return(new AesDecryptionResult() { Success = false, Message = MessageStrings.Decryption_NullKeyError }); } if (_IV == null) { return(new AesDecryptionResult() { Success = false, Message = MessageStrings.Decryption_NullIVError }); } byte[] decryptedData = null; try { using (var aesManaged = new AesManaged()) { if (aesManaged.ValidKeySize((_key.Length * 8))) { aesManaged.Key = _key; } else { return(new AesDecryptionResult() { Success = false, Message = $"{MessageStrings.Common_InvalidKeySizeError} ({(_key.Length * 8)})." }); } aesManaged.IV = _IV; aesManaged.Mode = cipherMode; aesManaged.Padding = paddingMode; using (var decryptor = aesManaged.CreateDecryptor(_key, _IV)) { using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write)) { using (var bw = new BinaryWriter(cs)) { bw.Write(encryptedData); } } decryptedData = ms.ToArray(); } } } } catch (Exception ex) { return(new AesDecryptionResult() { Success = false, Message = $"{MessageStrings.Decryption_ExceptionError}\n{ex.ToString()}" }); } return(new AesDecryptionResult() { Success = true, Message = MessageStrings.Decryption_DecryptSuccess, DecryptedDataBytes = decryptedData, DecryptedDataString = System.Text.Encoding.UTF8.GetString(decryptedData), Key = _key, IV = _IV, AesCipherMode = (AesCipherMode)cipherMode, PaddingMode = paddingMode }); }
internal AesEncryptionResult EncryptWithMemoryStream(byte[] sourceData, byte[] key = null, byte[] IV = null, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7) { if (sourceData == null || sourceData.Length == 0) { return(new AesEncryptionResult() { Success = false, Message = "Source data cannot be null or 0 bytes." }); } _key = key; _IV = IV; _cipherMode = cipherMode; _paddingMode = paddingMode; byte[] encryptedData = null; try { using (AesManaged aesManaged = new AesManaged()) { if (_key == null) { aesManaged.GenerateKey(); _key = aesManaged.Key; } else { if (aesManaged.ValidKeySize((_key.Length * 8))) { aesManaged.Key = _key; } else { return(new AesEncryptionResult() { Success = false, Message = $"Invalid key bit size ({(_key.Length * 8)})." }); } } if (_IV == null) { aesManaged.GenerateIV(); _IV = aesManaged.IV; } else { aesManaged.IV = _IV; } aesManaged.Mode = _cipherMode; aesManaged.Padding = _paddingMode; using (var encryptor = aesManaged.CreateEncryptor(_key, _IV)) { using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { using (var bw = new BinaryWriter(cs)) { bw.Write(sourceData); } } encryptedData = ms.ToArray(); } } } } catch (Exception ex) { return(new AesEncryptionResult() { Success = false, Message = $"Error while trying to encrypt data:\n{ex.ToString()}" }); } return(new AesEncryptionResult() { Success = true, Message = "Data succesfully encrypted.", EncryptedDataBytes = encryptedData, EncryptedDataBase64String = Convert.ToBase64String(encryptedData), Key = _key, IV = _IV, AesCipherMode = (AesCipherMode)_cipherMode, PaddingMode = _paddingMode }); }
internal AesDecryptionResult DecryptWithMemoryStream(byte[] encryptedData, byte[] key, byte[] IV, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7) { if (encryptedData == null || encryptedData.Length == 0) { return(new AesDecryptionResult() { Success = false, Message = "Encrypted data cannot be null or 0 bytes." }); } if (key == null) { return(new AesDecryptionResult() { Success = false, Message = "Key cannot be null." }); } if (IV == null) { return(new AesDecryptionResult() { Success = false, Message = "IV cannot be null." }); } _key = key; _IV = IV; _cipherMode = cipherMode; _paddingMode = paddingMode; byte[] decryptedData = null; try { using (AesManaged aesManaged = new AesManaged()) { if (aesManaged.ValidKeySize((_key.Length * 8))) { aesManaged.Key = _key; } else { return(new AesDecryptionResult() { Success = false, Message = $"Invalid key bit size ({(_key.Length * 8)})." }); } aesManaged.IV = _IV; aesManaged.Mode = _cipherMode; aesManaged.Padding = _paddingMode; using (var decryptor = aesManaged.CreateDecryptor(_key, _IV)) { using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write)) { using (var bw = new BinaryWriter(cs)) { bw.Write(encryptedData); } } decryptedData = ms.ToArray(); } } } } catch (Exception ex) { return(new AesDecryptionResult() { Success = false, Message = $"Error while trying to decrypt data:\n{ex.ToString()}" }); } return(new AesDecryptionResult() { Success = true, Message = "Data succesfully decrypted.", DecryptedDataBytes = decryptedData, DecryptedDataString = Encoding.UTF8.GetString(decryptedData), Key = _key, IV = _IV, AesCipherMode = (AesCipherMode)_cipherMode, PaddingMode = _paddingMode }); }