python: Clean up examples.

* lang/python/examples/delkey.py: Clean up example.
* lang/python/examples/encrypt-to-all.py: Likewise.
* lang/python/examples/genkey.py: Likewise.
* lang/python/examples/inter-edit.py: Likewise.
* lang/python/examples/sign.py: Likewise.
* lang/python/examples/signverify.py: Likewise.
* lang/python/examples/simple.py: Likewise.
* lang/python/examples/t-edit.py: Likewise.
* lang/python/examples/verifydetails.py: Likewise.
* lang/python/pyme/__init__.py: Likewise.

Signed-off-by: Justus Winter <justus@gnupg.org>
This commit is contained in:
Justus Winter 2016-05-17 14:15:21 +02:00
parent 64e5fe767f
commit 10328324c8
10 changed files with 46 additions and 43 deletions

View File

@ -31,6 +31,6 @@ core.check_version(None)
c = core.Context() c = core.Context()
# 0 in keylist means to list not only public but secret keys as well. # 0 in keylist means to list not only public but secret keys as well.
for thekey in [x for x in c.op_keylist_all(b"joe@example.org", 0)]: for thekey in [x for x in c.op_keylist_all("joe+pyme@example.org", 0)]:
# 1 in delete means to delete not only public but secret keys as well. # 1 in delete means to delete not only public but secret keys as well.
c.op_delete(thekey, 1) c.op_delete(thekey, 1)

View File

@ -23,13 +23,14 @@ 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 keyring. If your keyring has any invalid keys on it, those keys will
be skipped and it will re-try the encryption.""" be skipped and it will re-try the encryption."""
import sys
import os
from pyme import core from pyme import core
from pyme.core import Data, Context from pyme.core import Data, Context
from pyme.constants import validity
core.check_version(None) core.check_version(None)
plain = Data(b'This is my message.') plain = Data('This is my message.')
c = Context() c = Context()
c.set_armor(1) c.set_armor(1)
@ -37,7 +38,7 @@ c.set_armor(1)
def sendto(keylist): def sendto(keylist):
cipher = Data() cipher = Data()
c.op_encrypt(keylist, 1, plain, cipher) c.op_encrypt(keylist, 1, plain, cipher)
cipher.seek(0,0) cipher.seek(0, os.SEEK_SET)
return cipher.read() return cipher.read()
names = [] names = []
@ -64,4 +65,4 @@ for key in c.op_keylist_all(None, 0):
passno = 0 passno = 0
print("Encrypting to %d recipients" % len(names)) print("Encrypting to %d recipients" % len(names))
print(sendto(names)) sys.stdout.buffer.write(sendto(names))

View File

@ -28,14 +28,14 @@ c.set_progress_cb(callbacks.progress_stdout, None)
# This example from the GPGME manual # This example from the GPGME manual
parms = b"""<GnupgKeyParms format="internal"> parms = """<GnupgKeyParms format="internal">
Key-Type: RSA Key-Type: RSA
Key-Length: 2048 Key-Length: 2048
Subkey-Type: RSA Subkey-Type: RSA
Subkey-Length: 2048 Subkey-Length: 2048
Name-Real: Joe Tester Name-Real: Joe Tester
Name-Comment: with stupid passphrase Name-Comment: with stupid passphrase
Name-Email: joe@example.org Name-Email: joe+pyme@example.org
Passphrase: Crypt0R0cks Passphrase: Crypt0R0cks
Expire-Date: 2020-12-31 Expire-Date: 2020-12-31
</GnupgKeyParms> </GnupgKeyParms>

View File

@ -17,7 +17,6 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
# 02111-1307 USA # 02111-1307 USA
import os
import sys import sys
from pyme import core from pyme import core
from pyme.core import Data, Context from pyme.core import Data, Context
@ -40,21 +39,21 @@ def edit_fnc(stat, args, helper):
helper["data"].seek(helper["skip"], 0) helper["data"].seek(helper["skip"], 0)
data = helper["data"].read() data = helper["data"].read()
helper["skip"] += len(data) helper["skip"] += len(data)
print(data) sys.stdout.buffer.write(data)
return input("(%s) %s > " % (stat2str[stat], args)) return input("(%s) %s > " % (stat2str[stat], args))
except EOFError: except EOFError:
pass pass
# Simple interactive editor to test editor scripts # Simple interactive editor to test editor scripts
if len(sys.argv) != 2: if len(sys.argv) != 2:
sys.stderr.write("Usage: %s <Gpg key patter>\n" % sys.argv[0]) sys.stderr.write("Usage: %s <Gpg key pattern>\n" % sys.argv[0])
else: else:
c = Context() c = Context()
out = Data() out = Data()
c.op_keylist_start(sys.argv[1].encode('utf-8'), 0) c.op_keylist_start(sys.argv[1], 0)
key = c.op_keylist_next() key = c.op_keylist_next()
helper = {"skip": 0, "data": out} helper = {"skip": 0, "data": out}
c.op_edit(key, edit_fnc, helper, out) c.op_edit(key, edit_fnc, helper, out)
print("[-- Final output --]") print("[-- Final output --]")
out.seek(helper["skip"], 0) out.seek(helper["skip"], 0)
print(out.read()) sys.stdout.buffer.write(out.read())

View File

@ -17,6 +17,8 @@
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import sys
import os
from pyme import core, callbacks from pyme import core, callbacks
from pyme.constants.sig import mode from pyme.constants.sig import mode
@ -27,5 +29,5 @@ sig = core.Data()
c = core.Context() c = core.Context()
c.set_passphrase_cb(callbacks.passphrase_stdin, b'for signing') c.set_passphrase_cb(callbacks.passphrase_stdin, b'for signing')
c.op_sign(plain, sig, mode.CLEAR) c.op_sign(plain, sig, mode.CLEAR)
sig.seek(0,0) sig.seek(0, os.SEEK_SET)
print(sig.read()) sys.stdout.buffer.write(sig.read())

View File

@ -20,7 +20,8 @@
# It uses keys for joe@example.org generated by genkey.pl script # It uses keys for joe@example.org generated by genkey.pl script
import sys import sys
from pyme import core, callbacks import os
from pyme import core
from pyme.constants.sig import mode from pyme.constants.sig import mode
core.check_version(None) core.check_version(None)
@ -28,7 +29,7 @@ core.check_version(None)
plain = core.Data(b"Test message") plain = core.Data(b"Test message")
sig = core.Data() sig = core.Data()
c = core.Context() c = core.Context()
user = b"joe@example.org" user = "joe"
c.signers_clear() c.signers_clear()
# Add joe@example.org's keys in the list of signers # Add joe@example.org's keys in the list of signers
@ -50,9 +51,9 @@ c.set_passphrase_cb(lambda x,y,z: passlist[x[x.rindex("<"):]])
c.op_sign(plain, sig, mode.CLEAR) c.op_sign(plain, sig, mode.CLEAR)
# Print out the signature (don't forget to rewind since signing put sig at EOF) # Print out the signature (don't forget to rewind since signing put sig at EOF)
sig.seek(0,0) sig.seek(0, os.SEEK_SET)
signedtext = sig.read() signedtext = sig.read()
print(signedtext) sys.stdout.buffer.write(signedtext)
# Create Data with signed text. # Create Data with signed text.
sig2 = core.Data(signedtext) sig2 = core.Data(signedtext)
@ -63,9 +64,7 @@ c.op_verify(sig2, None, plain2)
result = c.op_verify_result() result = c.op_verify_result()
# List results for all signatures. Status equal 0 means "Ok". # List results for all signatures. Status equal 0 means "Ok".
index = 0 for index, sign in enumerate(result.signatures):
for sign in result.signatures:
index += 1
print("signature", index, ":") print("signature", index, ":")
print(" summary: ", sign.summary) print(" summary: ", sign.summary)
print(" status: ", sign.status) print(" status: ", sign.status)
@ -74,5 +73,6 @@ for sign in result.signatures:
print(" uid: ", c.get_key(sign.fpr, 0).uids[0].uid) print(" uid: ", c.get_key(sign.fpr, 0).uids[0].uid)
# Print "unsigned" text. Rewind since verify put plain2 at EOF. # Print "unsigned" text. Rewind since verify put plain2 at EOF.
plain2.seek(0,0) plain2.seek(0, os.SEEK_SET)
print("\n", plain2.read()) print("\n")
sys.stdout.buffer.write(plain2.read())

View File

@ -18,8 +18,8 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import sys import sys
from pyme import core, constants, errors import os
import pyme.constants.validity from pyme import core, errors
core.check_version(None) core.check_version(None)
@ -47,7 +47,7 @@ else:
# Do the encryption. # Do the encryption.
try: try:
c.op_encrypt([r], 1, plain, cipher) c.op_encrypt([r], 1, plain, cipher)
cipher.seek(0,0) cipher.seek(0, os.SEEK_SET)
sys.stdout.buffer.write(cipher.read()) sys.stdout.buffer.write(cipher.read())
except errors.GPGMEError as ex: except errors.GPGMEError as ex:
print(ex.getstring()) print(ex.getstring())

View File

@ -30,8 +30,8 @@ class KeyEditor:
def edit_fnc(self, status, args, out): def edit_fnc(self, status, args, out):
print("[-- Response --]") print("[-- Response --]")
out.seek(0,0) out.seek(0, os.SEEK_SET)
print(out.read(), end=' ') sys.stdout.buffer.write(out.read())
print("[-- Code: %d, %s --]" % (status, args)) print("[-- Code: %d, %s --]" % (status, args))
if args == "keyedit.prompt": if args == "keyedit.prompt":
@ -59,5 +59,5 @@ else:
"Did you point GNUPGHOME to GPGME's tests/gpg dir?") "Did you point GNUPGHOME to GPGME's tests/gpg dir?")
c.op_edit(key, KeyEditor().edit_fnc, out, out) c.op_edit(key, KeyEditor().edit_fnc, out, out)
print("[-- Last response --]") print("[-- Last response --]")
out.seek(0,0) out.seek(0, os.SEEK_SET)
print(out.read(), end=' ') sys.stdout.buffer.write(out.read())

View File

@ -25,8 +25,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys import sys
from pyme import core, callbacks, constants import os
from pyme.constants.sig import mode from pyme import core
from pyme.constants import protocol from pyme.constants import protocol
def print_engine_infos(): def print_engine_infos():
@ -58,9 +58,7 @@ def verifyprintdetails(sigfilename, filefilename=None):
result = c.op_verify_result() result = c.op_verify_result()
# List results for all signatures. Status equal 0 means "Ok". # List results for all signatures. Status equal 0 means "Ok".
index = 0 for index, sign in enumerate(result.signatures):
for sign in result.signatures:
index += 1
print("signature", index, ":") print("signature", index, ":")
print(" summary: %#0x" % (sign.summary)) print(" summary: %#0x" % (sign.summary))
print(" status: %#0x" % (sign.status)) print(" status: %#0x" % (sign.status))
@ -71,8 +69,9 @@ def verifyprintdetails(sigfilename, filefilename=None):
# Print "unsigned" text if inline signature # Print "unsigned" text if inline signature
if plain2: if plain2:
#Rewind since verify put plain2 at EOF. #Rewind since verify put plain2 at EOF.
plain2.seek(0,0) plain2.seek(0, os.SEEK_SET)
print("\n", plain2.read()) print("\n")
sys.stdout.buffer.write(plain2.read())
def main(): def main():
print_engine_infos() print_engine_infos()
@ -86,13 +85,13 @@ def main():
sys.exit(1) sys.exit(1)
if argc == 2: if argc == 2:
print("trying to verify file: " + sys.argv[1].encode('utf-8')) print("trying to verify file: " + sys.argv[1])
verifyprintdetails(sys.argv[1].encode('utf-8')) verifyprintdetails(sys.argv[1])
if argc == 3: if argc == 3:
print("trying to verify signature %s for file %s" \ print("trying to verify signature %s for file %s" \
% (sys.argv[1].encode('utf-8'), sys.argv[2].encode('utf-8'))) % (sys.argv[1], sys.argv[2]))
verifyprintdetails(sys.argv[1].encode('utf-8'), sys.argv[2].encode('utf-8')) verifyprintdetails(sys.argv[1], sys.argv[2])
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -84,6 +84,7 @@ QUICK START SAMPLE PROGRAM
This program is not for serious encryption, but for example purposes only! This program is not for serious encryption, but for example purposes only!
import sys import sys
import os
from pyme import core, constants from pyme import core, constants
# Set up our input and output buffers. # Set up our input and output buffers.
@ -99,6 +100,7 @@ c.set_armor(1)
# Set up the recipients. # Set up the recipients.
sys.stdout.write("Enter name of your recipient: ") sys.stdout.write("Enter name of your recipient: ")
sys.stdout.flush()
name = sys.stdin.readline().strip() name = sys.stdin.readline().strip()
c.op_keylist_start(name, 0) c.op_keylist_start(name, 0)
r = c.op_keylist_next() r = c.op_keylist_next()
@ -106,8 +108,8 @@ r = c.op_keylist_next()
# Do the encryption. # Do the encryption.
c.op_encrypt([r], 1, plain, cipher) c.op_encrypt([r], 1, plain, cipher)
cipher.seek(0,0) cipher.seek(0, os.SEEK_SET)
print cipher.read() sys.stdout.buffer.write(cipher.read())
Note that although there is no explicit error checking done here, the Note that although there is no explicit error checking done here, the
Python GPGME library is automatically doing error-checking, and will Python GPGME library is automatically doing error-checking, and will