/// <summary> /// Get a key for an existing database. First, the key file is located, either because its location /// and filename are the same as the database path (with the exception of the extension), or the user /// is asked. Then, the key file is decrypted using a private key. /// </summary> /// <param name="strPath">Full filename of the database file.</param> /// <returns>A byte array with the key, or null if an error occurs. If an error occurs, user is /// notified of the error.</returns> byte[] GetExistingKey(IOConnectionInfo ioc) { Stream stream = null; try { string newpath = UrlUtil.StripExtension(ioc.Path) + "." + CertProtKeyFileExtension; IOConnectionInfo keyIoc = ioc.CloneDeep(); keyIoc.Path = newpath; stream = IOConnection.OpenRead(keyIoc); } catch (Exception e) { // strPath may be a URL (even if IsLocalFile returns true?), // whatever the reason, fall through and the user can pick a // local file as the key file } if (stream == null || !stream.CanRead) { // fall back on opening a local file // FUTURE ENHANCEMENT: allow user to enter a URL and name/pwd as well OpenFileDialog ofd = UIUtil.CreateOpenFileDialog("KeePassX509Provider", UIUtil.CreateFileTypeFilter(CertProtKeyFileExtension, "x05KeyFile", true), 1, CertProtKeyFileExtension, false /* multi-select */, true); if (ofd.ShowDialog() != DialogResult.OK) { return(null); } stream = IOConnection.OpenRead(IOConnectionInfo.FromPath(ofd.FileName)); } try { BinaryReader reader = new BinaryReader(stream); byte[] p7m = reader.ReadBytes(MAX_KEY_FILE_LENGTH); // URL streams don't support seeking, and so Position doesn't work //bool tooBig = stream.Position >= MAX_KEY_FILE_LENGTH; bool tooBig = p7m.Length >= MAX_KEY_FILE_LENGTH; reader.Close(); if (tooBig) { MessageBox.Show("Kes File ist to big"); return(null); } Certmanager cert_mgr = new Certmanager(); return(cert_mgr.DecryptMsg(p7m)); } catch (SystemException ex) // covers IOException and CryptographicException { MessageBox.Show("Error at encryption or IO error!\nIf you used a smart card for encryption, please provide/plugin fist!"); return(null); } }