Bug 1621128 - Change OpenPGP to use the configured key. r=PatrickBrunschwig
authorKai Engert <kaie@kuix.de>
Mon, 09 Mar 2020 21:41:09 +0100
changeset 38519 b0232faeed8a3bc67763c31d2c7b3fcf31e2c162
parent 38518 586f1686ac4ba992fb059603fef073850926e39b
child 38520 88ed189e636041ce222a2767664c3bfdc833ead8
push id400
push userclokep@gmail.com
push dateMon, 04 May 2020 18:56:09 +0000
reviewersPatrickBrunschwig
bugs1621128
Bug 1621128 - Change OpenPGP to use the configured key. r=PatrickBrunschwig Differential Revision: https://phabricator.services.mozilla.com/D66661
mail/extensions/am-e2e/prefs/e2e-prefs.js
mail/extensions/openpgp/content/BondOpenPGP.jsm
mail/extensions/openpgp/content/modules/core.jsm
mail/extensions/openpgp/content/modules/encryption.jsm
mail/extensions/openpgp/content/modules/hash.jsm
mail/extensions/openpgp/content/modules/keyRing.jsm
mail/extensions/openpgp/content/modules/mimeEncrypt.jsm
mail/extensions/openpgp/content/modules/rnp.jsm
mail/extensions/openpgp/content/modules/rnpLib.jsm
mail/extensions/openpgp/content/strings/enigmail.dtd
mail/extensions/openpgp/content/ui/enigmailEditIdentity.js
mail/extensions/openpgp/content/ui/enigmailKeygen.js
mail/extensions/openpgp/content/ui/enigmailKeygen.xhtml
mail/extensions/openpgp/content/ui/enigmailMessengerOverlay.js
mail/extensions/openpgp/content/ui/enigmailMsgComposeOverlay.js
--- a/mail/extensions/am-e2e/prefs/e2e-prefs.js
+++ b/mail/extensions/am-e2e/prefs/e2e-prefs.js
@@ -249,18 +249,16 @@ pref("temp.openpgp.keyRefreshOn", false)
 pref("temp.openpgp.enableExperiments", false);
 
 
 /*
    Default pref values for the enigmail per-identity
    settings
 */
 
-pref("mail.identity.default.pgpkeyId", "");
-pref("mail.identity.default.pgpKeyMode", 0);
 pref("mail.identity.default.defaultSigningPolicy", 0);
 pref("mail.identity.default.defaultEncryptionPolicy", 0);
 pref("mail.identity.default.openPgpUrlName", "");
 pref("mail.identity.default.pgpMimeMode", true);
 pref("mail.identity.default.attachPgpKey", false);
 pref("mail.identity.default.autoEncryptDrafts", true);
 pref("mail.identity.default.protectSubject", true);
 pref("mail.identity.default.warnWeakReply", false);
--- a/mail/extensions/openpgp/content/BondOpenPGP.jsm
+++ b/mail/extensions/openpgp/content/BondOpenPGP.jsm
@@ -14,25 +14,20 @@ var { Services } = ChromeUtils.import("r
 var { MailConstants } = ChromeUtils.import(
   "resource:///modules/MailConstants.jsm"
 );
 
 const { EnigmailLazy } = ChromeUtils.import(
   "chrome://openpgp/content/modules/lazy.jsm"
 );
 
-const getEnigmailApp = EnigmailLazy.loader("enigmail/app.jsm", "EnigmailApp");
 const getEnigmailCore = EnigmailLazy.loader(
   "enigmail/core.jsm",
   "EnigmailCore"
 );
-const getEnigmailPgpmimeHander = EnigmailLazy.loader(
-  "enigmail/pgpmimeHandler.jsm",
-  "EnigmailPgpmimeHander"
-);
 const getRNP = EnigmailLazy.loader("enigmail/rnp.jsm", "RNP");
 const getEnigmailWindows = EnigmailLazy.loader(
   "enigmail/windows.jsm",
   "EnigmailWindows"
 );
 
 var BondOpenPGP = {
   logException(exc) {
@@ -51,19 +46,18 @@ var BondOpenPGP = {
       return;
     }
     this.initDone = true;
     console.log("loading OpenPGP");
     try {
       getRNP().init({});
       //TODO: check RNP.libLoaded
 
-      getEnigmailApp().initAddon();
-      getEnigmailCore().startup(0);
-      getEnigmailPgpmimeHander().startup(0);
+      // trigger service init
+      getEnigmailCore().getService();
 
       Services.console.logStringMessage("OpenPGP bootstrap completed");
     } catch (ex) {
       this.logException(ex);
     }
   },
 
   openKeyManager(window) {
--- a/mail/extensions/openpgp/content/modules/core.jsm
+++ b/mail/extensions/openpgp/content/modules/core.jsm
@@ -59,16 +59,20 @@ const getEnigmailConfigure = EnigmailLaz
   "enigmail/configure.jsm",
   "EnigmailConfigure"
 );
 const getEnigmailApp = EnigmailLazy.loader("enigmail/app.jsm", "EnigmailApp");
 const getEnigmailWksMimeHandler = EnigmailLazy.loader(
   "enigmail/wksMimeHandler.jsm",
   "EnigmailWksMimeHandler"
 );
+const getEnigmailPgpmimeHander = EnigmailLazy.loader(
+  "enigmail/pgpmimeHandler.jsm",
+  "EnigmailPgpmimeHander"
+);
 //const getEnigmailOverlays = EnigmailLazy.loader("enigmail/enigmailOverlays.jsm", "EnigmailOverlays");
 const getEnigmailSqlite = EnigmailLazy.loader(
   "enigmail/sqliteDb.jsm",
   "EnigmailSqliteDb"
 );
 const getOpenPGPMasterpass = EnigmailLazy.loader(
   "enigmail/masterpass.jsm",
   "OpenPGPMasterpass"
@@ -455,18 +459,20 @@ Enigmail.prototype = {
 
     getEnigmailLog().DEBUG("core.jsm: svc = " + this + "\n");
 
     if (!this.initialized) {
       const firstInitialization = !this.initializationAttempted;
 
       try {
         // Initialize enigmail
-        EnigmailCore.init(getEnigmailApp().getVersion());
-        this.initialize(win, getEnigmailApp().getVersion());
+        let app = getEnigmailApp();
+        app.initAddon();
+        EnigmailCore.init(app.getVersion());
+        this.initialize(win, app.getVersion());
 
         try {
           // Reset alert count to default value
           getEnigmailPrefs()
             .getPrefBranch()
             .clearUserPref("initAlert");
         } catch (ex) {}
       } catch (ex) {
@@ -519,16 +525,18 @@ Enigmail.prototype = {
       if (
         this.initialized &&
         getEnigmailApp().getVersion() != configuredVersion
       ) {
         getEnigmailConfigure().configureEnigmail(win, startingPreferences);
       }
     }
 
+    EnigmailCore.startup(0);
+    getEnigmailPgpmimeHander().startup(0);
     return this.initialized ? this : null;
   },
 }; // Enigmail.prototype
 
 class Factory {
   constructor(component) {
     this.component = component;
     this.register();
--- a/mail/extensions/openpgp/content/modules/encryption.jsm
+++ b/mail/extensions/openpgp/content/modules/encryption.jsm
@@ -600,16 +600,17 @@ var EnigmailEncryption = {
     }
 
     EnigmailLog.DEBUG(
       "encryption.jsm: encryptMessageEnd: command execution exit code: " +
         exitCode +
         "\n"
     );
 
+    /*
     if (retStatusObj.statusFlags & EnigmailConstants.DISPLAY_MESSAGE) {
       if (retStatusObj.extendedStatus.search(/\bdisp:/) >= 0) {
         retStatusObj.errorMsg = retStatusObj.statusMsg;
       } else {
         if (fromMailAddr.search(/^0x/) === 0) {
           fromMailAddr = fromMailAddr.substr(2);
         }
         if (fromMailAddr.search(/^[A-F0-9]{8,40}$/i) === 0) {
@@ -629,16 +630,17 @@ var EnigmailEncryption = {
           retStatusObj.errorMsg = retStatusObj.statusMsg;
         }
       }
     } else if (retStatusObj.statusFlags & EnigmailConstants.INVALID_RECIPIENT) {
       retStatusObj.errorMsg = retStatusObj.statusMsg;
     } else if (exitCode !== 0) {
       retStatusObj.errorMsg = EnigmailLocale.getString("badCommand");
     }
+    */
 
     return exitCode;
   },
 
   encryptMessage(
     parent,
     uiFlags,
     plainText,
deleted file mode 100644
--- a/mail/extensions/openpgp/content/modules/hash.jsm
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-"use strict";
-
-var EXPORTED_SYMBOLS = ["EnigmailHash"];
-
-const { EnigmailLog } = ChromeUtils.import(
-  "chrome://openpgp/content/modules/log.jsm"
-);
-const { EnigmailWindows } = ChromeUtils.import(
-  "chrome://openpgp/content/modules/windows.jsm"
-);
-const { EnigmailLocale } = ChromeUtils.import(
-  "chrome://openpgp/content/modules/locale.jsm"
-);
-const { EnigmailPrefs } = ChromeUtils.import(
-  "chrome://openpgp/content/modules/prefs.jsm"
-);
-const { EnigmailEncryption } = ChromeUtils.import(
-  "chrome://openpgp/content/modules/encryption.jsm"
-);
-const { EnigmailDialog } = ChromeUtils.import(
-  "chrome://openpgp/content/modules/dialog.jsm"
-);
-const { EnigmailConstants } = ChromeUtils.import(
-  "chrome://openpgp/content/modules/constants.jsm"
-);
-
-const keyAlgorithms = [];
-const mimeHashAlgorithms = [
-  null,
-  "sha1",
-  "ripemd160",
-  "sha256",
-  "sha384",
-  "sha512",
-  "sha224",
-  "md5",
-];
-
-var EnigmailHash = {
-  determineAlgorithm(win, uiFlags, fromMailAddr, hashAlgoObj) {
-    EnigmailLog.DEBUG("hash.jsm: determineAlgorithm\n");
-
-    if (!win) {
-      win = EnigmailWindows.getMostRecentWindow();
-    }
-
-    const sendFlags =
-      EnigmailConstants.SEND_TEST | EnigmailConstants.SEND_SIGNED;
-    const hashAlgo =
-      mimeHashAlgorithms[EnigmailPrefs.getPref("mimeHashAlgorithm")];
-
-    if (typeof keyAlgorithms[fromMailAddr] != "string") {
-      // hash algorithm not yet known
-
-      const testUiFlags = EnigmailConstants.UI_TEST;
-      const listener = {
-        stdoutData: "",
-        stderrData: "",
-        exitCode: -1,
-        stdin(pipe) {
-          pipe.write("Dummy Test");
-          pipe.close();
-        },
-        stdout(data) {
-          this.stdoutData += data;
-        },
-        stderr(data) {
-          this.stderrData += data;
-        },
-        done(exitCode) {
-          this.exitCode = exitCode;
-        },
-      };
-
-      let errorMsgObj = {};
-      let statusFlagsObj = {};
-      const proc = EnigmailEncryption.encryptMessageStart(
-        win,
-        testUiFlags,
-        fromMailAddr,
-        "",
-        "",
-        hashAlgo,
-        sendFlags,
-        listener,
-        statusFlagsObj,
-        errorMsgObj
-      );
-
-      if (!proc) {
-        hashAlgoObj.errorMsg = errorMsgObj.value;
-        hashAlgoObj.statusFlags = statusFlagsObj.value;
-        return 1;
-      }
-
-      proc.wait();
-
-      const msgText = listener.stdoutData;
-      const exitCode = listener.exitCode;
-
-      const retStatusObj = {};
-      let exitCode2 = EnigmailEncryption.encryptMessageEnd(
-        fromMailAddr,
-        listener.stderrData,
-        exitCode,
-        testUiFlags,
-        sendFlags,
-        10,
-        retStatusObj
-      );
-
-      if (exitCode2 === 0 && !msgText) {
-        exitCode2 = 1;
-      }
-      // if (exitCode2 > 0) exitCode2 = -exitCode2;
-
-      if (exitCode2 !== 0) {
-        // Abormal return
-        if (retStatusObj.statusFlags & EnigmailConstants.BAD_PASSPHRASE) {
-          // "Unremember" passphrase on error return
-          retStatusObj.errorMsg = EnigmailLocale.getString("badPhrase");
-        }
-        EnigmailDialog.alert(win, retStatusObj.errorMsg);
-        return exitCode2;
-      }
-
-      let hashAlgorithm = "sha1"; // default as defined in RFC 4880, section 7 is MD5 -- but that's outdated
-
-      const m = msgText.match(/^(Hash: )(.*)$/m);
-      if (m && m.length > 2 && m[1] == "Hash: ") {
-        hashAlgorithm = m[2].toLowerCase();
-      } else {
-        EnigmailLog.DEBUG(
-          "hash.jsm: determineAlgorithm: no hashAlgorithm specified - using MD5\n"
-        );
-      }
-
-      for (let i = 1; i < mimeHashAlgorithms.length; i++) {
-        if (mimeHashAlgorithms[i] === hashAlgorithm) {
-          EnigmailLog.DEBUG(
-            "hash.jsm: determineAlgorithm: found hashAlgorithm " +
-              hashAlgorithm +
-              "\n"
-          );
-          keyAlgorithms[fromMailAddr] = hashAlgorithm;
-          hashAlgoObj.value = hashAlgorithm;
-          return 0;
-        }
-      }
-
-      EnigmailLog.ERROR(
-        "hash.jsm: determineAlgorithm: no hashAlgorithm found\n"
-      );
-      return 2;
-    }
-
-    EnigmailLog.DEBUG(
-      "hash.jsm: determineAlgorithm: hashAlgorithm " +
-        keyAlgorithms[fromMailAddr] +
-        " is cached\n"
-    );
-    hashAlgoObj.value = keyAlgorithms[fromMailAddr];
-
-    return 0;
-  },
-};
--- a/mail/extensions/openpgp/content/modules/keyRing.jsm
+++ b/mail/extensions/openpgp/content/modules/keyRing.jsm
@@ -259,22 +259,28 @@ var EnigmailKeyRing = {
     EnigmailLog.DEBUG(
       "keyRing.jsm: getSecretKeyByUserId: '" + searchTerm + "'\n"
     );
     let keyList = this.getKeysByUserId(searchTerm, true);
 
     result.all = [];
     result.best = null;
 
+    var nowDate = new Date();
+    var nowSecondsSinceEpoch = nowDate.valueOf() / 1000;
+
     for (let key of keyList) {
       if (
         key.secretAvailable &&
         key.getEncryptionValidity().keyValid &&
         key.getSigningValidity().keyValid
       ) {
+        if (key.expiryTime < nowSecondsSinceEpoch) {
+          continue;
+        }
         result.all.push(key);
         if (!result.best) {
           result.best = key;
         } else if (
           result.best.algoSym === key.algoSym &&
           result.best.keySize === key.keySize
         ) {
           if (key.expiryTime > result.best.expiryTime) {
@@ -440,36 +446,38 @@ var EnigmailKeyRing = {
    * @param userId            String   - space or comma separated list of keys to export. Specification by
    *                                     key ID, fingerprint, or userId
    * @param outputFile        String or nsIFile - output file name or Object - or NULL
    * @param exitCodeObj       Object   - o.value will contain exit code
    * @param errorMsgObj       Object   - o.value will contain error message from GnuPG
    *
    * @return String - if outputFile is NULL, the key block data; "" if a file is written
    */
-  extractKey(includeSecretKey, id, outputFile, exitCodeObj, errorMsgObj) {
-    EnigmailLog.DEBUG("keyRing.jsm: EnigmailKeyRing.extractKey: " + id + "\n");
+  extractKey(includeSecretKey, idArray, outputFile, exitCodeObj, errorMsgObj) {
+    EnigmailLog.DEBUG(
+      "keyRing.jsm: EnigmailKeyRing.extractKey: " + idArray + "\n"
+    );
     exitCodeObj.value = -1;
 
     if (includeSecretKey) {
       throw new Error("extractKey with secret key not implemented");
     }
 
-    if (!id.length) {
+    if (!idArray.length) {
       return "";
     }
 
-    if (id.includes(" ")) {
+    if (idArray.length > 1) {
       throw new Error(
         "keyRing.jsm: EnigmailKeyRing.extractKey: multiple IDs not yet implemented"
       );
     }
 
     const cApi = EnigmailCryptoAPI();
-    let keyBlock = cApi.sync(cApi.getPublicKey(id));
+    let keyBlock = cApi.sync(cApi.getPublicKey(idArray[0]));
     if (!keyBlock) {
       errorMsgObj.value = EnigmailLocale.getString("failKeyExtract");
       return "";
     }
 
     exitCodeObj.value = 0;
     if (outputFile) {
       if (
--- a/mail/extensions/openpgp/content/modules/mimeEncrypt.jsm
+++ b/mail/extensions/openpgp/content/modules/mimeEncrypt.jsm
@@ -230,40 +230,16 @@ PgpMimeEncrypt.prototype = {
 
       if (this.sendFlags & EnigmailConstants.SEND_PGP_MIME) {
         if (this.sendFlags & EnigmailConstants.SEND_ENCRYPTED) {
           // applies to encrypted and signed & encrypted
           this.cryptoMode = MIME_ENCRYPTED;
         } else if (this.sendFlags & EnigmailConstants.SEND_SIGNED) {
           this.cryptoMode = MIME_SIGNED;
           this.hashAlgorithm = "SHA256"; // TODO: coordinate with RNP.jsm
-
-          /*
-          let hashAlgoObj = {};
-          if (
-            EnigmailHash.determineAlgorithm(
-              this.win,
-              this.UIFlags,
-              this.senderEmailAddr,
-              hashAlgoObj
-            ) === 0
-          ) {
-            this.hashAlgorithm = hashAlgoObj.value;
-          } else {
-            if (
-              "statusFlags" in hashAlgoObj &&
-              hashAlgoObj.statusFlags !== 0 &&
-              hashAlgoObj.errorMsg
-            ) {
-              EnigmailDialog.alert(this.win, hashAlgoObj.errorMsg);
-            }
-
-            throw Cr.NS_ERROR_FAILURE;
-          }
-          */
         }
       } else {
         throw Cr.NS_ERROR_NOT_IMPLEMENTED;
       }
 
       this.cryptoBoundary = EnigmailMime.createBoundary();
       this.startCryptoHeaders();
     } catch (ex) {
@@ -525,17 +501,16 @@ PgpMimeEncrypt.prototype = {
       this.writeToPipe("\r\n--" + this.encHeader + "--\r\n");
       if (this.cryptoMode == MIME_SIGNED) {
         this.writeOut("\r\n--" + this.encHeader + "--\r\n");
       }
     }
 
     let statusFlagsObj = {};
     let errorMsgObj = {};
-    //let proc =
     EnigmailEncryption.encryptMessageStart(
       this.win,
       this.UIFlags,
       this.senderEmailAddr,
       this.recipients,
       this.bccRecipients,
       this.hashAlgorithm,
       this.sendFlags,
--- a/mail/extensions/openpgp/content/modules/rnp.jsm
+++ b/mail/extensions/openpgp/content/modules/rnp.jsm
@@ -1366,13 +1366,78 @@ var RNP = {
 
       result = char_array.readString();
     }
 
     RNPLib.rnp_output_destroy(output_to_memory);
     RNPLib.rnp_key_handle_destroy(key);
     return result;
   },
+
+  getNewRevocation(id) {
+    let result = "";
+    let key = this.getKeyHandleByIdentifier(RNPLib.ffi, id);
+
+    if (key.isNull()) {
+      return result;
+    }
+
+    let out_final = new RNPLib.rnp_output_t();
+    RNPLib.rnp_output_to_memory(out_final.address(), 0);
+
+    let out_binary = new RNPLib.rnp_output_t();
+    let rv;
+    if (
+      (rv = RNPLib.rnp_output_to_armor(
+        out_final,
+        out_binary.address(),
+        "public key"
+      ))
+    ) {
+      throw new Error("rnp_output_to_armor failed:" + rv);
+    }
+
+    if (
+      (rv = RNPLib.rnp_key_export_revocation(
+        key,
+        out_binary,
+        0,
+        null,
+        null,
+        null
+      ))
+    ) {
+      throw new Error("rnp_key_export_revocation failed: " + rv);
+    }
+
+    if ((rv = RNPLib.rnp_output_finish(out_binary))) {
+      throw new Error("rnp_output_finish failed: " + rv);
+    }
+
+    let result_buf = new ctypes.uint8_t.ptr();
+    let result_len = new ctypes.size_t();
+    let exitCode = RNPLib.rnp_output_memory_get_buf(
+      out_final,
+      result_buf.address(),
+      result_len.address(),
+      false
+    );
+
+    console.debug(exitCode);
+
+    if (!exitCode) {
+      let char_array = ctypes.cast(
+        result_buf,
+        ctypes.char.array(result_len.value).ptr
+      ).contents;
+      result = char_array.readString();
+    }
+
+    RNPLib.rnp_output_destroy(out_binary);
+    RNPLib.rnp_output_destroy(out_final);
+    RNPLib.rnp_key_handle_destroy(key);
+    return result;
+  },
 };
 
 // exports
 
 const EXPORTED_SYMBOLS = ["RNP"];
--- a/mail/extensions/openpgp/content/modules/rnpLib.jsm
+++ b/mail/extensions/openpgp/content/modules/rnpLib.jsm
@@ -872,16 +872,44 @@ function enableRNPLibJS() {
       "rnp_key_export",
       abi,
       rnp_result_t,
       rnp_key_handle_t,
       rnp_output_t,
       ctypes.uint32_t
     ),
 
+    rnp_key_export_revocation: librnp.declare(
+      "rnp_key_export_revocation",
+      abi,
+      rnp_result_t,
+      rnp_key_handle_t,
+      rnp_output_t,
+      ctypes.uint32_t,
+      ctypes.char.ptr,
+      ctypes.char.ptr,
+      ctypes.char.ptr
+    ),
+
+    rnp_output_to_armor: librnp.declare(
+      "rnp_output_to_armor",
+      abi,
+      rnp_result_t,
+      rnp_output_t,
+      rnp_output_t.ptr,
+      ctypes.char.ptr
+    ),
+
+    rnp_output_finish: librnp.declare(
+      "rnp_output_finish",
+      abi,
+      rnp_result_t,
+      rnp_output_t
+    ),
+
     rnp_result_t,
     rnp_ffi_t,
     rnp_password_cb_t,
     rnp_input_t,
     rnp_output_t,
     rnp_key_handle_t,
     rnp_uid_handle_t,
     rnp_identifier_iterator_t,
--- a/mail/extensions/openpgp/content/strings/enigmail.dtd
+++ b/mail/extensions/openpgp/content/strings/enigmail.dtd
@@ -1,14 +1,13 @@
 <!ENTITY enigmail.label                   "Gine-Liam">
 <!ENTITY enigmail.autocrypt.label         "Autocrypt">
 
 <!ENTITY enigmail.keyUserId.label         "Account / User ID">
 <!ENTITY enigmail.keygenTitle.label       "Generate OpenPGP Key">
-<!ENTITY enigmail.useForSigning.label     "Use generated key for the selected identity">
 <!ENTITY enigmail.keyNoPassphrase.label   "No passphrase">
 <!ENTITY enigmail.keyPassphrase.label     "Passphrase">
 <!ENTITY enigmail.keyPassphraseRepeat.label "Passphrase (repeat)">
 <!ENTITY enigmail.generateKey.tooltip     "Generates a new OpenPGP compliant key for encryption and/or signing">
 <!ENTITY enigmail.cancelKey.label         "Cancel">
 <!ENTITY enigmail.cancelKey.tooltip       "Cancel Key Generation">
 <!ENTITY enigmail.keyGen.expiry.title     "Key expiry">
 <!ENTITY enigmail.keyGen.expire.label     "Key expires in">
deleted file mode 100644
--- a/mail/extensions/openpgp/content/ui/enigmailEditIdentity.js
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
- */
-
-/* global gAccount: false, gIdentity: false, onOk: false, smimeOnAcceptEditor: false */
-
-"use strict";
-
-var EnigmailFuncs = ChromeUtils.import(
-  "chrome://openpgp/content/modules/funcs.jsm"
-).EnigmailFuncs;
-var EnigmailLocale = ChromeUtils.import(
-  "chrome://openpgp/content/modules/locale.jsm"
-).EnigmailLocale;
-var EnigmailWindows = ChromeUtils.import(
-  "chrome://openpgp/content/modules/windows.jsm"
-).EnigmailWindows;
-var EnigmailDialog = ChromeUtils.import(
-  "chrome://openpgp/content/modules/dialog.jsm"
-).EnigmailDialog;
-
-if (!Enigmail) {
-  var Enigmail = {};
-}
-
-Enigmail.edit = {
-  account: null,
-  identity: null,
-  enablePgp: null,
-  pgpKeyMode: null,
-  pgpKeyId: null,
-  cryptoChoicesEnabled: null,
-  signingPolicy: null, // account specific: by default sign
-  encryptionPolicy: null, // account specific: by default encrypt
-  pgpMimeMode: null, // account specific: by default pgp/mime
-  pgpSignPlainPolicy: null,
-  pgpSignEncPolicy: null,
-  autoEncryptDrafts: null,
-  openPgpSendKeyWithMsg: null,
-
-  onInit() {
-    // initialize all of our elements based on the current identity values....
-    EnigmailFuncs.collapseAdvanced(
-      document.getElementById("enigmail_PrefsBox"),
-      "hidden"
-    );
-
-    this.enablePgp = document.getElementById("enigmail_enablePgp");
-    this.pgpKeyMode = document.getElementById("enigmail_pgpKeyMode");
-    this.pgpKeyId = document.getElementById("enigmail_identity.pgpkeyId");
-    this.signingPolicy = document.getElementById("enigmail_sign_ifPossible");
-    this.encryptionPolicy = document.getElementById(
-      "enigmail_encrypt_ifPossible"
-    );
-    this.pgpMimeMode = document.getElementById("enigmail_pgpMimeMode");
-    this.autoEncryptDrafts = document.getElementById(
-      "enigmail_autoEncryptDrafts"
-    );
-    this.mimePreferOpenPGP = document.getElementById(
-      "enigmail_mimePreferOpenPGP"
-    );
-    this.isSingleIdEditor = !!document.getElementById("enigmail_singleId");
-    this.openPgpSendKeyWithMsg = document.getElementById(
-      "openpgp.sendKeyWithMsg"
-    );
-
-    if (this.identity) {
-      this.enablePgp.checked = this.identity.getBoolAttribute("enablePgp");
-      this.cryptoChoicesEnabled = this.enablePgp.checked;
-
-      var selectedItemId = null;
-      var keyPolicy = this.identity.getIntAttribute("pgpKeyMode");
-      switch (keyPolicy) {
-        case 1:
-          selectedItemId = "enigmail_keymode_usePgpkeyId";
-          break;
-        default:
-          selectedItemId = "enigmail_keymode_useFromAddress";
-          break;
-      }
-      this.pgpKeyMode.selectedItem = document.getElementById(selectedItemId);
-
-      var mimePolicy = this.identity.getIntAttribute("mimePreferOpenPGP");
-      switch (mimePolicy) {
-        case 1:
-          selectedItemId = "enigmail_mime_preferEnigmail";
-          break;
-        default:
-          selectedItemId = "enigmail_mime_preferSMime";
-          break;
-      }
-      this.mimePreferOpenPGP.selectedItem = document.getElementById(
-        selectedItemId
-      );
-
-      this.pgpKeyId.value = this.identity.getCharAttribute("pgpkeyId");
-      this.signingPolicy.checked =
-        this.identity.getIntAttribute("defaultSigningPolicy") > 0;
-      this.encryptionPolicy.checked =
-        this.identity.getIntAttribute("defaultEncryptionPolicy") > 0;
-      this.pgpMimeMode.checked = this.identity.getBoolAttribute("pgpMimeMode");
-      this.pgpSignEncPolicy.checked = this.identity.getBoolAttribute(
-        "pgpSignEncrypted"
-      );
-      this.pgpSignPlainPolicy.checked = this.identity.getBoolAttribute(
-        "pgpSignPlain"
-      );
-      this.autoEncryptDrafts.checked = this.identity.getBoolAttribute(
-        "autoEncryptDrafts"
-      );
-    } else {
-      this.enablePgp.checked = false;
-      this.cryptoChoicesEnabled = false;
-      this.pgpMimeMode.checked = true;
-      this.pgpSignEncPolicy.checked = true;
-      this.autoEncryptDrafts.checked = true;
-    }
-
-    // Disable all locked elements on the panel
-    //onLockPreference();
-    this.enableAllPrefs();
-  },
-
-  onLoadEditor() {
-    if (typeof gAccount == "object") {
-      this.account = gAccount;
-      this.identity = gIdentity;
-    } else if ("arguments" in window) {
-      this.identity = window.arguments[0].identity;
-      this.account = window.arguments[0].account;
-    }
-
-    if (this.identity) {
-      var idLabel = EnigmailLocale.getString("identityName", [
-        this.identity.identityName,
-      ]);
-      document.getElementById("enigmail_identityName").value = idLabel;
-    }
-
-    var dlg = document.getElementsByTagName("dialog")[0];
-    dlg.setAttribute(
-      "ondialogaccept",
-      "return Enigmail.edit.onAcceptEditor();"
-    );
-
-    this.onInit();
-  },
-
-  onAcceptEditor() {
-    try {
-      if (onOk() === false) {
-        return false;
-      }
-    } catch (ex) {}
-    this.onSave();
-    if (typeof smimeOnAcceptEditor == "function") {
-      return smimeOnAcceptEditor();
-    }
-    return true;
-  },
-
-  onSave() {
-    if (!this.identity) {
-      this.identity = gIdentity;
-    }
-    this.identity.setBoolAttribute("enablePgp", this.enablePgp.checked);
-    //To attach OpenPGP Key with the mail
-    this.identity.setBoolAttribute(
-      "attachPgpKey",
-      this.openPgpSendKeyWithMsg.checked
-    );
-
-    if (this.enablePgp.checked) {
-      // PGP is enabled
-      this.identity.setIntAttribute(
-        "pgpKeyMode",
-        this.pgpKeyMode.selectedItem.value
-      );
-      this.identity.setIntAttribute(
-        "mimePreferOpenPGP",
-        this.mimePreferOpenPGP.selectedItem.value
-      );
-      this.identity.setCharAttribute("pgpkeyId", this.pgpKeyId.value);
-      this.identity.setIntAttribute(
-        "defaultSigningPolicy",
-        this.signingPolicy.checked ? 1 : 0
-      );
-      this.identity.setIntAttribute(
-        "defaultEncryptionPolicy",
-        this.encryptionPolicy.checked ? 1 : 0
-      );
-      this.identity.setBoolAttribute("pgpMimeMode", this.pgpMimeMode.checked);
-      this.identity.setBoolAttribute(
-        "pgpSignEncrypted",
-        this.pgpSignEncPolicy.checked
-      );
-      this.identity.setBoolAttribute(
-        "pgpSignPlain",
-        this.pgpSignPlainPolicy.checked
-      );
-      this.identity.setBoolAttribute(
-        "autoEncryptDrafts",
-        this.autoEncryptDrafts.checked
-      );
-    }
-  },
-
-  toggleEnable() {
-    let newCryptoEnabled = !this.cryptoChoicesEnabled;
-
-    this.cryptoChoicesEnabled = newCryptoEnabled;
-    this.enableAllPrefs();
-  },
-
-  enableAllPrefs() {
-    var elem = document.getElementById("enigmail_bcEnablePgp");
-    if (this.cryptoChoicesEnabled) {
-      if (elem) {
-        elem.removeAttribute("disabled");
-      }
-    } else if (elem) {
-      elem.setAttribute("disabled", "true");
-    }
-
-    this.enableKeySel(this.cryptoChoicesEnabled && this.pgpKeyMode.value == 1);
-  },
-
-  enableKeySel(enable) {
-    if (enable) {
-      document
-        .getElementById("enigmail_bcUseKeyId")
-        .removeAttribute("disabled");
-    } else {
-      document
-        .getElementById("enigmail_bcUseKeyId")
-        .setAttribute("disabled", "true");
-    }
-  },
-
-  handleClick(event) {
-    if (event.target.hasAttribute("href")) {
-      EnigmailWindows.openMailTab(event.target.getAttribute("href"));
-    }
-  },
-
-  selectKeyId() {
-    var resultObj = {};
-    var inputObj = {};
-    inputObj.dialogHeader = EnigmailLocale.getString("encryptKeyHeader");
-    inputObj.options = "single,hidexpired,private,nosending";
-    var button = document.getElementById("enigmail_selectPgpKey");
-    var label = button.getAttribute("label");
-    inputObj.options += ",sendlabel=" + label;
-    inputObj.options += ",";
-
-    window.openDialog(
-      "chrome://openpgp/content/ui/enigmailKeySelection.xhtml",
-      "",
-      "dialog,modal,centerscreen,resizable",
-      inputObj,
-      resultObj
-    );
-    try {
-      if (resultObj.cancelled) {
-        return;
-      }
-      var selKey = resultObj.userList[0];
-      //selKey = "0x"+selKey.substring(10,18);
-      this.pgpKeyId.value = selKey;
-    } catch (ex) {
-      // cancel pressed -> don't send mail
-    }
-  },
-};
-
-window.addEventListener(
-  "load-enigmail",
-  Enigmail.edit.onLoadEditor.bind(Enigmail.edit)
-);
-
-document.addEventListener("dialogaccept", function(event) {
-  Enigmail.edit.onAcceptEditor();
-});
--- a/mail/extensions/openpgp/content/ui/enigmailKeygen.js
+++ b/mail/extensions/openpgp/content/ui/enigmailKeygen.js
@@ -24,37 +24,56 @@ EnigInitCommon("enigmailKeygen");
 
 var gAccountManager = Cc[ENIG_ACCOUNT_MANAGER_CONTRACTID].getService(
   Ci.nsIMsgAccountManager
 );
 
 var EnigmailCryptoAPI = ChromeUtils.import(
   "chrome://openpgp/content/modules/cryptoAPI.jsm"
 ).EnigmailCryptoAPI;
+var { EnigmailFiles } = ChromeUtils.import(
+  "chrome://openpgp/content/modules/files.jsm"
+);
 var OpenPGPMasterpass = ChromeUtils.import(
   "chrome://openpgp/content/modules/masterpass.jsm"
 ).OpenPGPMasterpass;
+var { RNP } = ChromeUtils.import("chrome://openpgp/content/modules/rnp.jsm");
 
 var gUserIdentityList;
 var gUserIdentityListPopup;
-var gUseForSigning;
 
 var gKeygenRequest;
 var gAllData = "";
 var gGeneratedKey = null;
 var gUsedId;
 
 const KEYGEN_CANCELLED = "cancelled";
+const DEFAULT_FILE_PERMS = 0o600;
+
+let revocationFilePrefix1 =
+  "This is a revocation certificate for the OpenPGP key:";
+let revocationFilePrefix2 = `
+A revocation certificate is a kind of "kill switch" to publicly
+declare that a key shall no longer be used.  It is not possible
+to retract such a revocation certificate once it has been published.
+
+Use it to revoke this key in case of a secret key compromise, or loss of
+the secret key, or loss of passphrase of the secret key.
+
+To avoid an accidental use of this file, a colon has been inserted
+before the 5 dashes below.  Remove this colon with a text editor
+before importing and publishing this revocation certificate.
+
+:`;
 
 function enigmailKeygenLoad() {
   EnigmailLog.DEBUG("enigmailKeygen.js: Load\n");
 
   gUserIdentityList = document.getElementById("userIdentity");
   gUserIdentityListPopup = document.getElementById("userIdentityPopup");
-  gUseForSigning = document.getElementById("useForSigning");
 
   //if (EnigmailGpg.getGpgFeature("supports-ecc-keys"))
   let eccElem = document.getElementById("keyType_ecc");
   eccElem.removeAttribute("hidden");
   updateKeySizeSel(eccElem);
   //document.getElementById("keyType").selectedItem = eccElem;
 
   if (gUserIdentityListPopup) {
@@ -98,92 +117,16 @@ function enigmailOnClose() {
 }
 
 function enigmailKeygenUnload() {
   EnigmailLog.DEBUG("enigmailKeygen.js: Unload\n");
 
   enigmailKeygenCloseRequest();
 }
 
-function enigmailKeygenTerminate(exitCode) {
-  EnigmailLog.DEBUG("enigmailKeygen.js: Terminate:\n");
-
-  var curId = gUsedId;
-
-  gKeygenRequest = null;
-
-  if (!gGeneratedKey || gGeneratedKey == KEYGEN_CANCELLED) {
-    if (!gGeneratedKey) {
-      EnigAlert(EnigGetString("keyGenFailed"));
-    }
-    return;
-  }
-
-  var progMeter = document.getElementById("keygenProgress");
-  progMeter.setAttribute("value", 100);
-
-  if (gGeneratedKey) {
-    if (gUseForSigning.checked) {
-      curId.setBoolAttribute("enablePgp", true);
-      curId.setIntAttribute("pgpKeyMode", 1);
-      curId.setCharAttribute("pgpkeyId", "0x" + gGeneratedKey);
-
-      EnigSavePrefs();
-
-      EnigmailWindows.keyManReloadKeys();
-
-      if (
-        EnigConfirm(
-          EnigGetString("keygenComplete", curId.email) +
-            "\n\n" +
-            EnigGetString("revokeCertRecommended"),
-          EnigGetString("keyMan.button.generateCert")
-        )
-      ) {
-        EnigCreateRevokeCert(gGeneratedKey, curId.email, closeAndReset);
-      } else {
-        closeAndReset();
-      }
-    } else if (
-      EnigConfirm(
-        EnigGetString("genCompleteNoSign") +
-          "\n\n" +
-          EnigGetString("revokeCertRecommended"),
-        EnigGetString("keyMan.button.generateCert")
-      )
-    ) {
-      EnigCreateRevokeCert(gGeneratedKey, curId.email, closeAndReset);
-      genAndSaveRevCert(gGeneratedKey, curId.email).then(
-        function() {
-          closeAndReset();
-        },
-        function() {
-          // do nothing
-        }
-      );
-    } else {
-      closeAndReset();
-    }
-  } else {
-    EnigAlert(EnigGetString("keyGenFailed"));
-    window.close();
-  }
-}
-
-/**
- * generate and save a revokation certificate.
- *
- * return: Promise object
- */
-
-function genAndSaveRevCert(keyId, uid) {
-  EnigmailLog.DEBUG("enigmailKeygen.js: genAndSaveRevCert\n");
-  throw new Error("Not implemented");
-}
-
 /**
  *  create a copy of the revokation cert at a user defined location
  */
 function saveRevCert(inputKeyFile, keyId, uid, resolve, reject) {
   let defaultFileName = uid.replace(/[\\/<>]/g, "");
   defaultFileName += " (0x" + keyId + ") rev.asc";
 
   let outFile = EnigFilePicker(
@@ -279,81 +222,68 @@ function enigmailKeygenStart() {
 
   var confirmMsg = EnigGetString("keyConfirm", idString);
 
   if (!EnigConfirm(confirmMsg, EnigGetString("keyMan.button.generateKey"))) {
     return;
   }
 
   try {
+    let newId = null;
     const cApi = EnigmailCryptoAPI();
-    let newId = cApi.sync(
+    newId = cApi.sync(
       cApi.genKey(
         idString,
         keyType,
         keySize,
         expiryTime,
         OpenPGPMasterpass.retrieveOpenPGPPassword()
       )
     );
     console.log("created new key with id: " + newId);
+    gGeneratedKey = newId;
   } catch (ex) {
     console.log(ex);
   }
 
   EnigmailWindows.keyManReloadKeys();
+
+  gKeygenRequest = null;
+
+  var progMeter = document.getElementById("keygenProgress");
+  progMeter.setAttribute("value", 100);
+
+  if (!gGeneratedKey || gGeneratedKey == KEYGEN_CANCELLED) {
+    EnigAlert(EnigGetString("keyGenFailed"));
+  } else {
+    console.debug("saving new key id " + gGeneratedKey);
+    curId.setCharAttribute("openpgp_key_id", gGeneratedKey);
+    EnigSavePrefs();
+  }
+
   closeAndReset();
 
-  /*
-  var proc = null;
-
-  var listener = {
-    onStartRequest: function() {},
-    onStopRequest: function(status) {
-      enigmailKeygenTerminate(status);
-    },
-    onDataAvailable: function(data) {
-      EnigmailLog.DEBUG("enigmailKeygen.js: onDataAvailable() " + data + "\n");
-
-      gAllData += data;
-      var keyCreatedIndex = gAllData.indexOf("[GNUPG:] KEY_CREATED");
-      if (keyCreatedIndex > 0) {
-        gGeneratedKey = gAllData.substr(keyCreatedIndex);
-        gGeneratedKey = gGeneratedKey.replace(/(.*\[GNUPG:\] KEY_CREATED . )([a-fA-F0-9]+)([\n\r].*)* /{{{remove-space-between-*-and-/-to-unconfuse-syntax-highlighting-editor}}}, "$2");
-        gAllData = gAllData.replace(/\[GNUPG:\] KEY_CREATED . [a-fA-F0-9]+[\n\r]/, "");
-      }
-      gAllData = gAllData.replace(/[\r\n]*\[GNUPG:\] GOOD_PASSPHRASE/g, "").replace(/([\r\n]*\[GNUPG:\] PROGRESS primegen )(.)( \d+ \d+)/g, "$2");
-      var progMeter = document.getElementById("keygenProgress");
-      var progValue = Number(progMeter.value);
-      progValue += (1 + (100 - progValue) / 200);
-      if (progValue >= 95) progValue = 10;
-      progMeter.setAttribute("value", progValue);
-    }
-  };
-
-  try {
-    gKeygenRequest = EnigmailKeyRing.generateKey(
-      EnigmailData.convertFromUnicode(userName),
-      "", // user id comment
-      EnigmailData.convertFromUnicode(userEmail),
-      expiryTime,
-      keySize,
-      keyType,
-      EnigmailData.convertFromUnicode(passphrase),
-      listener);
-  } catch (ex) {
-    EnigmailLog.DEBUG("enigmailKeygen.js: generateKey() failed with " + ex.toString() + "\n" + ex.stack + "\n");
+  let rev = RNP.getNewRevocation("0x" + gGeneratedKey);
+  if (!rev) {
+    throw new Error("failed to obtain revocation for key " + gGeneratedKey);
   }
 
-  if (!gKeygenRequest) {
-    EnigAlert(EnigGetString("keyGenFailed"));
-  }
+  let revFull =
+    revocationFilePrefix1 +
+    "\n\n" +
+    gGeneratedKey +
+    "\n" +
+    revocationFilePrefix2 +
+    rev;
 
-  EnigmailLog.WRITE("enigmailKeygen.js: Start: gKeygenRequest = " + gKeygenRequest + "\n");
-  */
+  let revFile = EnigmailApp.getProfileDirectory();
+  revFile.append("0x" + gGeneratedKey + "_rev.asc");
+
+  // create a revokation cert in the TB profile directoy
+  EnigmailFiles.writeFileContents(revFile, revFull, DEFAULT_FILE_PERMS);
 }
 
 function abortKeyGeneration() {
   gGeneratedKey = KEYGEN_CANCELLED;
   enigmailKeygenCloseRequest();
 }
 
 function enigmailKeygenCancel() {
--- a/mail/extensions/openpgp/content/ui/enigmailKeygen.xhtml
+++ b/mail/extensions/openpgp/content/ui/enigmailKeygen.xhtml
@@ -32,20 +32,16 @@
 
 <vbox class="enigmailGroupbox" id="userIdBox">
   <hbox orient="horizontal" align="center">
     <label value="&enigmail.keyUserId.label;" control="userIdentity"/>
     <menulist id="userIdentity" label="..." flex="1">
       <menupopup id="userIdentityPopup"/>
     </menulist>
   </hbox>
-
-  <checkbox id="useForSigning"
-            label="&enigmail.useForSigning.label;"
-            checked="true" />
 </vbox>
 
 
 <tabbox flex="1">
   <tabs id="settingsTabBox">
     <tab id="basicTab"    label="&enigmail.keyGen.expiry.title;"/>
     <tab id="advancedTab" label="&enigmail.advancedPrefsButton.label;"/>
   </tabs>
--- a/mail/extensions/openpgp/content/ui/enigmailMessengerOverlay.js
+++ b/mail/extensions/openpgp/content/ui/enigmailMessengerOverlay.js
@@ -88,19 +88,16 @@ var EnigmailDecryption = ChromeUtils.imp
   "chrome://openpgp/content/modules/decryption.jsm"
 ).EnigmailDecryption;
 var EnigmailAttachment = ChromeUtils.import(
   "chrome://openpgp/content/modules/attachment.jsm"
 ).EnigmailAttachment;
 var EnigmailConstants = ChromeUtils.import(
   "chrome://openpgp/content/modules/constants.jsm"
 ).EnigmailConstants;
-var EnigmailKeyUsability = ChromeUtils.import(
-  "chrome://openpgp/content/modules/keyUsability.jsm"
-).EnigmailKeyUsability;
 var EnigmailURIs = ChromeUtils.import(
   "chrome://openpgp/content/modules/uris.jsm"
 ).EnigmailURIs;
 var EnigmailProtocolHandler = ChromeUtils.import(
   "chrome://openpgp/content/modules/protocolHandler.jsm"
 ).EnigmailProtocolHandler;
 var EnigmailAutocrypt = ChromeUtils.import(
   "chrome://openpgp/content/modules/autocrypt.jsm"
@@ -577,20 +574,16 @@ Enigmail.msg = {
   isAutocryptEnabled() {
     try {
       let email = EnigmailFuncs.stripEmail(
         gFolderDisplay.selectedMessage.recipients
       );
       let maybeIdent = EnigmailStdlib.getIdentityForEmail(email);
 
       if (maybeIdent && maybeIdent.identity) {
-        if (!maybeIdent.identity.getBoolAttribute("enablePgp")) {
-          return false;
-        }
-
         let acct = EnigmailFuncs.getAccountForIdentity(maybeIdent.identity);
         return acct.incomingServer.getBoolValue("enableAutocrypt");
       }
     } catch (ex) {}
 
     return false;
   },
 
--- a/mail/extensions/openpgp/content/ui/enigmailMsgComposeOverlay.js
+++ b/mail/extensions/openpgp/content/ui/enigmailMsgComposeOverlay.js
@@ -1031,20 +1031,21 @@ Enigmail.msg = {
       this.attachOwnKeyObj.attachedKey &&
       this.attachOwnKeyObj.attachedKey != id
     ) {
       // remove attached key if user ID changed
       this.removeAttachedKey();
     }
 
     if (!this.attachOwnKeyObj.attachedKey) {
-      var attachedObj = this.extractAndAttachKey([id], true);
+      let hex = "0x" + id;
+      var attachedObj = this.extractAndAttachKey([hex], true);
       if (attachedObj) {
         this.attachOwnKeyObj.attachedObj = attachedObj;
-        this.attachOwnKeyObj.attachedKey = id;
+        this.attachOwnKeyObj.attachedKey = hex;
       }
     }
   },
 
   attachKey() {
     EnigmailLog.DEBUG(
       "enigmailMsgComposeOverlay.js: Enigmail.msg.attachKey: \n"
     );
@@ -1068,17 +1069,17 @@ Enigmail.msg = {
         return;
       }
       this.extractAndAttachKey(resultObj.userList, true);
     } catch (ex) {
       // cancel pressed -> do nothing
     }
   },
 
-  extractAndAttachKey(uid, warnOnError) {
+  extractAndAttachKey(uidArray, warnOnError) {
     EnigmailLog.DEBUG(
       "enigmailMsgComposeOverlay.js: Enigmail.msg.extractAndAttachKey: \n"
     );
     var enigmailSvc = EnigmailCore.getService(window);
     if (!enigmailSvc) {
       return null;
     }
 
@@ -1099,33 +1100,42 @@ Enigmail.msg = {
     }
     tmpFile.append("key.asc");
     tmpFile.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0o600);
 
     // save file
     var exitCodeObj = {};
     var errorMsgObj = {};
 
-    EnigmailKeyRing.extractKey(false, uid, tmpFile, exitCodeObj, errorMsgObj);
+    EnigmailKeyRing.extractKey(
+      false,
+      uidArray,
+      tmpFile,
+      exitCodeObj,
+      errorMsgObj
+    );
     if (exitCodeObj.value !== 0) {
       if (warnOnError) {
         EnigmailDialog.alert(window, errorMsgObj.value);
       }
       return null;
     }
 
     // create attachment
     var ioServ = Services.io;
     var tmpFileURI = ioServ.newFileURI(tmpFile);
     var keyAttachment = Cc[
       "@mozilla.org/messengercompose/attachment;1"
     ].createInstance(Ci.nsIMsgAttachment);
     keyAttachment.url = tmpFileURI.spec;
-    if (uid.length == 1 && uid[0].search(/^(0x)?[a-fA-F0-9]+$/) === 0) {
-      keyAttachment.name = uid[0].substr(-16, 16) + ".asc";
+    if (
+      uidArray.length == 1 &&
+      uidArray[0].search(/^(0x)?[a-fA-F0-9]+$/) === 0
+    ) {
+      keyAttachment.name = uidArray[0].substr(-16, 16) + ".asc";
       if (keyAttachment.name.search(/^0x/) < 0) {
         keyAttachment.name = "0x" + keyAttachment.name;
       }
     } else {
       keyAttachment.name = "pgpkeys.asc";
     }
     keyAttachment.temporary = true;
     keyAttachment.contentType = "application/pgp-keys";
@@ -1626,42 +1636,16 @@ Enigmail.msg = {
 
         if (s) s.removeAttribute("collapsed");
         if (e) e.removeAttribute("collapsed");
         if (s) s.setAttribute("collapsed", "true");
         if (e) e.setAttribute("collapsed", "true");
   },
   */
 
-  /**
-   * determine if own key may be attached.
-   * @result: Number:
-   *          -1: account not enabled for Enigmail
-   *           0: account enabled but key mode set to "by Email address"
-   *           1: account enabled; key specified
-   */
-  /*
-  allowAttachOwnKey: function() {
-
-    let allow = -1;
-
-    if (Enigmail.msg.isEnigmailEnabledForIdentity()) {
-      allow = 0;
-      if (this.identity.getIntAttribute("pgpKeyMode") > 0) {
-        let keyIdValue = this.identity.getCharAttribute("pgpkeyId");
-        if (keyIdValue.search(/^ *(0x)?[0-9a-fA-F]* *$/) === 0) {
-          allow = 1;
-        }
-      }
-    }
-
-    return allow;
-  },
-  */
-
   /* check if encryption is possible (have keys for everyone or not)
    */
   determineSendFlags() {
     EnigmailLog.DEBUG(
       "enigmailMsgComposeOverlay.js: Enigmail.msg.focusChange: Enigmail.msg.determineSendFlags\n"
     );
 
     let detailsObj = {};
@@ -1702,122 +1686,16 @@ Enigmail.msg = {
     // process and signal new resulting state
     //this.processFinalState();
     this.updateStatusBar();
 
     return detailsObj;
   },
 
   /*
-  setChecked: function(elementId, checked) {
-    let elem = document.getElementById(elementId);
-    if (elem) {
-      if (checked) {
-        elem.setAttribute("checked", "true");
-      }
-      else
-        elem.removeAttribute("checked");
-    }
-  },
-  */
-
-  /*
-  setMenuSettings: function(postfix) {
-    EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.setMenuSettings: postfix=" + postfix + "\n");
-
-    let enigmailEnabled = Enigmail.msg.wasEnigmailEnabledForIdentity();
-    let smimeEnabled = Enigmail.msg.isSmimeEnabled();
-
-    const SIGN = EnigmailConstants.SEND_SIGNED;
-    const ENCRYPT = EnigmailConstants.SEND_ENCRYPTED;
-
-    var elem = document.getElementById("enigmail_compose_sign_item" + postfix);
-    if (elem) {
-      elem.setAttribute("label", this.statusSignedStr);
-      switch (gSendSigned) {
-          //elem.setAttribute("checked", "true");
-          //elem.setAttribute("checked", "false");
-      }
-    }
-
-    elem = document.getElementById("enigmail_compose_encrypt_item" + postfix);
-    if (elem) {
-      elem.setAttribute("label", this.statusEncryptedStr);
-      switch (gSendEncrypted) {
-          //elem.setAttribute("checked", "true");
-          //elem.setAttribute("checked", "false");
-      }
-    }
-
-    elem = document.getElementById("enigmail_compose_pgpmime_item" + postfix);
-    if (elem) {
-      elem.setAttribute("label", this.statusPGPMimeStr);
-      if (enigmailEnabled) {
-        elem.removeAttribute("disabled");
-      }
-      else {
-        elem.setAttribute("disabled", "true");
-      }
-
-          //elem.setAttribute("checked", "true");
-          //elem.setAttribute("checked", "false");
-
-      elem = document.getElementById("enigmail_compose_inline_item" + postfix);
-      if (elem) {
-        elem.setAttribute("label", this.statusInlinePGPStr);
-        if (enigmailEnabled) {
-          elem.removeAttribute("disabled");
-        }
-        else {
-          elem.setAttribute("disabled", "true");
-        }
-
-            //elem.setAttribute("checked", "true");
-            //elem.setAttribute("checked", "false");
-      }
-
-      elem = document.getElementById("enigmail_compose_smime_item" + postfix);
-      if (elem) {
-        elem.setAttribute("label", this.statusSMimeStr);
-        if (smimeEnabled) {
-          elem.removeAttribute("disabled");
-        }
-        else {
-          elem.setAttribute("disabled", "true");
-        }
-
-            //elem.setAttribute("checked", "true");
-            //elem.setAttribute("checked", "false");
-      }
-
-      elem = document.getElementById("enigmail_insert_own_key");
-      if (elem) {
-        if (this.identity.getIntAttribute("pgpKeyMode") > 0) {
-          elem.setAttribute("checked", gAttachMyPublicPGPKey.toString());
-          elem.removeAttribute("disabled");
-        }
-        else {
-          elem.setAttribute("disabled", "true");
-        }
-      }
-
-      elem = document.getElementById("enigmail_encrypt_subject");
-      if (elem) {
-        if (enigmailEnabled) {
-          elem.setAttribute("checked", this.protectHeaders ? "true" : "false");
-          elem.removeAttribute("disabled");
-        }
-        else {
-          elem.setAttribute("disabled", "true");
-        }
-      }
-  },
-  */
-
-  /*
   displaySecuritySettings: function() {
     EnigmailLog.DEBUG("enigmailMsgComposeOverlay.js: Enigmail.msg.displaySecuritySettings\n");
 
     var inputObj = {
       gSendEncrypted: gSendEncrypted,
       gSendSigned: gSendSigned,
       success: false,
       resetDefaults: false
@@ -1877,56 +1755,18 @@ Enigmail.msg = {
       (gSendSigned) + 
       (gAttachMyPublicPGPKey ? "1" : "0") + (doEncrypt && this.protectHeaders ? "1" : "0");
 
     this.setAdditionalHeader("X-Enigmail-Draft-Status", draftStatus);
     */
   },
 
   getSenderUserId() {
-    var userIdValue = null;
-
-    if (this.identity.getIntAttribute("pgpKeyMode") > 0) {
-      userIdValue = this.identity.getCharAttribute("pgpkeyId");
-
-      if (!userIdValue) {
-        var mesg = EnigmailLocale.getString("composeSpecifyEmail");
-
-        var valueObj = {
-          value: userIdValue,
-        };
-
-        if (EnigmailDialog.promptValue(window, mesg, valueObj)) {
-          userIdValue = valueObj.value;
-        }
-      }
-
-      if (userIdValue) {
-        this.identity.setCharAttribute("pgpkeyId", userIdValue);
-      } else {
-        this.identity.setIntAttribute("pgpKeyMode", 0);
-      }
-    }
-
-    if (typeof userIdValue != "string") {
-      EnigmailLog.DEBUG(
-        "enigmailMsgComposeOverlay.js: Enigmail.msg.getSenderUserId: type of userIdValue=" +
-          typeof userIdValue +
-          "\n"
-      );
-      userIdValue = this.identity.email;
-    }
-
-    if (this.identity.getIntAttribute("pgpKeyMode") === 0) {
-      let key = EnigmailKeyRing.getSecretKeyByEmail(userIdValue);
-      if (key) {
-        userIdValue = "0x" + key.fpr;
-      }
-    }
-    return userIdValue;
+    let keyId = this.identity.getUnicharAttribute("openpgp_key_id");
+    return "0x" + keyId;
   },
 
   /* process rules and find keys for passed email addresses
    * This is THE core method to prepare sending encryptes emails.
    * - it processes the recipient rules (if not disabled)
    * - it
    *
    * @sendFlags:    Longint - all current combined/processed send flags (incl. optSendFlags)
@@ -2836,17 +2676,18 @@ Enigmail.msg = {
       }
 
       sendFlags = result.sendFlags;
       let toAddrStr = result.toAddrStr;
       let bccAddrStr = result.bccAddrStr;
       let keyMap = result.keyMap;
 
       if (gAttachMyPublicPGPKey) {
-        this.attachOwnKey(rcpt.fromAddr);
+        let keyId = this.identity.getUnicharAttribute("openpgp_key_id");
+        this.attachOwnKey(keyId);
       }
 
       /*
       if (this.preferPgpOverSmime(sendFlags) === 0) {
         // use S/MIME
         Attachments2CompFields(gMsgCompose.compFields); // update list of attachments
         sendFlags = 0;
         return true;
@@ -3416,49 +3257,16 @@ Enigmail.msg = {
 
   getCurrentIncomingServer() {
     let currentAccountKey = getCurrentAccountKey();
     let account = MailServices.accounts.getAccount(currentAccountKey);
 
     return account.incomingServer; /* returns nsIMsgIncomingServer */
   },
 
-  /*
-  setAutocryptHeader: function() {
-    if (!this.isAutocryptEnabled()) return;
-
-    this.identity = getCurrentIdentity();
-    let fromMail = this.identity.email;
-
-    try {
-      fromMail = EnigmailFuncs.stripEmail(gMsgCompose.compFields.from);
-    }
-    catch (ex) {}
-
-    let key;
-    if (this.identity.getIntAttribute("pgpKeyMode") > 0) {
-      key = EnigmailKeyRing.getKeyById(this.identity.getCharAttribute("pgpkeyId"));
-    }
-    else {
-      key = EnigmailKeyRing.getSecretKeyByEmail(this.identity.email);
-    }
-
-    if (key) {
-      let srv = this.getCurrentIncomingServer();
-      let prefMutual = (srv.getIntValue("acPreferEncrypt") > 0 ? "; prefer-encrypt=mutual" : "");
-
-      let k = key.getMinimalPubKey(fromMail);
-      if (k.exitCode === 0) {
-        let keyData = " " + k.keyData.replace(/(.{72})/g, "$1\r\n ").replace(/\r\n $/, "");
-        this.setAdditionalHeader('Autocrypt', 'addr=' + fromMail + prefMutual + '; keydata=\r\n' + keyData);
-      }
-    }
-  },
-  */
-
   fromChangedListener(event) {
     EnigmailLog.DEBUG(
       "enigmailMsgComposeOverlay.js: Enigmail.msg.fromChangedListener\n"
     );
 
     /* TODO:
      * reset gSendSigned, gAttachMyPublicPGPKey, gSendEncrypted, gOptionalEncryption
      * to account's default setting, but only if settings haven't been touched