public static (IntPtr, int) SecureStringToKeyDeriveReturnPointer(SecureString password, IEnumerable salt, PerformanceDerivative performanceDerivative, Type keyDeriveAlgorithm, out KeyDerive keyDerive) { // Turn the secure string into a string to pass it into keyDevice for the shortest interval possible IntPtr ptrSecureString = IntPtr.Zero; try { ptrSecureString = Marshal.SecureStringToGlobalAllocUnicode(password); var dataInsecureBytes = new byte[password.Length * sizeof(char)]; GCHandle bytesHandle = GCHandle.Alloc(dataInsecureBytes, GCHandleType.Pinned); for (var i = 0; i < password.Length * sizeof(char); i++) { dataInsecureBytes[i] = Marshal.ReadByte(ptrSecureString, i); } // Create an object array of parameters var parametersForInstance = new object[] { dataInsecureBytes, salt, null }; // Parameters for static function call var parametersForStatic = new object[] { performanceDerivative, performanceDerivative.Milliseconds }; object val = keyDeriveAlgorithm.GetMethod("TransformPerformance")?.Invoke(null, parametersForStatic); parametersForInstance[2] = val; keyDerive = (KeyDerive)Activator.CreateInstance(keyDeriveAlgorithm, parametersForInstance); password.Dispose(); return(bytesHandle.AddrOfPinnedObject(), dataInsecureBytes.Length); } catch (NotSupportedException e) { password.Dispose(); FileStatics.WriteToLogFile(e); MessageBox.Show("Fatal error while managing password. Check log file for details"); throw; } catch (OutOfMemoryException e) { password.Dispose(); FileStatics.WriteToLogFile(e); MessageBox.Show("Fatal error while managing password. Check log file for details"); throw; } finally { // Destroy the managed string Marshal.ZeroFreeGlobalAllocUnicode(ptrSecureString); } }
private void EncryptDataWithHeader(CryptographicInfo cryptographicInfo, SecureString password, string filePath) { #if DEBUG Stopwatch watch = Stopwatch.StartNew(); #endif // Forward declaration of the device used to derive the key KeyDerive keyDevice = null; // Load the assemblies necessary for reflection Assembly securityAsm = Assembly.LoadFile(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "System.Security.dll")); Assembly coreAsm = Assembly.LoadFile(Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "System.Core.dll")); var performanceDerivative = new PerformanceDerivative(cryptographicInfo.InstanceKeyCreator.PerformanceDerivative); // Get the password using (password) { if (password.Length == 0) { EncryptOutput.Content = "You must enter a password"; return; } if (password.Length < 4) { EncryptOutput.Content = "Password to short"; return; } // Turn the secure string into a string to pass it into keyDevice for the shortest interval possible IntPtr valuePtr = IntPtr.Zero; try { valuePtr = Marshal.SecureStringToGlobalAllocUnicode(password); // Create an object array of parameters var parameters = new object[] { Marshal.PtrToStringUni(valuePtr), cryptographicInfo.InstanceKeyCreator.salt, null }; var tempTransformationDevice = (KeyDerive)Activator.CreateInstance(Type.GetType(cryptographicInfo.InstanceKeyCreator.root_HashAlgorithm) ?? securityAsm.GetType(cryptographicInfo.InstanceKeyCreator.root_HashAlgorithm) ?? coreAsm.GetType(cryptographicInfo.InstanceKeyCreator.root_HashAlgorithm)); tempTransformationDevice.TransformPerformance(performanceDerivative, 2000UL); #if DEBUG Console.WriteLine(Encryption_App.Resources.MainWindow_EncryptDataWithHeader_Iteration_value__ + tempTransformationDevice.PerformanceValues); #endif parameters[2] = tempTransformationDevice.PerformanceValues; keyDevice = (KeyDerive)Activator.CreateInstance(Type.GetType(cryptographicInfo.InstanceKeyCreator.root_HashAlgorithm) ?? securityAsm.GetType(cryptographicInfo.InstanceKeyCreator.root_HashAlgorithm) ?? coreAsm.GetType(cryptographicInfo.InstanceKeyCreator.root_HashAlgorithm), parameters); } finally { // Destroy the managed string Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); } } HMAC hmacAlg = null; if (cryptographicInfo.Hmac != null) { // Create the algorithm using reflection hmacAlg = (HMAC)Activator.CreateInstance(Type.GetType(cryptographicInfo.Hmac.HashAlgorithm) ?? securityAsm.GetType(cryptographicInfo.Hmac .HashAlgorithm) ?? coreAsm.GetType(cryptographicInfo.Hmac.HashAlgorithm)); } var encryptor = (SymmetricCryptoManager)Activator.CreateInstance(Type.GetType(cryptographicInfo.CryptoManager) ?? securityAsm.GetType(cryptographicInfo.CryptoManager) ?? coreAsm.GetType(cryptographicInfo.CryptoManager)); #if DEBUG long offset = watch.ElapsedMilliseconds; #endif byte[] key = keyDevice.GetBytes(KeySize / 8); #if DEBUG Console.WriteLine(Encryption_App.Resources.MainWindow_EncryptDataWithHeader_Actual_key_derivation_time__ + (watch.ElapsedMilliseconds - offset)); Console.WriteLine(Encryption_App.Resources.MainWindow_EncryptDataWithHeader_Expected_key_derivation_time__ + DesiredKeyDerivationMilliseconds); #endif // Create a handle to the key to allow control of it GCHandle keyHandle = GCHandle.Alloc(key, GCHandleType.Pinned); #if DEBUG Console.WriteLine(Encryption_App.Resources.MainWindow_EncryptDataWithHeader_Pre_encryption_time__ + watch.ElapsedMilliseconds); #endif // Encrypt the data to a temporary file encryptor.EncryptFileBytes(filePath, _dataTempFile, key, cryptographicInfo.EncryptionModeInfo.InitializationVector); #if DEBUG Console.WriteLine(Encryption_App.Resources.MainWindow_EncryptDataWithHeader_Post_encryption_time__ + watch.ElapsedMilliseconds); #endif if (cryptographicInfo.Hmac != null) { // Create the signature derived from the encrypted data and key byte[] signature = MessageAuthenticator.CreateHmac(_dataTempFile, key, hmacAlg); // Set the signature correctly in the CryptographicInfo object cryptographicInfo.Hmac.root_Hash = signature; } // Delete the key from memory for security ZeroMemory(keyHandle.AddrOfPinnedObject(), key.Length); keyHandle.Free(); StepEncryptStrings(); #if DEBUG Console.WriteLine(Encryption_App.Resources.MainWindow_EncryptDataWithHeader_Post_authenticate_time__ + watch.ElapsedMilliseconds); #endif // Write the CryptographicInfo object to a file cryptographicInfo.WriteHeaderToFile(filePath); #if DEBUG // We have to use Dispatcher.Invoke as the current thread can't access these objects this.dispatcher.Invoke(() => { EncryptOutput.Content = "Transferring the data to the file"; }); Console.WriteLine(Encryption_App.Resources.MainWindow_EncryptDataWithHeader_Post_header_time___0_, watch.ElapsedMilliseconds); #endif FileStatics.AppendToFile(filePath, _dataTempFile); #if DEBUG Console.WriteLine(Encryption_App.Resources.MainWindow_EncryptDataWithHeader_File_write_time__ + watch.ElapsedMilliseconds); #endif StepEncryptStrings(); GC.Collect(); }