예제 #1
0
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
예제 #2
0
파일: gnupg.py 프로젝트: 4sp1r3/batzenca
    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()
예제 #3
0
파일: gnupg.py 프로젝트: 4sp1r3/batzenca
    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()
예제 #4
0
    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()
예제 #5
0
    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()
예제 #6
0
    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()
예제 #7
0
    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()
예제 #8
0
    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(),
예제 #9
0
파일: t-edit.py 프로젝트: gpg/gpgme
        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())
예제 #10
0
파일: inter-edit.py 프로젝트: gpg/gpgme
    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())
예제 #11
0
파일: encrypt-to-all.py 프로젝트: gpg/gpgme
def sendto(keylist):
    cipher = Data()
    c.op_encrypt(keylist, 1, plain, cipher)
    cipher.seek(0, os.SEEK_SET)
    return cipher.read()
예제 #12
0
        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()
예제 #13
0
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))
예제 #14
0
def sendto(keylist):
    cipher = Data()
    c.op_encrypt(keylist, 1, plain, cipher)
    cipher.seek(0, 0)
    return cipher.read()