private void oLoadItemButton_Click(object sender, RoutedEventArgs e) { // select all the certs associated with this user X509Certificate2 oCert = GetUserKey(UserListSelected.Where <User>(u => u.IsOwnedByCurrentUser)); if (oCert == null) { return; } using (CryptureEntities oContent = new CryptureEntities()) { // reconnect our instance so we can lookup the cipher oContent.Entry(ThisItem).State = EntityState.Unchanged; // look for the matching instance Instance oInstance = ThisItem.Instances.Where( i => StructuralComparisons.StructuralEqualityComparer.Equals( i.User.Certificate, oCert.RawData)).FirstOrDefault(); try { // setup an aes decryptor using the iv and decrypted key using (Aes oCng = AesCng.Create()) { // always attempt to use next generation classes first before // resorting to using legacy crytographic classes try { using (RSA oRSA = oCert.GetRSAPrivateKey()) { oCng.Key = oRSA.Decrypt(oInstance.CipherKey, RSAEncryptionPadding.Pkcs1); oCng.IV = ThisItem.Cipher.CipherVector; } } catch (CryptographicException eCryptoOperation) { // exit if user opted to cancel if ((uint)eCryptoOperation.HResult == 0x8010006E) { return; } using (RSACryptoServiceProvider oRSA = oCert.PrivateKey as RSACryptoServiceProvider) { oCng.Key = oRSA.Decrypt(oInstance.CipherKey, false); oCng.IV = ThisItem.Cipher.CipherVector; } } // attempt to decode the data using (MemoryStream oMemory = new MemoryStream()) using (CryptoStream oCrypto = new CryptoStream( oMemory, oCng.CreateDecryptor(), CryptoStreamMode.Write)) { oCrypto.Write(ThisItem.Cipher.CipherText, 0, ThisItem.Cipher.CipherText.Length); oCrypto.FlushFinalBlock(); // process text item if (ThisItem.ItemType == "text") { oItemData.Text = Encoding.Unicode.GetString(oMemory.ToArray()); } // text binary item else { BinaryItemData = oMemory.ToArray(); } } } // change the ui to allow saving again SetEditingControls(true); } catch (Exception eError) { MessageBox.Show(this, "An error occurred during item decryption: " + Environment.NewLine + Environment.NewLine + eError.Message, "Error During Item Decryption", MessageBoxButton.OK, MessageBoxImage.Error); } } }