private static IOWebClient CreateWebClient(IOConnectionInfo ioc) { PrepareWebAccess(ioc); IOWebClient wc = new IOWebClient(ioc); ConfigureWebClient(wc); if ((ioc.UserName.Length > 0) || (ioc.Password.Length > 0)) { wc.Credentials = new NetworkCredential(ioc.UserName, ioc.Password); } else if (NativeLib.IsUnix()) // Mono requires credentials { wc.Credentials = new NetworkCredential("anonymous", string.Empty); } return(wc); }
public Options(IPluginHost host) : this() { mHost = host; mCreateEntryShortcutKey.TextChanged += mCreateEntryShortcutKey_TextChanged; if (NativeLib.IsUnix()) { mCreateEntryShortcutKey.Enabled = false; mCreateEntryShortcutKey.Clear(); } if (mHost.Database.RootGroup != null) { AddGroupToCombo(mHost.Database.RootGroup, 0); } // Set initial UI state mCreateEntryShortcutKey_TextChanged(null, EventArgs.Empty); }
private static bool NeedClipboardWorkaround() { try { string strHandle = (NativeLib.RunConsoleApp(AppXDoTool, "getactivewindow") ?? string.Empty).Trim(); if (strHandle.Length == 0) { Debug.Assert(false); return(false); } // IntPtr h = new IntPtr(long.Parse(strHandle)); long.Parse(strHandle); // Validate // Detection of own windows based on Form.Handle // comparisons doesn't work reliably (Mono's handles // are usually off by 1) // Predicate<IntPtr> fOwnWindow = g_fOwnWindow; // if(fOwnWindow != null) // { // if(fOwnWindow(h)) return true; // } // else { Debug.Assert(false); } string strWmClass = (NativeLib.RunConsoleApp("xprop", "-id " + strHandle + " WM_CLASS") ?? string.Empty); if (strWmClass.IndexOf("\"" + PwDefs.ResClass + "\"", StrUtil.CaseIgnoreCmp) >= 0) { return(true); } if (strWmClass.IndexOf("\"Remmina\"", StrUtil.CaseIgnoreCmp) >= 0) { return(true); } } catch (ThreadAbortException) { throw; } catch (Exception) { Debug.Assert(false); } return(false); }
public ImageComboBoxEx() : base() { if (Program.DesignMode) { return; } if (NativeLib.IsUnix()) { return; } Debug.Assert(this.DrawMode == DrawMode.Normal); this.DrawMode = DrawMode.OwnerDrawVariable; this.DropDownHeight = GetStdItemHeight(null) * 12 + 2; this.MaxDropDownItems = 12; Debug.Assert(!this.Sorted); }
/// <summary> /// Transform the current key <c>uNumRounds</c> times. /// </summary> /// <param name="pbOriginalKey32">The original key which will be transformed. /// This parameter won't be modified.</param> /// <param name="pbKeySeed32">Seed used for key transformations. Must not /// be <c>null</c>. This parameter won't be modified.</param> /// <param name="uNumRounds">Transformation count.</param> /// <returns>256-bit transformed key.</returns> private static byte[] TransformKey(byte[] pbOriginalKey32, byte[] pbKeySeed32, ulong uNumRounds) { Debug.Assert((pbOriginalKey32 != null) && (pbOriginalKey32.Length == 32)); if (pbOriginalKey32 == null) { throw new ArgumentNullException("pbOriginalKey32"); } if (pbOriginalKey32.Length != 32) { throw new ArgumentException(); } Debug.Assert((pbKeySeed32 != null) && (pbKeySeed32.Length == 32)); if (pbKeySeed32 == null) { throw new ArgumentNullException("pbKeySeed32"); } if (pbKeySeed32.Length != 32) { throw new ArgumentException(); } byte[] pbNewKey = new byte[32]; Array.Copy(pbOriginalKey32, pbNewKey, pbNewKey.Length); try { // Try to use the native library first if (NativeLib.TransformKey256(pbNewKey, pbKeySeed32, uNumRounds)) { return((new SHA256Managed()).ComputeHash(pbNewKey)); } if (!TransformKeyManaged(pbNewKey, pbKeySeed32, uNumRounds)) { return(null); } return((new SHA256Managed()).ComputeHash(pbNewKey)); } finally { MemUtil.ZeroByteArray(pbNewKey); } }
private static bool GCryptInitLib() { if (!NativeLib.IsUnix()) { return(false); // Independent of workaround state } if (!MonoWorkarounds.IsRequired(1468)) { return(false); // Can be turned off } #if (!KeePassLibSD && !KeePassUAP && !NETSTANDARD2_0) // gcry_check_version initializes the library; // throws when LibGCrypt is not available NativeMethods.gcry_check_version(IntPtr.Zero); return(true); #else return(false); #endif }
private static string FindFirefox() { if (NativeLib.IsUnix()) { return(FindAppUnix("firefox")); } try { string strPath = FindFirefoxWin(false); if (!string.IsNullOrEmpty(strPath)) { return(strPath); } } catch (Exception) { } return(FindFirefoxWin(true)); }
private static WebRequest CreateWebRequest(IOConnectionInfo ioc) { PrepareWebAccess(); WebRequest req = WebRequest.Create(ioc.Path); ConfigureWebRequest(req); if ((ioc.UserName.Length > 0) || (ioc.Password.Length > 0)) { req.Credentials = new NetworkCredential(ioc.UserName, ioc.Password); } else if (NativeLib.IsUnix()) // Mono requires credentials { req.Credentials = new NetworkCredential("anonymous", string.Empty); } return(req); }
private static bool ShowHelpLocalKcv(string strQuotedMsIts) { try { if (!NativeLib.IsUnix()) { return(false); } string strApp = AppLocator.FindAppUnix("kchmviewer"); if (string.IsNullOrEmpty(strApp)) { return(false); } string strFile = StrUtil.GetStringBetween(strQuotedMsIts, 0, ":", "::"); if (string.IsNullOrEmpty(strFile)) { strFile = StrUtil.GetStringBetween(strQuotedMsIts, 0, ":", "\""); } if (string.IsNullOrEmpty(strFile)) { Debug.Assert(false); return(false); } string strUrl = StrUtil.GetStringBetween(strQuotedMsIts, 0, "::", "\""); // https://www.ulduzsoft.com/linux/kchmviewer/kchmviewer-integration-reference/ string strArgs = "\"" + SprEncoding.EncodeForCommandLine(strFile) + "\""; if (!string.IsNullOrEmpty(strUrl)) { strArgs = "-showPage \"" + SprEncoding.EncodeForCommandLine( strUrl) + "\" " + strArgs; } NativeLib.StartProcess(strApp, strArgs); return(true); } catch (Exception) { Debug.Assert(false); } return(false); }
public void TestNativeLib() { var mock = new Mock <IBuildEngine>(); var trackerLogDirectory = new TaskItem(Path.GetFullPath(TestContext.TestDir)); var nativeCompile = new NativeCompile(); nativeCompile.BuildEngine = mock.Object; nativeCompile.ToolExe = "clang++.exe"; nativeCompile.TrackerLogDirectory = trackerLogDirectory; var sourceFile = new TaskItem(Path.Combine(TestContext.TestDir, "test1.cpp")); File.WriteAllText(sourceFile.ItemSpec, "int main() { return 0; }", Encoding.UTF8); nativeCompile.InputFiles = new List <ITaskItem> { sourceFile }.ToArray(); Assert.IsTrue(nativeCompile.Execute()); Assert.IsFalse(nativeCompile.SkippedExecution); Assert.IsTrue(nativeCompile.OutputFiles.Length == 1); var nativeLib = new NativeLib(); nativeLib.BuildEngine = mock.Object; nativeLib.ToolExe = "llvm-ar.exe"; nativeLib.InputFiles = new List <ITaskItem> { new TaskItem("test1.o") }.ToArray(); nativeLib.InputFiles[0].SetMetadata("OutputFile", Path.ChangeExtension(Path.GetRandomFileName(), ".a")); nativeLib.TrackerLogDirectory = trackerLogDirectory; Assert.IsTrue(nativeLib.Execute()); Assert.IsFalse(nativeCompile.SkippedExecution); Assert.IsTrue(nativeLib.OutputFiles.Length == 1); // Minimal rebuild. nativeLib.MinimalRebuildFromTracking = true; Assert.IsTrue(nativeLib.Execute()); Assert.IsTrue(nativeLib.SkippedExecution); Assert.IsTrue(nativeLib.OutputFiles.Length == 0); }
// ReSharper disable once MemberCanBePrivate.Global - Public for forms designer public Options() { InitializeComponent(); // Must mach order and values of Actions enum var actions = new object[] { Resources.PerformAutoType, Resources.EditEntry, Resources.ShowEntry, Resources.OpenEntryUrl, Resources.CopyPassword, Resources.PerformAutoTypePassword }; mDefaultAction.Items.AddRange(actions); mAlternativeAction.Items.AddRange(actions); // Read options mShowOnFailedSearch.Checked = Settings.Default.ShowOnFailedAutoType; if (NativeLib.IsUnix()) { mShowOnHotKey.Enabled = false; mShowOnHotKey.Checked = false; mShowHotKeyControl.Clear(); } else { mShowOnHotKey.Checked = Settings.Default.ShowOnHotKey; ShowHotKey = Settings.Default.ShowHotKey; } mShowOnHotKey_CheckedChanged(null, EventArgs.Empty); mShowOnIPC.Checked = Settings.Default.ShowOnIPC; mSearchInTitle.Checked = Settings.Default.SearchTitle; mSearchInUserName.Checked = Settings.Default.SearchUserName; mSearchInUrl.Checked = Settings.Default.SearchUrl; mSearchInNotes.Checked = Settings.Default.SearchNotes; mSearchInTags.Checked = Settings.Default.SearchTags; mSearchInOtherFields.Checked = Settings.Default.SearchCustomFields; mCaseSensitive.Checked = Settings.Default.CaseSensitive; mExcludeExpired.Checked = Settings.Default.ExcludeExpired; mResolveReferences.Checked = Settings.Default.ResolveReferences; mDefaultAction.SelectedIndex = (int)Settings.Default.DefaultAction; mAlternativeAction.SelectedIndex = (int)Settings.Default.AlternativeAction; }
private void TxfPrepare() { try { if (NativeLib.IsUnix()) { return; } if (!m_iocBase.IsLocalFile()) { return; } string strID = StrUtil.AlphaNumericOnly(Convert.ToBase64String( CryptoRandom.Instance.GetRandomBytes(16))); string strTempDir = Path.GetTempPath(); if (!Directory.Exists(strTempDir)) { Directory.CreateDirectory(strTempDir); } // See also ClearOld method string strTemp = UrlUtil.EnsureTerminatingSeparator(strTempDir, false) + StrTxfTempPrefix + strID + StrTxfTempSuffix; char chB = UrlUtil.GetDriveLetter(m_iocBase.Path); char chT = UrlUtil.GetDriveLetter(strTemp); if (!TxfIsSupported(chB)) { return; } if ((chT != chB) && !TxfIsSupported(chT)) { return; } m_iocTxfMidFallback = m_iocTemp; m_iocTemp = IOConnectionInfo.FromPath(strTemp); m_lToDelete.Add(m_iocTemp); } catch (Exception) { Debug.Assert(false); m_iocTxfMidFallback = null; } }
public override bool TryBeginImport() { if (NativeLib.IsUnix()) { MessageService.ShowWarning(KPRes.KeePassLibCNotWindows, KPRes.KeePassLibCNotWindowsHint); return(false); } Exception exLib; if (!KdbFile.IsLibraryInstalled(out exLib)) { MessageService.ShowWarning(KPRes.KeePassLibCNotFound, KPRes.KdbKeePassLibC, exLib); return(false); } return(true); }
public static void Refresh() { if (!NativeLib.IsUnix()) { return; // Windows, no refresh required } // Unix int iTicksDiff = (Environment.TickCount - m_iLastRefresh); if (iTicksDiff >= GmpMutexRefreshMs) { m_iLastRefresh = Environment.TickCount; for (int i = 0; i < m_vMutexesUnix.Count; ++i) { try { WriteMutexFilePriv(m_vMutexesUnix[i].Value); } catch (Exception) { Debug.Assert(false); } } } }
private static string FindChrome() { if (NativeLib.IsUnix()) { string str = FindAppUnix("google-chrome"); if (!string.IsNullOrEmpty(str)) { return(str); } return(FindAppUnix("chromium-browser")); } string strPath = FindChromeNew(); if (string.IsNullOrEmpty(strPath)) { strPath = FindChromeOld(); } return(strPath); }
private static void EnsureInitialized() { if (m_bInitialized) { return; } if (NativeLib.IsUnix()) { try { UnixLoadFonts(); } catch (Exception) { Debug.Assert(false); } } if (m_fontUI == null) { m_fontUI = SystemFonts.DefaultFont; } if (m_fontList == null) { if (UIUtil.VistaStyleListsSupported) { string str1 = SystemFonts.IconTitleFont.ToString(); string str2 = SystemFonts.StatusFont.ToString(); if (str1 == str2) { m_fontList = SystemFonts.StatusFont; } else { m_fontList = m_fontUI; } } else { m_fontList = m_fontUI; } } m_bInitialized = true; }
/// <summary> /// Transform the current key <c>uNumRounds</c> times. /// </summary> /// <param name="pbOriginalKey32">The original key which will be transformed. /// This parameter won't be modified.</param> /// <param name="pbKeySeed32">Seed used for key transformations. Must not /// be <c>null</c>. This parameter won't be modified.</param> /// <param name="uNumRounds">Transformation count.</param> /// <returns>256-bit transformed key.</returns> internal static byte[] TransformKey(byte[] pbOriginalKey32, byte[] pbKeySeed32, ulong uNumRounds) { Debug.Assert((pbOriginalKey32 != null) && (pbOriginalKey32.Length == 32)); if (pbOriginalKey32 == null) { throw new ArgumentNullException("pbOriginalKey32"); } if (pbOriginalKey32.Length != 32) { throw new ArgumentException(); } Debug.Assert((pbKeySeed32 != null) && (pbKeySeed32.Length == 32)); if (pbKeySeed32 == null) { throw new ArgumentNullException("pbKeySeed32"); } if (pbKeySeed32.Length != 32) { throw new ArgumentException(); } byte[] pbNewKey = new byte[32]; Array.Copy(pbOriginalKey32, pbNewKey, pbNewKey.Length); // Try to use the native library first if (NativeLib.TransformKey256(pbNewKey, pbKeySeed32, uNumRounds)) { return((new SHA256Managed()).ComputeHash(pbNewKey)); } if (TransformKeyManaged(pbNewKey, pbKeySeed32, uNumRounds) == false) { return(null); } SHA256Managed sha256 = new SHA256Managed(); return(sha256.ComputeHash(pbNewKey)); }
private static bool InitDevice(uint index) { try { IntPtr handle = NativeLib.IowKitGetDeviceHandle(index + 1); IOWarriorType id = (IOWarriorType)NativeLib.IowKitGetProductId(handle); if (id == IOWarriorType.IOWarrior40) { m_IOWarriors.Add(new IOWarrior40(handle)); } else if (id == IOWarriorType.IOWarrior24) { m_IOWarriors.Add(new IOWarrior24(handle)); } else if (id == IOWarriorType.IOWarrior56) { m_IOWarriors.Add(new IOWarrior56(handle)); } else if (id == IOWarriorType.IOWarrior28) { m_IOWarriors.Add(new IOWarrior28(handle)); } else if (id == IOWarriorType.IOWarrior28L) { m_IOWarriors.Add(new IOWarrior28L(handle)); } return(true); } catch (IOException) { return(false); } }
private static void SaveCompilerResults(PlgxPluginInfo plgx, StringBuilder sb) { string strFile = Path.GetTempFileName(); File.WriteAllText(strFile, sb.ToString(), StrUtil.Utf8); string strMsg = plgx.BaseFileName + MessageService.NewParagraph + "Compilation failed. Compiler results have been saved to:" + MessageService.NewLine; VistaTaskDialog dlg = new VistaTaskDialog(); dlg.Content = strMsg + VistaTaskDialog.CreateLink("F", strFile); dlg.DefaultButtonID = (int)DialogResult.Cancel; dlg.EnableHyperlinks = true; dlg.SetIcon(VtdIcon.Warning); dlg.WindowTitle = PwDefs.ShortProductName; dlg.AddButton((int)DialogResult.Cancel, KPRes.Ok, null); dlg.LinkClicked += delegate(object sender, LinkClickedEventArgs e) { if ((e != null) && (e.LinkText == "F") && !NativeLib.IsUnix()) { Process p = Process.Start(NativeLib.EncodePath( WinUtil.LocateSystemApp("Notepad.exe")), "\"" + SprEncoding.EncodeForCommandLine(strFile) + "\""); if (p != null) { p.Dispose(); } } }; if (!dlg.ShowDialog()) { MessageService.ShowWarning(strMsg + strFile); } }
public override bool Initialize(IPluginHost host) { if (m_host != null) { Terminate(); } if (host == null) { return(false); } if (NativeLib.IsUnix()) { return(false); } // #pragma warning disable 162 // if(PwDefs.Version32 <= 0x02010500) // { // MessageService.ShowWarning("IOProtocolExt", // "This plugin requires KeePass 2.16 or higher."); // return false; // } // #pragma warning restore 162 m_host = host; m_host.TriggerSystem.RaisingEvent += this.OnEcasEvent; m_tsSep = new ToolStripSeparator(); m_host.MainWindow.ToolsMenu.DropDownItems.Add(m_tsSep); m_tsOptions = new ToolStripMenuItem(IopDefs.ProductName + " Options..."); m_tsOptions.Click += this.OnOptions; m_host.MainWindow.ToolsMenu.DropDownItems.Add(m_tsOptions); m_wrcWinScp = new WinScpWebRequestCreator(); m_wrcWinScp.Register(); return(true); }
private void Initialize(IOConnectionInfo iocBaseFile, bool bTransacted) { if(iocBaseFile == null) throw new ArgumentNullException("iocBaseFile"); m_bTransacted = bTransacted; m_iocBase = iocBaseFile.CloneDeep(); string strPath = m_iocBase.Path; #if !KeePassUAP // Prevent transactions for FTP URLs under .NET 4.0 in order to // avoid/workaround .NET bug 621450: // https://connect.microsoft.com/VisualStudio/feedback/details/621450/problem-renaming-file-on-ftp-server-using-ftpwebrequest-in-net-framework-4-0-vs2010-only if(strPath.StartsWith("ftp:", StrUtil.CaseIgnoreCmp) && (Environment.Version.Major >= 4) && !NativeLib.IsUnix()) m_bTransacted = false; else { #endif foreach(KeyValuePair<string, bool> kvp in g_dEnabled) { if(strPath.StartsWith(kvp.Key, StrUtil.CaseIgnoreCmp)) { m_bTransacted = kvp.Value; break; } } #if !KeePassUAP } #endif if(m_bTransacted) { m_iocTemp = m_iocBase.CloneDeep(); m_iocTemp.Path += StrTempSuffix; } else m_iocTemp = m_iocBase; }
private static void RunBuildCommand(string strCmd, string strTmpDir, string strCacheDir) { if (string.IsNullOrEmpty(strCmd)) { return; // No assert } string str = strCmd; if (strTmpDir != null) { str = StrUtil.ReplaceCaseInsensitive(str, @"{PLGX_TEMP_DIR}", SprEncoding.EncodeForCommandLine(strTmpDir)); } if (strCacheDir != null) { str = StrUtil.ReplaceCaseInsensitive(str, @"{PLGX_CACHE_DIR}", SprEncoding.EncodeForCommandLine(strCacheDir)); } // str = UrlUtil.ConvertSeparators(str); // Would convert args str = SprEngine.Compile(str, new SprContext(null, null, SprCompileFlags.NonActive, false, true)); string strApp, strArgs; StrUtil.SplitCommandLine(str, out strApp, out strArgs); try { NativeLib.StartProcess(strApp, strArgs); } catch (Exception ex) { if (Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null) { throw new PlgxException(ex.Message); } throw; } }
public RenderedGlyph RenderGlyph(float pixelSize, char glyph, FontRenderMode mode) { FontGlyphInfo result; CheckError(NativeLib.uFontFace_RenderGlyph(Handle, pixelSize, glyph, mode, out result)); // TODO: Also use size of PixelFormat var bitmap = new byte[result.BitmapWidth * result.BitmapHeight]; CheckError(NativeLib.uFontFace_ReadGlyphBitmap(Handle, bitmap, bitmap.Length)); return(new RenderedGlyph { AdvanceX = result.AdvanceX, AdvanceY = result.AdvanceY, BearingX = result.BearingX, BearingY = result.BearingY, Width = result.BitmapWidth, Height = result.BitmapHeight, PixelFormat = (Textures.PixelFormat)result.PixelFormat, Bitmap = bitmap }); }
private static void PrepareResXFile(string strFilePath) { if (!NativeLib.IsUnix()) { return; } string[] v = File.ReadAllLines(strFilePath, Encoding.UTF8); // Fix directory separators in ResX file; // Mono's ResXResourceReader doesn't convert them for (int i = 0; i < (v.Length - 1); ++i) { if ((v[i].IndexOf(@"<data") >= 0) && (v[i].IndexOf( @"System.Resources.ResXFileRef") >= 0) && (v[i + 1].IndexOf( @"<value>") >= 0)) { v[i + 1] = UrlUtil.ConvertSeparators(v[i + 1]); } } File.WriteAllLines(strFilePath, v, new UTF8Encoding(false)); }
private static void SetStringU(string str) { // if(GtkSetString(str)) return; // string r = NativeLib.RunConsoleApp("xclip", // "-in -selection clipboard", str); // if(r != null) return; if (string.IsNullOrEmpty(str)) { // xsel with an empty input can hang, thus use --clear if (NativeLib.RunConsoleApp("xsel", "--clear --primary", null, XSelFlags) != null) { NativeLib.RunConsoleApp("xsel", "--clear --clipboard", null, XSelFlags); return; } try { Clipboard.Clear(); } catch (Exception) { Debug.Assert(false); } return; } // xsel does not support --primary and --clipboard together if (NativeLib.RunConsoleApp("xsel", "--input --primary", str, XSelFlags) != null) { NativeLib.RunConsoleApp("xsel", "--input --clipboard", str, XSelFlags); return; } try { Clipboard.SetText(str); } catch (Exception) { Debug.Assert(false); } }
private static string GetStringU() { // string strGtk = GtkGetString(); // if(strGtk != null) return strGtk; // string str = NativeLib.RunConsoleApp("xclip", // "-out -selection clipboard"); // if(str != null) return str; string str = NativeLib.RunConsoleApp("xsel", "--output --clipboard", null, XSelFlags); if (str != null) { return(str); } if (Clipboard.ContainsText()) { return(Clipboard.GetText() ?? string.Empty); } return(string.Empty); }
private static WebRequest CreateWebRequest(IOConnectionInfo ioc, bool digestAuth) { PrepareWebAccess(); WebRequest req = WebRequest.Create(ioc.Path); ConfigureWebRequest(req); if ((ioc.UserName.Length > 0) || (ioc.Password.Length > 0)) { req.Credentials = new NetworkCredential(ioc.UserName, ioc.Password); if (digestAuth) { var credentialCache = new CredentialCache(); credentialCache.Add( new Uri(new Uri(ioc.Path).GetLeftPart(UriPartial.Authority)), // request url's host "Digest", // authentication type new NetworkCredential(ioc.UserName, ioc.Password) // credentials ); credentialCache.Add( new Uri(new Uri(ioc.Path).GetLeftPart(UriPartial.Authority)), // request url's host "NTLM", // authentication type new NetworkCredential(ioc.UserName, ioc.Password) // credentials ); req.Credentials = credentialCache; } } else if (NativeLib.IsUnix()) // Mono requires credentials { req.Credentials = new NetworkCredential("anonymous", string.Empty); } return(req); }
private void UIBlockInteraction(bool bBlock) { if (bBlock) { m_cPreBlock = UIUtil.GetActiveControl(this); } this.UseWaitCursor = bBlock; // this.Enabled = !bBlock; // Prevents wait cursor m_tabMain.Enabled = !bBlock; m_btnConfigPrinter.Enabled = !bBlock; m_btnPrintPreview.Enabled = !bBlock; m_btnOK.Enabled = !bBlock; m_btnCancel.Enabled = !bBlock; try { m_wbMain.Visible = !bBlock; } catch (Exception) { Debug.Assert(NativeLib.IsUnix()); } if (!bBlock && (m_cPreBlock != null)) { UIUtil.SetFocus(m_cPreBlock, this); } }
public override KdfParameters GetBestParameters(uint uMilliseconds) { const ulong uStep = 3001; ulong uRounds; KdfParameters p = GetDefaultParameters(); // Try native method if (NativeLib.TransformKeyBenchmark256(uMilliseconds, out uRounds)) { p.SetUInt64(ParamRounds, uRounds); return(p); } byte[] pbKey = new byte[32]; byte[] pbNewKey = new byte[32]; for (int i = 0; i < pbKey.Length; ++i) { pbKey[i] = (byte)i; pbNewKey[i] = (byte)i; } #if KeePassUAP KeyParameter kp = new KeyParameter(pbKey); AesEngine aes = new AesEngine(); aes.Init(true, kp); #else byte[] pbIV = new byte[16]; Array.Clear(pbIV, 0, pbIV.Length); RijndaelManaged r = new RijndaelManaged(); if (r.BlockSize != 128) // AES block size { Debug.Assert(false); r.BlockSize = 128; } r.IV = pbIV; r.Mode = CipherMode.ECB; r.KeySize = 256; r.Key = pbKey; ICryptoTransform iCrypt = r.CreateEncryptor(); // !iCrypt.CanReuseTransform -- doesn't work with Mono if ((iCrypt == null) || (iCrypt.InputBlockSize != 16) || (iCrypt.OutputBlockSize != 16)) { Debug.Assert(false, "Invalid ICryptoTransform."); Debug.Assert(iCrypt.InputBlockSize == 16, "Invalid input block size!"); Debug.Assert(iCrypt.OutputBlockSize == 16, "Invalid output block size!"); p.SetUInt64(ParamRounds, PwDefs.DefaultKeyEncryptionRounds); return(p); } #endif uRounds = 0; int tStart = Environment.TickCount; while (true) { for (ulong j = 0; j < uStep; ++j) { #if KeePassUAP aes.ProcessBlock(pbNewKey, 0, pbNewKey, 0); aes.ProcessBlock(pbNewKey, 16, pbNewKey, 16); #else iCrypt.TransformBlock(pbNewKey, 0, 16, pbNewKey, 0); iCrypt.TransformBlock(pbNewKey, 16, 16, pbNewKey, 16); #endif } uRounds += uStep; if (uRounds < uStep) // Overflow check { uRounds = ulong.MaxValue; break; } uint tElapsed = (uint)(Environment.TickCount - tStart); if (tElapsed > uMilliseconds) { break; } } p.SetUInt64(ParamRounds, uRounds); return(p); }
public FileTransactionEx(IOConnectionInfo iocBaseFile, bool bTransacted) { if (iocBaseFile == null) { throw new ArgumentNullException("iocBaseFile"); } m_bTransacted = bTransacted; m_iocBase = iocBaseFile.CloneDeep(); if (m_iocBase.IsLocalFile()) { m_iocBase.Path = UrlUtil.GetShortestAbsolutePath(m_iocBase.Path); } string strPath = m_iocBase.Path; if (m_iocBase.IsLocalFile()) { try { if (File.Exists(strPath)) { // Symbolic links are realized via reparse points; // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365503.aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365680.aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365006.aspx // Performing a file transaction on a symbolic link // would delete/replace the symbolic link instead of // writing to its target FileAttributes fa = File.GetAttributes(strPath); if ((long)(fa & FileAttributes.ReparsePoint) != 0) { m_bTransacted = false; } } else { // If the base and the temporary file are in different // folders and the base file doesn't exist (i.e. we can't // backup the ACL), a transaction would cause the new file // to have the default ACL of the temporary folder instead // of the one of the base folder; therefore, we don't use // a transaction when the base file doesn't exist (this // also results in other applications monitoring the folder // to see one file creation only) m_bTransacted = false; } } catch (Exception) { Debug.Assert(false); } } #if !KeePassUAP // Prevent transactions for FTP URLs under .NET 4.0 in order to // avoid/workaround .NET bug 621450: // https://connect.microsoft.com/VisualStudio/feedback/details/621450/problem-renaming-file-on-ftp-server-using-ftpwebrequest-in-net-framework-4-0-vs2010-only if (strPath.StartsWith("ftp:", StrUtil.CaseIgnoreCmp) && (Environment.Version.Major >= 4) && !NativeLib.IsUnix()) { m_bTransacted = false; } #endif foreach (KeyValuePair <string, bool> kvp in g_dEnabled) { if (strPath.StartsWith(kvp.Key, StrUtil.CaseIgnoreCmp)) { m_bTransacted = kvp.Value; break; } } if (m_bTransacted) { m_iocTemp = m_iocBase.CloneDeep(); m_iocTemp.Path += StrTempSuffix; TxfPrepare(); // Adjusts m_iocTemp } else { m_iocTemp = m_iocBase; } }