def encryptMessage(): try: Json_in_request=request.form['json'] except: #Check for json return json.dumps({'errors':'Bad request parameter'}) try: json_decoded=json.loads(Json_in_request) except: # Check if JSON is parseable return json.dumps({'errors':'Couldn`t parse Json'}) try: ph=json_decoded['Passphrase'] msg=json_decoded['Message'] except: #check if the JSON prams are there return json.dumps({'errors':'bad Json parameter'}) encrypted_obj=GPG().encrypt(passphrase=ph,data=msg) return json.dumps({'DecryptedMessage':decrypted_obj.data})
def touch_pass_query(message, bot, way, name): val_old = '/' part = name.split('/') try: if not path.isdir(way + '/' + '/'.join(part[:-1])): makedirs(way + '/' + '/'.join(part[:-1])) gpg = GPG() gpg.encrypt( message.text, recipients=['user_' + str(message.chat.id)], output=way + '/' + name + '.gpg', ) msg = bot.send_message(message.chat.id, 'Запись ' + name + ' добавлена.') del_mess(msg, bot, 4) return except: msg = bot.send_message(message.chat.id, 'Произошла ошибка.') del_mess(msg, bot, 4) return
def createciphermsgs_gpg(jt65msgcount, stegmsg, recipient, verbose=False): # Performs the actual GPG encryption ciphermsgs = [] while len(stegmsg) % 8: stegmsg += " " gpg = GPG() stegstream = io.StringIO(unicode(stegmsg)) cipherdata = gpg.encrypt_file(stegstream, recipient) if cipherdata == "": print "You must set the recipient's trust level to -something- in your keyring before we can encrypt the message" sys.exit(0) cipherlist = list(bytearray(str(cipherdata))) if verbose: print "Cipher list: " + str(cipherlist) if jt65msgcount * 8 < len(cipherlist): print( "Length of hidden message exceeds capacity of number of valid JT65 messages provided") sys.exit(0) # Is the total length too big to fit into our max number of packets? if len(cipherlist) > MAX_MULTI_PACKET_STEG_BYTES_GPG: print("Length of hidden message exceeds capacity of multi-packet steg") sys.exit(0) totalpackets = len(cipherlist) / 8 createciphermsgs_packer_other( totalpackets, ciphermsgs, cipherlist, verbose) return ciphermsgs
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from gnupg import GPG from config import Config app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) migrate = Migrate(app, db) login = LoginManager(app) login.login_view = 'login' gpg = GPG(binary=app.config['GPG_BINARY'], homedir=app.config['GPG_KEY_STORE'], keyring='pubring.gpg', secring='secring.gpg') from app import routes, models, file_handler, block_api
def deciphersteg(stegdata, cipher, key, aesmode, verbose=False, unprep=True): # Decipher hidden message from array of data hidden in JT65 errors stegedmsg = "" stegedmsgba = np.array(range(0), dtype=np.int32) statusar = [] for index, value in enumerate(stegdata): if unprep: value = jt.unprepsteg(value) # Decode real data from FEC if cipher == "none": recoveredtext = jt.decode(value)[0:13] if verbose: print "Steg Text in Message " + str(index) + " : " + recoveredtext stegedmsg += recoveredtext elif cipher == "XOR" or cipher == "OTP": thesebytes = jt65tobytes(value) thisstatus = thesebytes[0:1] if thisstatus & 0x40 == 0x40: # This is the last packet, signals how many bytes to read bytestoread = thisstatus & 0x3F thisunstegbytes = thesebytes[1:bytestoread + 1] else: thisunstegbytes = thesebytes[1:] if verbose: print "Steg Data in Message " + str(index) + " : " + str(thisunstegbytes) stegedmsgba = np.append(stegedmsgba, thisunstegbytes) else: thesebytes = jt65tobytes(value) thisunstegbytes = thesebytes[1:10] if verbose: print "Steg Data in Message " + str(index) + " : " + str(thisunstegbytes) stegedmsgba = np.append(stegedmsgba, thisunstegbytes) if cipher == "XOR": if verbose: print"Cipher Data : " + str(stegedmsgba) finalcipherdata = ( ''.join('{0:02x}'.format(int(e)).decode("hex") for e in stegedmsgba)) if verbose: print"Cipher Data Hex : " + finalcipherdata cryptobj = XOR.new(key) stegedmsg = cryptobj.decrypt(finalcipherdata) if cipher == "ARC4": if verbose: print"Cipher Data : " + str(stegedmsgba) finalcipherdata = ( ''.join('{0:02x}'.format(int(e)).decode("hex") for e in stegedmsgba)) if verbose: print"Cipher Data Hex : " + finalcipherdata tempkey = SHA.new(key).digest() cryptobj = ARC4.new(tempkey) stegedmsg = cryptobj.decrypt(finalcipherdata) if cipher == "AES": if verbose: print"Cipher Data : " + str(stegedmsgba) finalcipherdata = ( ''.join('{0:02x}'.format(int(e)).decode("hex") for e in stegedmsgba)) if verbose: print"Cipher Data Hex : " + finalcipherdata if aesmode == "ECB": cryptobj = AES.new(key, AES.MODE_ECB) elif aesmode == "CBC": cryptobj = AES.new(key, AES.MODE_CBC, finalcipherdata[0:16]) finalcipherdata = finalcipherdata[16:] elif aesmode == "CFB": cryptobj = AES.new(key, AES.MODE_CFB, finalcipherdata[0:16]) finalcipherdata = finalcipherdata[16:] stegedmsg = cryptobj.decrypt(finalcipherdata) if cipher == "GPG": if verbose: print"Cipher Data : " + str(stegedmsgba) finalcipherdata = ( ''.join('{0:02x}'.format(int(e)).decode("hex") for e in stegedmsgba)) if verbose: print"Cipher Data Hex : " + finalcipherdata gpg = GPG() stegedmsg = gpg.decrypt(finalcipherdata) stegedmsg = str(stegedmsg) if cipher == "OTP": finalcipherdata = (''.join(chr(e) for e in stegedmsgba)) if verbose: print"Cipher Data : " + str(finalcipherdata) stegedmsg = otp_decode(str(finalcipherdata), key) return stegedmsg
def _main(): descr = 'Generate Gerrit release announcement email text' parser = argparse.ArgumentParser( description=descr, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-v', '--version', dest='version', required=True, help='gerrit version to release') parser.add_argument('-p', '--previous', dest='previous', help='previous gerrit version (optional)') parser.add_argument('-s', '--summary', dest='summary', help='summary of the release content (optional)') options = parser.parse_args() summary = options.summary if summary and not summary.endswith("."): summary = summary + "." data = { "version": Version(options.version), "previous": options.previous, "summary": summary } war = os.path.join( os.path.expanduser("~/.m2/repository/com/google/gerrit/gerrit-war/"), "%(version)s/gerrit-war-%(version)s.war" % data) if not os.path.isfile(war): print("Could not find war file for Gerrit %s in local Maven repository" % data["version"], file=sys.stderr) sys.exit(1) md5 = hashlib.md5() sha1 = hashlib.sha1() sha256 = hashlib.sha256() BUF_SIZE = 65536 # Read data in 64kb chunks with open(war, 'rb') as f: while True: d = f.read(BUF_SIZE) if not d: break md5.update(d) sha1.update(d) sha256.update(d) data["sha1"] = sha1.hexdigest() data["sha256"] = sha256.hexdigest() data["md5"] = md5.hexdigest() template_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "release-announcement-template.txt") template = Template(open(template_path).read()) output = template.render(data=data) filename = "release-announcement-gerrit-%s.txt" % data["version"] with open(filename, "w") as f: f.write(output) gpghome = os.path.abspath(os.path.expanduser("~/.gnupg")) if not os.path.isdir(gpghome): print("Skipping signing due to missing gnupg home folder") else: try: gpg = GPG(homedir=gpghome) except TypeError: gpg = GPG(gnupghome=gpghome) signed = gpg.sign(output) filename = filename + ".asc" with open(filename, "w") as f: f.write(str(signed))
def gnupg_instance() -> GPG: return GPG()
def create_gpg(workdir): gpg = GPG(gnupghome=os.path.join(workdir, '.gnupg')) gpg.encoding = 'utf-8' return gpg
def _check_openpgp_pubkey_from_file(self, pubkey_file, long_key_id): with TemporaryDirectory() as temp_gpg_home: gpg = GPG(gnupghome=temp_gpg_home) with open(pubkey_file, 'rb') as pubkey_fh: import_result = gpg.import_keys(pubkey_fh.read()) if len(import_result.results) == 0: raise Exception("The OpenPGP file {} contains no OpenPGP keys." " Keys: {}".format( pubkey_file, import_result.results, )) logging.info( "OK - OpenPGP file {pubkey_file} contains one or more OpenPGP key." .format(pubkey_file=pubkey_file, )) fingerprint = [ x['fingerprint'] for x in import_result.results if x.get('fingerprint') ][0] actual_long_key_id = fingerprint[-16:] given_long_key_id = re.sub(r'^0x', '', long_key_id) if actual_long_key_id.lower() != given_long_key_id.lower(): raise Exception( textwrap.dedent(""" The OpenPGP file {given_long_key_id} contains a different key than what the file name suggests. Key ID from file name: {given_long_key_id}, Key ID from pubkey in file: {actual_long_key_id} """).lstrip().format( given_long_key_id=given_long_key_id, actual_long_key_id=actual_long_key_id, )) logging.info( "OK - OpenPGP file {pubkey_file} contains a OpenPGP public key" " whose long key ID matching the file name.".format( pubkey_file=pubkey_file, )) list_key = gpg.list_keys()[0] epoch_time = int(time.time()) expires_time = int(list_key['expires']) if self._strict: if expires_time < epoch_time: raise Exception( textwrap.dedent(""" The OpenPGP file {} contains a expired OpenPGP key. Current date: {} Expiration date: {} """).lstrip().format( pubkey_file, datetime.fromtimestamp(epoch_time), datetime.fromtimestamp(expires_time), )) else: logging.info( "OK - OpenPGP public key from {pubkey_file} is not expired." " Expiration date: {expiration_date}".format( pubkey_file=pubkey_file, expiration_date=datetime.fromtimestamp( expires_time), )) # https://keyring.debian.org/creating-key.html if self._strict: if int(list_key['length']) < self._OPENPGP_MIN_KEY_SIZE: raise Exception( textwrap.dedent(""" The OpenPGP file {} contains a weak OpenPGP key. Current key length in bits: {} Expected at least (inclusive): {} """).lstrip().format( pubkey_file, list_key['length'], self._OPENPGP_MIN_KEY_SIZE, )) else: logging.info( "OK - The key length of the OpenPGP public key from {pubkey_file} is not considered to be weak." " Key length in bits: {key_size}".format( pubkey_file=pubkey_file, key_size=list_key['length'], )) return True
def test_check_git_commits_ok(): with TemporaryDirectory() as tmp_git_repo: gpg_tmp_home = os.path.join(tmp_git_repo, 'gpg_tmp_home') # Included in the repository to avoid problems with low entropy in CI # environments. # input_data = gpg.gen_key_input( # key_type='RSA', # subkey_type='RSA', # key_length=1024, # subkey_length=1024, # name_comment='This is only a test key who’s private key is publicly know. Don’t use this key for anything!1!', # name_email='*****@*****.**', # # Has already expired at the time of creation to ensure no one will ever use the key. # expire_date='2012-12-24', # Needs to be set to the 24 for the key to expire on 23. # # Hm, Ok, gpg does not do that by default. `--faked-system-time` # # could be used to force it but that would require cmd access. # # https://www.gnupg.org/documentation/manuals/gnupg/Unattended-GPG-key-generation.html # # "gpg: Invalid option "--faked-system-time"" :( # # Only: gpg2 --batch --gen-key --debug=0 --faked-system-time '2342-05-23' # # has been confirmed to work from current Debian Stretch. # # Faking it manually anyway … # ) # print(input_data) # print(gpg.gen_key(input_data)) shutil.copytree(debops_keyring_fake_gnupg_home, gpg_tmp_home) gpg = GPG(gnupghome=gpg_tmp_home) os.chmod(gpg_tmp_home, 0o700) for r, d, f in os.walk(gpg_tmp_home): os.chmod(r, 0o700) gpg_key_fingerprint = gpg.list_keys()[0]['fingerprint'] gpg_edit_key_cmd = subprocess.Popen( [ 'gpg', '--homedir', gpg_tmp_home, '--command-fd', '0', '--batch', '--edit-key', gpg_key_fingerprint ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) (gpg_edit_key_cmd_stdout, gpg_edit_key_cmd_stderr) = gpg_edit_key_cmd.communicate( input='expire\n0\nsave\n'.encode(), timeout=5, ) # print(gpg_edit_key_cmd_stderr.decode()) # print(subprocess.check_output(['gpg', '--homedir', gpg_tmp_home, '--list-public-keys']).decode()) if 'expires: never' not in str(gpg_edit_key_cmd_stderr): raise Exception("Could not change expiration date.") tmp_keyring_dir = os.path.join(tmp_git_repo, 'tmp-keyring-gpg') tmp_pubkey_file = os.path.join( tmp_keyring_dir, '0x' + gpg_key_fingerprint[-16:].upper()) os.mkdir(tmp_keyring_dir) with open(tmp_pubkey_file, 'w') as tmp_pubkey_fh: tmp_pubkey_fh.write(gpg.export_keys(gpg_key_fingerprint)) git_cmd = git.Git(tmp_git_repo) git_cmd.update_environment(GNUPGHOME=debops_keyring_fake_gnupg_home, ) git_cmd.init() git_cmd.config(['user.signingkey', gpg_key_fingerprint]) git_cmd.config(['user.email', '*****@*****.**']) git_cmd.config(['user.name', 'debops-keyring-test']) git_cmd.update_environment(GNUPGHOME=os.path.join( tmp_git_repo, 'gpg_tmp_home'), ) tmp_git_file = os.path.join(tmp_git_repo, 'new-file') with open(tmp_git_file, 'w') as tmp_git_fh: tmp_git_fh.write(str(time.time())) git_cmd.add([tmp_git_file]) git_cmd.commit(['--gpg-sign', '--message', 'Signed commit']) debops_keyring = Keyring(keyring_name=tmp_keyring_dir, ) debops_keyring.check_git_commits(tmp_git_repo) # Now make an unsigned commit to ensure that this raises an exception. with open(tmp_git_file, 'w') as tmp_git_fh: tmp_git_fh.write(str(time.time())) git_cmd.add([tmp_git_file]) git_cmd.commit(['--no-gpg-sign', '--message', 'Unsigned commit']) try: debops_keyring.check_git_commits(tmp_git_repo) assert False except Exception as e: if 'OpenPGP signature of commit could not be verified' in str( e) and 'Unsigned commit' in str(e): assert True else: assert False
def rm_key(key, password): gpg = GPG() gpg.delete_keys(key, True, passphrase=password) gpg.delete_keys(key) system('echo RELOADAGENT | gpg-connect-agent')
def DecryptGPG(cipher_file, gpghome, p_phrase): """Simple decrypt.""" cipher_data = str(open(cipher_file, 'r').read()).strip('\n') g = GPG(gnupghome=gpghome) clear_data = g.decrypt(cipher_data, passphrase=p_phrase) return clear_data
def gpg_verify_signature(signature_file, message): gpg = GPG(gnupghome = KEYS_DIR) return gpg.verify_data(signature_file, message)
def gpg_sign_message(message): gpg = GPG(gnupghome = KEYS_DIR) return gpg.sign(message, detach=True)
import config from smtplib import SMTP, SMTP_SSL from gnupg import GPG gpg = GPG( homedir=config.gnupg_home ) class Email: def __init__( self ): # Send the message if config.Smtp.security == 'tls': self.smtp = SMTP_SSL( config.Smtp.host, config.Smtp.port, config.Smtp.local_hostname, config.Smtp.tls_cert_file, config.Smtp.tls_key_file ) else: self.smtp = SMTP( config.Smtp.host, config.Smtp.port, config.Smtp.local_hostname ) if config.Smtp.security == 'starttls': self.smtp.starttls( config.Smtp.tls_cert_file, config.Smtp.tls_key_file ) if config.Smtp.username != None: self.smtp.login( config.Smtp.username, config.Smtp.password ) def close( self ): self.smtp.quit() def construct_message( self, from_addr, to_addr, body, headers ): if not 'From' in headers: headers['From'] = from_addr if not 'To' in headers: headers['To'] = to_addr message = '' for name, value in headers.items():
def send_mail(subject, body_text, addr_from, addr_to, fail_silently=False, attachments=None, body_html=None, connection=None, headers=None): """ Sends a multipart email containing text and html versions which are encrypted for each recipient that has a valid gpg key installed. """ # Allow for a single address to be passed in. if isinstance(addr_to, basestring): addr_to = [addr_to] # Obtain a list of the recipients that have gpg keys installed. key_addresses = {} if USE_GNUPG: from email_extras.models import Address for address in Address.objects.filter(address__in=addr_to): key_addresses[address.address] = address.use_asc # Create the gpg object. if key_addresses: gpg = GPG(gnupghome=GNUPG_HOME) # Encrypts body if recipient has a gpg key installed. def encrypt_if_key(body, addr_list): if addr_list[0] in key_addresses: encrypted = gpg.encrypt(body, addr_list[0], always_trust=ALWAYS_TRUST) return smart_text(encrypted) return body # Load attachments and create name/data tuples. attachments_parts = [] if attachments is not None: for attachment in attachments: # Attachments can be pairs of name/data, or filesystem paths. if not hasattr(attachment, "__iter__"): with open(attachment, "rb") as f: attachments_parts.append((basename(attachment), f.read())) else: attachments_parts.append(attachment) # Send emails - encrypted emails needs to be sent individually, while # non-encrypted emails can be sent in one send. So the final list of # lists of addresses to send to looks like: # [[unencrypted1, unencrypted2, unencrypted3], [encrypted1], [encrypted2]] unencrypted = [[addr for addr in addr_to if addr not in key_addresses]] encrypted = [[addr] for addr in key_addresses] for addr_list in unencrypted + encrypted: msg = EmailMultiAlternatives(subject, encrypt_if_key(body_text, addr_list), addr_from, addr_list, connection=connection, headers=headers) if body_html is not None: msg.attach_alternative(encrypt_if_key(body_html, addr_list), "text/html") for parts in attachments_parts: name = parts[0] if key_addresses.get(addr_list[0]): name += ".asc" msg.attach(name, encrypt_if_key(parts[1], addr_list)) msg.send(fail_silently=fail_silently)
def finish_login(message, bot, settings): user_root_folder = '/Seppass/Users_folder/user_' + str(message.chat.id) try: if not path.isdir(user_root_folder+'/main'): makedirs(user_root_folder+'/main') if not path.isdir(user_root_folder+'/user_data'): makedirs(user_root_folder+'/user_data') except: msg = bot.send_message(message.chat.id, 'Произошла ошибка.') del_mess(msg, bot, 4) return try: gpg = GPG() input_data = gpg.gen_key_input( passphrase=message.text, name_real='user_'+str(message.chat.id) ) key = gpg.gen_key(input_data) key = key.fingerprint ascii_armored_private_keys = gpg.export_keys(key, True, passphrase=message.text) system('echo RELOADAGENT | gpg-connect-agent') with open(user_root_folder+'/user_data/gpg_private_key.asc', 'w') as f: f.write(ascii_armored_private_keys) with open(user_root_folder+'/main/gpg_private_key.asc', 'w') as f: f.write(ascii_armored_private_keys) except: msg = bot.send_message(message.chat.id, 'Произошла ошибка.') del_mess(msg, bot, 4) return try: data = (('user_'+str(message.chat.id), key, str(settings))) conn = connect('DataBase.db', check_same_thread=False) c = conn.cursor() query = "INSERT INTO Users VALUES (?, ?, ?)" c.execute(query, data) conn.commit() conn.close() except: msg = bot.send_message(message.chat.id, 'Произошла ошибка.') del_mess(msg, bot, 4) return markup = types.ReplyKeyboardMarkup(one_time_keyboard=True) markup.add('Да') if settings["store_pass"] == "pass_server": try: with open(user_root_folder+'/user_data/Nothing.txt', 'w') as f: f.write(message.text) except: msg = bot.send_message(message.chat.id, 'Произошла ошибка.') del_mess(msg, bot, 4) return msg_handler = bot.send_message(message.chat.id, 'Регистрация прошла успешно. Пароль храниться на сервере.\n\nВаш user id:\n'+str(message.chat.id)+'\n\nПароль:\n'+ message.text +'\n\nЭто ваш отпечаток ключа:\n'+ str(key)+'\n\nЗапомнили? Я сейчас это сообщение удалю, в целях сохранности ваших данных.', reply_markup = markup) bot.register_next_step_handler(msg_handler, lambda msg: complete_finish_login(msg, bot)) else: msg_handler = bot.send_message(message.chat.id, 'Регистрация прошла успешно. Запомните пароль, в случае его утери ваш акк не восстановить (пока).\n\nВаш user id:\n'+str(message.chat.id)+'\n\nПароль:\n'+ message.text +'\n\nЭто ваш отпечаток ключа:\n'+ str(key)+'\n\nЗапомнили? Я сейчас это сообщение удалю, в целях сохранности ваших данных.', reply_markup = markup) bot.register_next_step_handler(msg_handler, lambda msg: complete_finish_login(msg, bot))
def __init__(self): self.gpg = GPG(gpgbinary='/usr/bin/gpg', gnupghome='/usr/local/src/keys')
def vote(request, poll_id): if not request.user.is_authenticated(): return HttpResponseRedirect('/') else: logged_in = True error = '' success = '' try: poll = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 username = request.user.username if (not poll.is_allowed_voter(username)) \ or poll.has_voted(username) \ or (poll.starts > datetime.datetime.now()) \ or (poll.ends < datetime.datetime.now()): return HttpResponseRedirect('/mypolls') poll_choices = Choice.objects.filter(poll=poll).order_by('id') choice_type = "radio" if poll.max_choices > 1: choice_type = "checkbox" vote_tag = '' vote_receipt_encrypted = '' if request.POST: form = Form(request.POST) if form.is_valid(): choices = request.POST.getlist('choices') # Check that the submitted choices exist and belong to the poll for choice in choices: try: c = Choice.objects.get(pk=choice, poll=poll) except Choice.DoesNotExist: error = "The submitted choices are not valid choices of the poll" # Check that the submitted choices are between min and max number of choices allowed for the poll if len(choices) > poll.max_choices: error = 'You cannot vote for more than ' + str( poll.max_choices) + ' choices' if len(choices) < poll.min_choices: error = 'You must vote for at least ' + str( poll.min_choices) + ' choices' if poll.max_choices == 1: # a better error message for single choice polls error = 'You must select a choice' if list_has_duplicates(choices): error = 'Each choice can be selected only once' if not error: # Construct a unique, random string to use as a vote tag while not vote_tag: vote_tag = ''.join( random.choice(string.ascii_uppercase + string.digits) for x in range(35)) try: v = Vote.objects.get(tag=vote_tag) vote_tag = '' except Vote.DoesNotExist: # our random string is unique so we can use it as a vote tag # Encrypt the vote tag with user's public pgp key and sign it with the key of the system authority gpg = GPG(gpgbinary=settings.GNUPGBINARY, gnupghome=settings.GNUPGHOME) vote_receipt = """GPGVote: Vote Receipt --------------------- You are voter: %s You voted for Poll: \'%s\' Created by: %s Your Vote Tag is: %s You made the following choices:""" % (request.user.pgpkey.name + ' <' + request.user.username + '>', poll.question, \ poll.creator.pgpkey.name + ' <' + poll.creator.username + '>', vote_tag) for choice in choices: choice = Choice.objects.get(pk=choice, poll=poll) vote_receipt = vote_receipt + '\n * %s' % choice.choice vote_receipt_encrypted = gpg.encrypt( vote_receipt, request.user.pgpkey.fingerprint, always_trust=True, sign=settings.SYSTEM_KEY_FINGERPRINT, passphrase=settings.SYSTEM_KEY_PASSWD) # Create the actual vote records in database for choice in choices: vote = Vote(choice=Choice.objects.get(id=choice), tag=vote_tag) vote.save() poll.add_voter(voter=username, To='who_voted') poll.save() success = 'You have successfully voted for the poll' return render_to_response('vote.html', { 'user': username, 'poll': poll, 'choices': poll_choices, 'choice_type': choice_type, 'error': error, 'success': success, 'vote_receipt': vote_receipt_encrypted, 'logged_in': logged_in }, context_instance=RequestContext(request))
from importer import ImportHelper from setup import SetupHelper from renew import RenewHelper from utils import init_logger from utils import parse_args from utils import test_configuration args = parse_args() init_logger(args.verbose) logger = logging.getLogger('Main') logger.debug('Arguments : [{}]'.format(args)) configManager = ConfigManager() keyring = GPG(gnupghome=Environment.keyringDir) keyringManager = KeyringManager(keyring) passboltServer = PassboltServer(configManager, keyring) urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) if args.action == 'setup': setupHelper = SetupHelper(configManager, keyring) setupHelper.setupServer() # The user setup is not working yet, so we don't use it # setupHelper.setupUser() elif args.action == 'test': test_configuration(logger, configManager, keyring) elif args.action == 'renew': RenewHelper(configManager, keyringManager, passboltServer).run(args) elif args.action == 'import':
def gpg_init_only(tmpdir, benchmark, openpgp_keys, monkeypatch, num_keys): keys = openpgp_keys[0:num_keys] gpg = GPG(homedir=tmpdir.dirname) for key in keys: gpg.import_keys(key.key_data)
def send_mail(subject, body_text, addr_from, recipient_list, fail_silently=False, auth_user=None, auth_password=None, attachments=None, body_html=None, html_message=None, connection=None, headers=None): """ Sends a multipart email containing text and html versions which are encrypted for each recipient that has a valid gpg key installed. """ # Make sure only one HTML option is specified if body_html is not None and html_message is not None: # pragma: no cover raise ValueError("You cannot specify body_html and html_message at " "the same time. Please only use html_message.") # Push users to update their code if body_html is not None: # pragma: no cover warn("Using body_html is deprecated; use the html_message argument " "instead. Please update your code.", DeprecationWarning) html_message = body_html # Allow for a single address to be passed in. if isinstance(recipient_list, six.string_types): recipient_list = [recipient_list] connection = connection or get_connection( username=auth_user, password=auth_password, fail_silently=fail_silently) # Obtain a list of the recipients that have gpg keys installed. key_addresses = {} if USE_GNUPG: from email_extras.models import Address key_addresses = dict(Address.objects.filter(address__in=recipient_list) .values_list('address', 'use_asc')) # Create the gpg object. if key_addresses: gpg = GPG(gnupghome=GNUPG_HOME) if GNUPG_ENCODING is not None: gpg.encoding = GNUPG_ENCODING # Check if recipient has a gpg key installed def has_pgp_key(addr): return addr in key_addresses # Encrypts body if recipient has a gpg key installed. def encrypt_if_key(body, addr_list): if has_pgp_key(addr_list[0]): encrypted = gpg.encrypt(body, addr_list[0], always_trust=ALWAYS_TRUST) if encrypted == "" and body != "": # encryption failed raise EncryptionFailedError("Encrypting mail to %s failed.", addr_list[0]) return smart_str(encrypted) return body # Load attachments and create name/data tuples. attachments_parts = [] if attachments is not None: for attachment in attachments: # Attachments can be pairs of name/data, or filesystem paths. if not hasattr(attachment, "__iter__"): with open(attachment, "rb") as f: attachments_parts.append((basename(attachment), f.read())) else: attachments_parts.append(attachment) # Send emails - encrypted emails needs to be sent individually, while # non-encrypted emails can be sent in one send. So the final list of # lists of addresses to send to looks like: # [[unencrypted1, unencrypted2, unencrypted3], [encrypted1], [encrypted2]] unencrypted = [addr for addr in recipient_list if addr not in key_addresses] unencrypted = [unencrypted] if unencrypted else unencrypted encrypted = [[addr] for addr in key_addresses] for addr_list in unencrypted + encrypted: msg = EmailMultiAlternatives(subject, encrypt_if_key(body_text, addr_list), addr_from, addr_list, connection=connection, headers=headers) if html_message is not None: if has_pgp_key(addr_list[0]): mimetype = "application/gpg-encrypted" else: mimetype = "text/html" msg.attach_alternative(encrypt_if_key(html_message, addr_list), mimetype) for parts in attachments_parts: name = parts[0] if key_addresses.get(addr_list[0]): name += ".asc" msg.attach(name, encrypt_if_key(parts[1], addr_list)) msg.send(fail_silently=fail_silently)
trial = Timer("digest.update(message)", setup) algo_run.append(trial.repeat(RUN_COUNT, 1)) set_run.append(algo_run) lib_run.append(set_run) result.append(lib_run) # ********** ############################ ************************************** # ********** BEGIN 'PYTHON-GNUPG' LIBRARY ************************************** # ********** ############################ ************************************** lib_run = ['python-gnupg'] # Setupt the GPG object that will be used for all python-gnupg oprerations gpg = GPG(gnupghome='.python-gnupg') gpg.encoding = 'utf-8' # These commands needed to be run once to generate and save the key #input_data = gpg.gen_key_input(key_type="RSA", key_length=2**KEY_EXP) #gpg_key = gpg.gen_key(input_data) # BEGIN BLOCK CIPHER OPERATIONS set_run = ['block'] setup = """\ from __main__ import gpg, message, enctext """ # Create cipher, create cipher text for decryption, time operations, update # result with each new operation algo_run = ['3DES'] enctext = gpg.encrypt(message, None, symmetric='3DES',
""" Encrypt a file using GPG, then FTP it to a remote server. """ from gnupg import GPG from ftplib import FPT # Create instance and set gpg working directory gpg = GPG(gnupghome=".gpg") # import an existing public key with open("mykey.asc", 'r') as fp: key_data = fp.read() import_status = gpg.import_keys(key_data) print("ok: {}".format(import_status.results["ok"])) print("text: {}".format(import_status.results["text"])) # Encrypt a file using the public key. with open("plain.txt", 'rb') as fp: encrypted_file = "encrypted.asc" encrypt_status = gpg.encrypt_file(fp, recipients=import_status.fingerprints, always_trust=True, output=encrypted_file) print("ok {}".format(encrypt_status.ok)) print("text: {}".format(encrypt_status.text)) print("stderr: {}".format(encrypt_status.stderr)) # FTP the file with FTP("ftp.somehost.com") as ftp:
def get_gpg(): gpg = GPG(gnupghome=GNUPG_HOME) if GNUPG_ENCODING is not None: gpg.encoding = GNUPG_ENCODING return gpg
def gpg_instance(self): if self.config.gpgdir: return GPG(gnupghome=self.config.gpgdir)
print('Environment variables not properly set: {0}'.format(e)) exit() if __name__ == '__main__': get_env_vars() parser = argparse.ArgumentParser(description=DESCR, epilog=EPILOG) parser.add_argument('-k', '--key', dest='key', type=str, help=KEY_DSC) parser.add_argument('-l', '--list', action='store_true') parser.add_argument('-p', '--password', action='store_true') parser.add_argument('-u', '--user', action='store_true') parser.add_argument('-s', '--set', action='store_true') parser.add_argument('-r', '--remove', action='store_true') args = parser.parse_args() gpg_home, pass_loc = get_env_vars() gpg = GPG(gnupghome=gpg_home) with open(pass_loc, mode='rb') as f: decoded = gpg.decrypt_file(f, passphrase=getpass()) if decoded.data == b'': print("Incorrect Passphrase") exit() passes = loads(clean_gpg_json(decoded.data)) if args.list: for key in passes.keys(): print(key) if args.key is not None: if args.password: print_pass(passes, args.key) if args.user: print_user(passes, args.key) if args.set or args.remove:
def setUp(self): now = time.localtime() now = calendar.timegm(now) self.goodEmail = "signTest-{0}@learningregistry.org".format(now) self.goodRealName = "Autogenerated Sign Test" self.goodpassphrase = "supersecret" try: for root, dirs, files in os.walk(self.gnupgHome): for filename in files: try: os.unlink(os.path.join(root, filename)) except: pass os.removedirs(root) except: pass os.makedirs(self.gnupgHome) self.gpg = GPG(gpgbinary=self.gpgbin, gnupghome=self.gnupgHome) input = self.gpg.gen_key_input(name_real=self.goodRealName, name_email=self.goodEmail, passphrase=self.goodpassphrase) self.goodPrivateKey = self.gpg.gen_key(input) privateKeyAvailable = False privateKeys = self.gpg.list_keys(secret=True) for skey in privateKeys: if skey["keyid"] == self.goodPrivateKey.fingerprint: privateKeyAvailable = True self.privateKeyInfo = skey break if skey["fingerprint"] == self.goodPrivateKey.fingerprint: privateKeyAvailable = True self.privateKeyInfo = skey break assert privateKeyAvailable == True, "Could not locate generated Private Key" self.goodkeyid = self.privateKeyInfo["keyid"] self.goodowner = self.privateKeyInfo["uids"][0] self.badkeyid = "XXXXXXXXXXXXXXXX" self.badpassphrase = "bad passphrase" self.sampleJSON = ''' { "_id":"00e3f67232e743b6bc2a079bd98ff55a", "_rev":"1-8163d32f6cc9996f2b7228d8b5db7962", "doc_type":"resource_data", "update_timestamp":"2011-03-14 13:36:04.617999", "resource_data":"<oai_dc:dc xmlns:oai_dc=\\"http://www.openarchives.org/OAI/2.0/oai_dc/\\" xmlns:dc=\\"http://purl.org/dc/elements/1.1/\\" xmlns:xsi=\\"http://www.w3.org/2001/XMLSchema-instance\\" xmlns=\\"http://www.openarchives.org/OAI/2.0/\\" xsi:schemaLocation=\\"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd\\">\\n<dc:title>A chat about America. October and November, 1884.</dc:title>\\n<dc:creator>J. P.</dc:creator>\\n<dc:subject>United States--Description and travel.</dc:subject>\\n<dc:description>\\"Printed for private circulation only.\\"</dc:description>\\n<dc:description>Electronic reproduction. Washington, D.C. : Library of Congress, [2002-2003]</dc:description>\\n<dc:publisher>Manchester, Palmer & Howe</dc:publisher>\\n<dc:date>1885</dc:date>\\n<dc:type>text</dc:type>\\n<dc:identifier>http://hdl.loc.gov/loc.gdc/lhbtn.12281</dc:identifier>\\n<dc:language>eng</dc:language>\\n<dc:coverage>United States</dc:coverage>\\n</oai_dc:dc>\\n ", "keys":["United States--Description and travel.","eng"], "submitter_type":"agent", "resource_data_type":"metadata", "payload_schema_locator":"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd", "payload_placement":"inline", "submitter":"NSDL 2 LR Data Pump", "payload_schema":["oai_dc"], "node_timestamp":"2011-03-14 13:36:04.617999", "doc_version":"0.10.0", "create_timestamp":"2011-03-14 13:36:04.617999", "active":true, "publishing_node":"string", "resource_locator":"http://hdl.loc.gov/loc.gdc/lhbtn.12281", "doc_ID":"00e3f67232e743b6bc2a079bd98ff55a", "TOS": { "submission_TOS": "http://example.com/tos/unknown", "submission_attribution": "unidentified" } } ''' self.sampleJSON__0_23_0 = ''' { "_id":"00e3f67232e743b6bc2a079bd98ff55a", "_rev":"1-8163d32f6cc9996f2b7228d8b5db7962", "doc_type":"resource_data", "update_timestamp":"2011-03-14 13:36:04.617999", "resource_data":"<oai_dc:dc xmlns:oai_dc=\\"http://www.openarchives.org/OAI/2.0/oai_dc/\\" xmlns:dc=\\"http://purl.org/dc/elements/1.1/\\" xmlns:xsi=\\"http://www.w3.org/2001/XMLSchema-instance\\" xmlns=\\"http://www.openarchives.org/OAI/2.0/\\" xsi:schemaLocation=\\"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd\\">\\n<dc:title>A chat about America. October and November, 1884.</dc:title>\\n<dc:creator>J. P.</dc:creator>\\n<dc:subject>United States--Description and travel.</dc:subject>\\n<dc:description>\\"Printed for private circulation only.\\"</dc:description>\\n<dc:description>Electronic reproduction. Washington, D.C. : Library of Congress, [2002-2003]</dc:description>\\n<dc:publisher>Manchester, Palmer & Howe</dc:publisher>\\n<dc:date>1885</dc:date>\\n<dc:type>text</dc:type>\\n<dc:identifier>http://hdl.loc.gov/loc.gdc/lhbtn.12281</dc:identifier>\\n<dc:language>eng</dc:language>\\n<dc:coverage>United States</dc:coverage>\\n</oai_dc:dc>\\n ", "keys":["United States--Description and travel.","eng"], "identity":{ "submitter_type":"agent", "submitter":"NSDL 2 LR Data Pump" }, "resource_data_type":"metadata", "payload_schema_locator":"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd", "payload_placement":"inline", "payload_schema":["oai_dc"], "node_timestamp":"2011-03-14 13:36:04.617999", "doc_version":"0.23.0", "create_timestamp":"2011-03-14 13:36:04.617999", "active":true, "publishing_node":"string", "resource_locator":"http://hdl.loc.gov/loc.gdc/lhbtn.12281", "doc_ID":"00e3f67232e743b6bc2a079bd98ff55a", "TOS": { "submission_TOS": "http://example.com/tos/unknown", "submission_attribution": "unidentified" } } ''' self.sampleJSON__0_51_0 = ''' { "_id":"00e3f67232e743b6bc2a079bd98ff55a", "_rev":"1-8163d32f6cc9996f2b7228d8b5db7962", "doc_type":"resource_data", "update_timestamp":"2014-04-01 13:36:04.617999", "resource_data":"<oai_dc:dc xmlns:oai_dc=\\"http://www.openarchives.org/OAI/2.0/oai_dc/\\" xmlns:dc=\\"http://purl.org/dc/elements/1.1/\\" xmlns:xsi=\\"http://www.w3.org/2001/XMLSchema-instance\\" xmlns=\\"http://www.openarchives.org/OAI/2.0/\\" xsi:schemaLocation=\\"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd\\">\\n<dc:title>A chat about America. October and November, 1884.</dc:title>\\n<dc:creator>J. P.</dc:creator>\\n<dc:subject>United States--Description and travel.</dc:subject>\\n<dc:description>\\"Printed for private circulation only.\\"</dc:description>\\n<dc:description>Electronic reproduction. Washington, D.C. : Library of Congress, [2002-2003]</dc:description>\\n<dc:publisher>Manchester, Palmer & Howe</dc:publisher>\\n<dc:date>1885</dc:date>\\n<dc:type>text</dc:type>\\n<dc:identifier>http://hdl.loc.gov/loc.gdc/lhbtn.12281</dc:identifier>\\n<dc:language>eng</dc:language>\\n<dc:coverage>United States</dc:coverage>\\n</oai_dc:dc>\\n ", "keys":["United States--Description and travel.","eng"], "identity":{ "submitter_type":"agent", "submitter":"NSDL 2 LR Data Pump" }, "resource_data_type":"metadata", "payload_schema_locator":"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd", "payload_placement":"inline", "payload_schema":["oai_dc"], "node_timestamp":"2014-04-01 13:32:04.617999", "doc_version":"0.51.0", "create_timestamp":"2014-04-01 13:36:04.617999", "active":true, "publishing_node":"string", "resource_locator":"http://hdl.loc.gov/loc.gdc/lhbtn.12281", "doc_ID":"00e3f67232e743b6bc2a079bd98ff55a", "TOS": { "submission_TOS": "http://example.com/tos/unknown", "submission_attribution": "unidentified" } } ''' self.sampleJSON_no_coercion = ''' { "_id":"00e3f67232e743b6bc2a079bd98ff55a", "_rev":"1-8163d32f6cc9996f2b7228d8b5db7962", "doc_type":"resource_data", "update_timestamp":"2011-03-14 13:36:04.617999", "resource_data": { "name": "Test coersion", "nullable": null, "booleanT": true, "booleanF": false }, "keys":["United States--Description and travel.","eng"], "identity":{ "submitter_type":"agent", "submitter":"NSDL 2 LR Data Pump" }, "resource_data_type":"metadata", "payload_schema_locator":"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd", "payload_placement":"inline", "payload_schema":["oai_dc"], "node_timestamp":"2011-03-14 13:36:04.617999", "doc_version":"0.23.0", "create_timestamp":"2011-03-14 13:36:04.617999", "active":true, "publishing_node":"string", "resource_locator":"http://hdl.loc.gov/loc.gdc/lhbtn.12281", "doc_ID":"00e3f67232e743b6bc2a079bd98ff55a", "TOS": { "submission_TOS": "http://example.com/tos/unknown", "submission_attribution": "unidentified" } } ''' self.sampleJSON_lossy_sha256 = [ ''' { "_id":"00e3f67232e743b6bc2a079bd98ff55a", "_rev":"1-8163d32f6cc9996f2b7228d8b5db7962", "doc_type":"resource_data", "update_timestamp":"2011-03-14 13:36:04.617999", "resource_data": { "name": "Test Lossy" "integer": 1 }, "keys":["United States--Description and travel.","eng"], "identity":{ "submitter_type":"agent", "submitter":"NSDL 2 LR Data Pump" }, "resource_data_type":"metadata", "payload_schema_locator":"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd", "payload_placement":"inline", "payload_schema":["oai_dc"], "node_timestamp":"2011-03-14 13:36:04.617999", "doc_version":"0.23.0", "create_timestamp":"2011-03-14 13:36:04.617999", "active":true, "publishing_node":"string", "resource_locator":"http://hdl.loc.gov/loc.gdc/lhbtn.12281", "doc_ID":"00e3f67232e743b6bc2a079bd98ff55a", "TOS": { "submission_TOS": "http://example.com/tos/unknown", "submission_attribution": "unidentified" } } ''', ''' { "_id":"00e3f67232e743b6bc2a079bd98ff55a", "_rev":"1-8163d32f6cc9996f2b7228d8b5db7962", "doc_type":"resource_data", "update_timestamp":"2011-03-14 13:36:04.617999", "resource_data": { "name": "Test Lossy" "float": 1.1 }, "keys":["United States--Description and travel.","eng"], "identity":{ "submitter_type":"agent", "submitter":"NSDL 2 LR Data Pump" }, "resource_data_type":"metadata", "payload_schema_locator":"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd", "payload_placement":"inline", "payload_schema":["oai_dc"], "node_timestamp":"2011-03-14 13:36:04.617999", "doc_version":"0.23.0", "create_timestamp":"2011-03-14 13:36:04.617999", "active":true, "publishing_node":"string", "resource_locator":"http://hdl.loc.gov/loc.gdc/lhbtn.12281", "doc_ID":"00e3f67232e743b6bc2a079bd98ff55a", "TOS": { "submission_TOS": "http://example.com/tos/unknown", "submission_attribution": "unidentified" } } ''', ''' { "_id":"00e3f67232e743b6bc2a079bd98ff55a", "_rev":"1-8163d32f6cc9996f2b7228d8b5db7962", "doc_type":"resource_data", "update_timestamp":"2011-03-14 13:36:04.617999", "resource_data": { "name": "Test Lossy" "max_int": 9007199254740990 }, "keys":["United States--Description and travel.","eng"], "identity":{ "submitter_type":"agent", "submitter":"NSDL 2 LR Data Pump" }, "resource_data_type":"metadata", "payload_schema_locator":"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd", "payload_placement":"inline", "payload_schema":["oai_dc"], "node_timestamp":"2011-03-14 13:36:04.617999", "doc_version":"0.23.0", "create_timestamp":"2011-03-14 13:36:04.617999", "active":true, "publishing_node":"string", "resource_locator":"http://hdl.loc.gov/loc.gdc/lhbtn.12281", "doc_ID":"00e3f67232e743b6bc2a079bd98ff55a", "TOS": { "submission_TOS": "http://example.com/tos/unknown", "submission_attribution": "unidentified" } } ''', ''' { "_id":"00e3f67232e743b6bc2a079bd98ff55a", "_rev":"1-8163d32f6cc9996f2b7228d8b5db7962", "doc_type":"resource_data", "update_timestamp":"2011-03-14 13:36:04.617999", "resource_data": { "name": "Test Lossy" "min_int": -9007199254740990 }, "keys":["United States--Description and travel.","eng"], "identity":{ "submitter_type":"agent", "submitter":"NSDL 2 LR Data Pump" }, "resource_data_type":"metadata", "payload_schema_locator":"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd", "payload_placement":"inline", "payload_schema":["oai_dc"], "node_timestamp":"2011-03-14 13:36:04.617999", "doc_version":"0.23.0", "create_timestamp":"2011-03-14 13:36:04.617999", "active":true, "publishing_node":"string", "resource_locator":"http://hdl.loc.gov/loc.gdc/lhbtn.12281", "doc_ID":"00e3f67232e743b6bc2a079bd98ff55a", "TOS": { "submission_TOS": "http://example.com/tos/unknown", "submission_attribution": "unidentified" } } ''' ] self.sampleJSON_strip = '''{"keys": ["United States--Description and travel.", "eng"], "TOS": {"submission_attribution": "unidentified", "submission_TOS": "http://example.com/tos/unknown"}, "payload_placement": "inline", "active": true, "resource_locator": "http://hdl.loc.gov/loc.gdc/lhbtn.12281", "doc_type": "resource_data", "resource_data": "<oai_dc:dc xmlns:oai_dc=\\"http://www.openarchives.org/OAI/2.0/oai_dc/\\" xmlns:dc=\\"http://purl.org/dc/elements/1.1/\\" xmlns:xsi=\\"http://www.w3.org/2001/XMLSchema-instance\\" xmlns=\\"http://www.openarchives.org/OAI/2.0/\\" xsi:schemaLocation=\\"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd\\">\\n<dc:title>A chat about America. October and November, 1884.</dc:title>\\n<dc:creator>J. P.</dc:creator>\\n<dc:subject>United States--Description and travel.</dc:subject>\\n<dc:description>\\"Printed for private circulation only.\\"</dc:description>\\n<dc:description>Electronic reproduction. Washington, D.C. : Library of Congress, [2002-2003]</dc:description>\\n<dc:publisher>Manchester, Palmer & Howe</dc:publisher>\\n<dc:date>1885</dc:date>\\n<dc:type>text</dc:type>\\n<dc:identifier>http://hdl.loc.gov/loc.gdc/lhbtn.12281</dc:identifier>\\n<dc:language>eng</dc:language>\\n<dc:coverage>United States</dc:coverage>\\n</oai_dc:dc>\\n ", "submitter_type": "agent", "resource_data_type": "metadata", "payload_schema_locator": "http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd", "payload_schema": ["oai_dc"], "doc_version": "0.10.0", "submitter": "NSDL 2 LR Data Pump"}''' self.sampleJSON_strip_normal = '''{"keys": ["United States--Description and travel.", "eng"], "TOS": {"submission_attribution": "unidentified", "submission_TOS": "http://example.com/tos/unknown"}, "payload_placement": "inline", "active": "true", "resource_locator": "http://hdl.loc.gov/loc.gdc/lhbtn.12281", "doc_type": "resource_data", "resource_data": "<oai_dc:dc xmlns:oai_dc=\\"http://www.openarchives.org/OAI/2.0/oai_dc/\\" xmlns:dc=\\"http://purl.org/dc/elements/1.1/\\" xmlns:xsi=\\"http://www.w3.org/2001/XMLSchema-instance\\" xmlns=\\"http://www.openarchives.org/OAI/2.0/\\" xsi:schemaLocation=\\"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd\\">\\n<dc:title>A chat about America. October and November, 1884.</dc:title>\\n<dc:creator>J. P.</dc:creator>\\n<dc:subject>United States--Description and travel.</dc:subject>\\n<dc:description>\\"Printed for private circulation only.\\"</dc:description>\\n<dc:description>Electronic reproduction. Washington, D.C. : Library of Congress, [2002-2003]</dc:description>\\n<dc:publisher>Manchester, Palmer & Howe</dc:publisher>\\n<dc:date>1885</dc:date>\\n<dc:type>text</dc:type>\\n<dc:identifier>http://hdl.loc.gov/loc.gdc/lhbtn.12281</dc:identifier>\\n<dc:language>eng</dc:language>\\n<dc:coverage>United States</dc:coverage>\\n</oai_dc:dc>\\n ", "submitter_type": "agent", "resource_data_type": "metadata", "payload_schema_locator": "http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd", "payload_schema": ["oai_dc"], "doc_version": "0.10.0", "submitter": "NSDL 2 LR Data Pump"}''' self.sampleJSON_strip_normal_bencode = '''d3:TOSd14:submission_TOS30:http://example.com/tos/unknown22:submission_attribution12:unidentifiede6:active4:true8:doc_type13:resource_data11:doc_version6:0.10.04:keysl38:United States--Description and travel.3:enge17:payload_placement6:inline14:payload_schemal6:oai_dce22:payload_schema_locator90:http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd13:resource_data968:<oai_dc:dc xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.openarchives.org/OAI/2.0/" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd">\n<dc:title>A chat about America. October and November, 1884.</dc:title>\n<dc:creator>J. P.</dc:creator>\n<dc:subject>United States--Description and travel.</dc:subject>\n<dc:description>"Printed for private circulation only."</dc:description>\n<dc:description>Electronic reproduction. Washington, D.C. : Library of Congress, [2002-2003]</dc:description>\n<dc:publisher>Manchester, Palmer & Howe</dc:publisher>\n<dc:date>1885</dc:date>\n<dc:type>text</dc:type>\n<dc:identifier>http://hdl.loc.gov/loc.gdc/lhbtn.12281</dc:identifier>\n<dc:language>eng</dc:language>\n<dc:coverage>United States</dc:coverage>\n</oai_dc:dc>\n 18:resource_data_type8:metadata16:resource_locator38:http://hdl.loc.gov/loc.gdc/lhbtn.122819:submitter19:NSDL 2 LR Data Pump14:submitter_type5:agente''' self.sampleJSON_sha256 = '''ef1b3b63adc663602c7a3c7595951b2761b34f5f6490ea1acee3df0fd97db03c''' self.sampleKeyLocations = [ "http://example.com/mykey", "http://example2.com/mykey" ] self.signatureTemplate = '{{"key_location": [{0}], "key_owner": "' + self.goodowner + '", "signing_method": "LR-PGP.1.0", "signature": "{1}"}}'