def keys_export(self, keyids): """ Return string containing keys in list ``keyids`` in ASCII armor format :param keyid: see :func:`batzenca.gnupg.GnuPG.key_get` for accepted formats. """ from pyme.core import Data export_keys = Data() keys = [self.key_get(keyid) for keyid in keyids] self.ctx.op_export_keys(keys, 0, export_keys) export_keys.seek(0,0) return export_keys.read()
def keys_export(self, keyids): """ Return string containing keys in list ``keyids`` in ASCII armor format :param keyid: see :func:`batzenca.gnupg.GnuPG.key_get` for accepted formats. """ from pyme.core import Data export_keys = Data() keys = [self.key_get(keyid) for keyid in keyids] self.ctx.op_export_keys(keys, 0, export_keys) export_keys.seek(0, 0) return export_keys.read()
def aroundKeyPressEvent(self, evt, _old=''): if self.state == "showAnswer": key = unicode(evt.text()) if evt.key() == SHOW_PASS_KEY: if self.currentCard.fact.model.name == MODEL: mf = self.mainWin.mainText.page().mainFrame() """ Set up the PyMe stuff """ c = Context(); c.set_passphrase_cb(passCallback) c.set_armor(1); cipher = Data(re.sub("<br[^>]*>","\n",self.currentCard.fact['GPG'].encode('ascii'))) cipher.seek(0,0) """ Try to decrypt the password """ try: plain = Data(); c.op_decrypt(cipher, plain); plain.seek(0,0); QMessageBox.information(mw, "Password", "Your password is %s" % unicode(plain.read(), 'utf-8')) except GPGMEError, e: QMessageBox.information(mw, "Error", "Could not decrypt your password.\nError: " + str(e)) evt.accept() return
def change_key_trust(self, key, new_trust): val_dict = { "state": "start", "start keyedit.prompt": ("trust", "trust"), "trust edit_ownertrust.value": ("prompt", "%d" % new_trust), "prompt edit_ownertrust.set_ultimate.okay": ("prompt", "Y"), "prompt keyedit.prompt": ("finish", "quit") } out = Data() self.context.op_edit(key, self.editor_func, val_dict, out)
def format_sec_message(self, addrs, pub_gpg_keys): """ Create a GPG message (encrypted with the given public keys) """ from pyme.core import Data from StringIO import StringIO c = self.c plain = StringIO() plain.write("-- SECRET - This file contains Bitcoin private keys! --\n\n") plain.write("Index,Address,Private Key\n") i = 0 for addr, key in addrs: i += 1 plain.write("%d,%s,%s\n"%(i,addr,key)) plain_data = Data(plain.getvalue()) cipher = Data() c.op_encrypt(pub_gpg_keys, 1, plain_data, cipher) cipher.seek(0,0) return cipher.read()
def export_keys(self): selection = self.treeview.get_selection() if selection.count_selected_rows() <= 0: return export_file = None dialog = gtk.FileChooserDialog("Export Keys (Public only) into a File", self.mainwin, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK)) while dialog.run() == gtk.RESPONSE_OK: filename = dialog.get_filename() if os.path.exists(filename): if os.path.isdir(filename): self.error_message("%s is a directory!" % filename, dialog) continue elif not self.yesno_message("%s exists. Override?" % filename, dialog): continue # FIXME. Verify that file can be written to export_file = file(filename, "wb") break dialog.destroy() if export_file == None: return key_list = [] selection.selected_foreach(self.collect_keys, key_list) expkeys = Data() for key, row in key_list: self.context.op_export(key.subkeys[0].fpr, 0, expkeys) expkeys.seek(0,0) export_file.write(expkeys.read()) export_file.close()
def export_keys(self): selection = self.treeview.get_selection() if selection.count_selected_rows() <= 0: return export_file = None dialog = gtk.FileChooserDialog("Export Keys (Public only) into a File", self.mainwin, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK)) while dialog.run() == gtk.RESPONSE_OK: filename = dialog.get_filename() if os.path.exists(filename): if os.path.isdir(filename): self.error_message("%s is a directory!" % filename, dialog) continue elif not self.yesno_message("%s exists. Override?" % filename, dialog): continue # FIXME. Verify that file can be written to export_file = file(filename, "wb") break dialog.destroy() if export_file == None: return key_list = [] selection.selected_foreach(self.collect_keys, key_list) expkeys = Data() for key, row in key_list: self.context.op_export(key.subkeys[0].fpr, 0, expkeys) expkeys.seek(0, 0) export_file.write(expkeys.read()) export_file.close()
def on_import_keys_activate(self, obj): import_file = None dialog = gtk.FileChooserDialog("Import Keys from a File", self.mainwin, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK)) while dialog.run() == gtk.RESPONSE_OK: filename = dialog.get_filename() if os.path.exists(filename): if os.path.isdir(filename): self.error_message("%s is a directory!" % filename, dialog) else: # FIXME. Verify that file can be open. import_file = filename break else: self.error_message("%s does not exist." % filename, dialog) dialog.destroy() if import_file == None: return impkeys = Data(file=import_file) status = self.context.op_import(impkeys) if status: self.error_message("Import return an error message %d" % status) result = self.context.op_import_result() if result.considered == 0: self.error_message("There's no keys in the file.") # FIXME. Instead of rereading everything we could find out what's new # from the result based on the ORed value of impkey: # constants.import.NEW - The key was new. # constants.import.UID - The key contained new user IDs. # constants.import.SIG - The key contained new signatures. # constants.import.SUBKEY - The key contained new sub keys. # constants.import.SECRET - The key contained a secret key. # It would be nice to highlight new things as well. self.load_keys()
def format_sec_message(self, addrs, pub_gpg_keys): """ Create a GPG message (encrypted with the given public keys) """ from pyme.core import Data from StringIO import StringIO c = self.c plain = StringIO() plain.write( "-- SECRET - This file contains Bitcoin private keys! --\n\n") plain.write("Index,Address,Private Key\n") i = 0 for addr, key in addrs: i += 1 plain.write("%d,%s,%s\n" % (i, addr, key)) plain_data = Data(plain.getvalue()) cipher = Data() c.op_encrypt(pub_gpg_keys, 1, plain_data, cipher) cipher.seek(0, 0) return cipher.read()
def addPassword(): """ Model's not there? Fix it before we get into worse trouble. """ if not [m for m in mw.deck.models if m.name == MODEL]: m = Model(unicode(MODEL)) m.addFieldModel(FieldModel(u'Description', True, True)) m.addFieldModel(FieldModel(u'HMAC_%s' % HASH, True, True)) m.addFieldModel(FieldModel(u'GPG', True, True)) cm=CardModel(u'Password',u'%(Description)s',u'%%(HMAC_%s)s' % HASH) cm.typeAnswer = u'HMAC_%s' % HASH m.addCardModel(cm) mw.deck.addModel(m) else: m, = [m for m in mw.deck.models if m.name == MODEL] # Monkey patch existing models if 'HMAC_%s' % HASH not in [ a.name for a in m.fieldModels ]: m.addFieldModel(FieldModel(u'HMAC_%s' % HASH, True, True)) ret = QInputDialog.getText(mw, "Description", "Enter a description for the password") if ret[1]: desc = unicode(ret[0]) else: return ret = QInputDialog.getText(mw, "Password", "Enter the password", QLineEdit.Password) if ret[1]: pass1 = unicode(ret[0]) else: return ret = QInputDialog.getText(mw, "Confirm", "Confirm the password", QLineEdit.Password) if ret[1]: pass2 = unicode(ret[0]) else: return if pass1 != pass2: QMessageBox.information(mw, "Mismatch", "Your passwords didn't match") return """ Attempt to add the card. """ try: fact = mw.deck.newFact() fact['Description'] = desc """ Fill in the MAC """ mac = hmac.new(config.key, pass1.encode('utf-8'), getattr(hashlib, HASH)) fact['HMAC_%s' % HASH] = unicode(mac.hexdigest()) """ PyMe setup """ c = Context(); c.set_armor(1); c.op_keylist_start(GPG_USER_NAME, 0) key = c.op_keylist_next() if not key: QMessageBox.information(mw, "Error", "Could not find your key. Check you've set it up in the plugin file.") return print "Encrypting with key: " + key.uids[0].uid """ Do the encryption, or try to """ plain = Data(pass1.encode('utf-8')) cipher = Data() try: c.op_encrypt([key], 1, plain, cipher) cipher.seek(0,0) fact['GPG'] = unicode(re.sub("\n","<br>",cipher.read()), 'ascii') mw.deck.addFact(fact) except GPGMEError, e: QMessageBox.information(mw, "Error", "Could not encrypt your password.\nError: " + str(e)) except FactInvalidError, e: QMessageBox.information(mw, "Error", "Could not store your password.\nError: " + str(e))
if not name.startswith('__') and name != "util": stat2str[getattr(status, name)] = name # Print the output received since the last prompt before giving the new prompt def edit_fnc(stat, args, helper): global stat_strings try: while True: helper["data"].seek(helper["skip"], 0) data = helper["data"].read() helper["skip"] += len(data) sys.stdout.buffer.write(data) return input("(%s) %s > " % (stat2str[stat], args)) except EOFError: pass # Simple interactive editor to test editor scripts if len(sys.argv) != 2: sys.stderr.write("Usage: %s <Gpg key pattern>\n" % sys.argv[0]) else: c = Context() out = Data() c.op_keylist_start(sys.argv[1], 0) key = c.op_keylist_next() helper = {"skip": 0, "data": out} c.op_edit(key, edit_fnc, helper, out) print("[-- Final output --]") out.seek(helper["skip"], 0) sys.stdout.buffer.write(out.read())
def sendto(keylist): cipher = Data() c.op_encrypt(keylist, 1, plain, cipher) cipher.seek(0, os.SEEK_SET) return cipher.read()
for name in dir(status): if not name.startswith('__') and name != "util": stat2str[getattr(status, name)] = name # Print the output received since the last prompt before giving the new prompt def edit_fnc(stat, args, helper): global stat_strings try: while True: helper["data"].seek(helper["skip"],0) data = helper["data"].read() helper["skip"] += len(data) print(data) return input("(%s) %s > " % (stat2str[stat], args)) except EOFError: pass # Simple interactive editor to test editor scripts if len(sys.argv) != 2: sys.stderr.write("Usage: %s <Gpg key patter>\n" % sys.argv[0]) else: c = Context() out = Data() c.op_keylist_start(sys.argv[1], 0) key = c.op_keylist_next() helper = {"skip": 0, "data": out} c.op_edit(key, edit_fnc, helper, out) print("[-- Final output --]") out.seek(helper["skip"],0) print(out.read())
stat2str[getattr(status, name)] = name # Print the output received since the last prompt before giving the new prompt def edit_fnc(stat, args, helper): global stat_strings try: while True: helper["data"].seek(helper["skip"], 0) data = helper["data"].read() helper["skip"] += len(data) print data return raw_input("(%s) %s > " % (stat2str[stat], args)) except EOFError: pass # Simple interactive editor to test editor scripts if len(sys.argv) != 2: sys.stderr.write("Usage: %s <Gpg key patter>\n" % sys.argv[0]) else: c = Context() out = Data() c.op_keylist_start(sys.argv[1], 0) key = c.op_keylist_next() helper = {"skip": 0, "data": out} c.op_edit(key, edit_fnc, helper, out) print "[-- Final output --]" out.seek(helper["skip"], 0) print out.read()
def sendto(keylist): cipher = Data() c.op_encrypt(keylist, 1, plain, cipher) cipher.seek(0, 0) return cipher.read()
sys.stdout.buffer.write(out.read()) print("[-- Code: %d, %s --]" % (status, args)) if args == "keyedit.prompt": result = self.steps[self.step] self.step += 1 elif args == "keyedit.save.okay": result = "Y" elif args == "keygen.valid": result = "0" else: result = None return result if not os.getenv("GNUPGHOME"): print("Please, set GNUPGHOME env.var. pointing to GPGME's tests/gpg dir") else: c = Context() c.set_passphrase_cb(lambda x,y,z: "abc") out = Data() c.op_keylist_start(b"Alpha", 0) key = c.op_keylist_next() if not key: sys.exit("Key Alpha not found. " + "Did you point GNUPGHOME to GPGME's tests/gpg dir?") c.op_edit(key, KeyEditor().edit_fnc, out, out) print("[-- Last response --]") out.seek(0, os.SEEK_SET) sys.stdout.buffer.write(out.read())
def edit_fnc(self, status, args, out): print("[-- Response --]") out.seek(0,0) print(out.read(), end=' ') print("[-- Code: %d, %s --]" % (status, args)) if args == "keyedit.prompt": result = self.steps[self.step] self.step += 1 elif args == "keyedit.save.okay": result = "Y" elif args == "keygen.valid": result = "0" else: result = None return result if not os.getenv("GNUPGHOME"): print("Please, set GNUPGHOME env.var. pointing to GPGME's tests/gpg dir") else: c = Context() c.set_passphrase_cb(lambda x,y,z: "abc") out = Data() c.op_keylist_start("Alpha", 0) key = c.op_keylist_next() c.op_edit(key, KeyEditor().edit_fnc, out, out) print("[-- Last response --]") out.seek(0,0) print(out.read(), end=' ')
def edit_fnc(self, status, args, out): print "[-- Response --]" out.seek(0,0) print out.read(), print "[-- Code: %d, %s --]" % (status, args) if args == "keyedit.prompt": result = self.steps[self.step] self.step += 1 elif args == "keyedit.save.okay": result = "Y" elif args == "keygen.valid": result = "0" else: result = None return result if not os.getenv("GNUPGHOME"): print "Please, set GNUPGHOME env.var. pointing to GPGME's tests/gpg dir" else: c = Context() c.set_passphrase_cb(lambda x,y,z: "abc") out = Data() c.op_keylist_start("Alpha", 0) key = c.op_keylist_next() c.op_edit(key, KeyEditor().edit_fnc, out, out) print "[-- Last response --]" out.seek(0,0) print out.read(),
# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ This program will try to encrypt a simple message to each key on your keyring. If your keyring has any invalid keys on it, those keys will be removed and it will re-try the encryption.""" from pyme import core from pyme.core import Data, Context from pyme.constants import validity core.check_version(None) plain = Data('This is my message.') c = Context() c.set_armor(1) def sendto(keylist): cipher = Data() c.op_encrypt(keylist, 1, plain, cipher) cipher.seek(0, 0) return cipher.read() names = [] for key in c.op_keylist_all(None, 0): print " *** Found key for %s" % key.uids[0].uid