def read_cert_secret(k8s_api, secret_name, namespace): cert_data = None cert = None key = None try: cert_data = k8s_api.read_namespaced_secret(secret_name, namespace) except client.rest.ApiException as e: if e.reason == "Not Found": pass else: logger.info("secret %s/%s could not be read: %s" % (namespace, secret_name, e)) if cert_data and cert_data.data: cert_data = cert_data.data cert = cert_data.get('tls.crt', None) if cert: cert = binascii.a2b_base64(cert) key = cert_data.get('tls.key', None) if key: key = binascii.a2b_base64(key) return (cert, key, cert_data)
def savePathwayAs(self, pathwayId, filename, revisionNumb=0, display=True): """Save a pathway. :param str pathwayId: the pathway identifier. :param str filename: the name of the file. If a filename extension is not provided the pathway will be saved as a pdf (default). :param int revisionNumb: the revision number of the pathway (use '0 for most recent version). :param bool display: if True the pathway will be displayed in your browser. .. note:: Method from bioservices. Not a WikiPathways function """ if filename.find(".") == -1: filename = "%s.%s" % (filename, "pdf") filetype = filename.split(".")[-1] res = self.getPathwayAs(pathwayId, filetype=filetype, revisionNumb=revisionNumb) with open(filename, "wb") as f: import binascii try: # python3 newres = binascii.a2b_base64(bytes(res, "utf-8")) except: newres = binascii.a2b_base64(res) f.write(newres) if display: webbrowser.open(filename) f.close()
def write_file(self, data, metadata): """Write the probed file data to the bcfg2 specification.""" filename = data.get("name") contents = binascii.a2b_base64(data.text) entry = self.entries[metadata.hostname][filename] cfg = self.core.plugins['Cfg'] specific = "%s.H_%s" % (os.path.basename(filename), metadata.hostname) # we can't use os.path.join() for this because specific # already has a leading /, which confuses os.path.join() fileloc = "%s%s" % (cfg.data, os.path.join(filename, specific)) create = False try: cfg.entries[filename].bind_entry(entry, metadata) except Bcfg2.Server.Plugin.PluginExecutionError: create = True # get current entry data if entry.text and entry.get("encoding") == "base64": entrydata = binascii.a2b_base64(entry.text) else: entrydata = entry.text if create: self.logger.info("Writing new probed file %s" % fileloc) try: os.makedirs(os.path.dirname(fileloc)) except OSError, err: if err.errno == errno.EEXIST: pass else: raise open(fileloc, 'wb').write(contents) infoxml = os.path.join("%s%s" % (cfg.data, filename), "info.xml") if not os.path.exists(infoxml): self.write_infoxml(infoxml, entry, data) # Service the FAM events queued up by the key generation # so the data structure entries will be available for # binding. # # NOTE: We wait for up to ten seconds. There is some # potential for race condition, because if the file # monitor doesn't get notified about the new key files in # time, those entries won't be available for binding. In # practice, this seems "good enough". tries = 0 is_bound = False while not is_bound: if tries >= 10: self.logger.error("%s still not registered" % filename) self.core.fam.handle_events_in_interval(1) try: cfg.entries[filename].bind_entry(entry, metadata) is_bound = True except Bcfg2.Server.Plugin.PluginExecutionError: pass tries += 1
def build_snap_ent(entry): basefields = [] if entry.tag in ['Package', 'Service']: basefields += ['type'] desired = dict([(key, u_str(entry.get(key))) for key in basefields]) state = dict([(key, u_str(entry.get(key))) for key in basefields]) desired.update([(key, u_str(entry.get(key))) for key in \ datafields[entry.tag]]) if entry.tag == 'ConfigFile' or \ ((entry.tag == 'Path') and (entry.get('type') == 'file')): if entry.text == None: desired['contents'] = None else: if entry.get('encoding', 'ascii') == 'ascii': desired['contents'] = u_str(entry.text) else: desired['contents'] = u_str(binascii.a2b_base64(entry.text)) if 'current_bfile' in entry.attrib: state['contents'] = u_str(binascii.a2b_base64( \ entry.get('current_bfile'))) elif 'current_bdiff' in entry.attrib: diff = binascii.a2b_base64(entry.get('current_bdiff')) state['contents'] = u_str( \ '\n'.join(difflib.restore(diff.split('\n'), 1))) state.update([(key, u_str(entry.get('current_' + key, entry.get(key)))) \ for key in datafields[entry.tag]]) if entry.tag in ['ConfigFile', 'Path'] and entry.get('exists', 'true') == 'false': state = None return [desired, state]
def decode_seq(state): "Convert an encoded string to a sequence" state=translate(state, tminus) l=len(state) if l > 76: states=[] j=0 for i in range(l/76): k=j+76 states.append(a2b_base64(state[j:k])) j=k if j < l: state=state[j:] l=len(state) k=l%4 if k: state=state+'='*(4-k) states.append(a2b_base64(state)) state=''.join(states) else: l=len(state) k=l%4 if k: state=state+'='*(4-k) state=a2b_base64(state) state=decompress(state) try: return list(MiniUnpickler(StringIO(state)).load()) except: return []
def make_baseline_from_xml(xml_report, appraiser_type): """search the xml for records and add each one to a dictionary.""" timestamp = get_current_timestamp() baseline_name = "full_{0}_baseline_{1}".format(appraiser_type, timestamp) baseline_description = "{0} baseline created by parsing an xml report and uploaded for systems testing".format(appraiser_type) baseline = {"name": baseline_name, "description": baseline_description} baseline["records"] = [] tree = parse_xml_with_stripped_namespaces(xml_report) if appraiser_type == "TPM": pcr_tags = get_all_nodes_recursively(tree, "PcrValue") for pcr_tag in pcr_tags: tpm_digest = get_all_nodes_recursively(pcr_tag, "digest")[0].text parsed_record = {} parsed_record["pcr"] = pcr_tag.attrib['PcrNumber'] parsed_record["hash"] = binascii.hexlify(binascii.a2b_base64(tpm_digest)) baseline["records"].append(parsed_record) if appraiser_type == "IMA": ima_records = get_all_nodes_recursively(tree, "imaRecords") for ima_record in ima_records: ima_path = get_all_nodes_recursively(ima_record, "path")[0].text ima_digest = get_all_nodes_recursively(ima_record, "digest")[0].text parsed_record = {} parsed_record['path'] = ima_path hash64 = ima_digest parsed_record["hash"] = ( binascii.hexlify(binascii.a2b_base64(hash64))) baseline["records"].append(parsed_record) logging.info("created {0} baseline from xml with {1} records".format( appraiser_type, str(len(baseline["records"])))) return baseline
def decrypt_sym(data, key, method, **kwargs): """ Decrypt data using symmetric secret. Currently, the only encryption method supported is AES-256 CTR mode. :param data: The data to be decrypted. :type data: str :param key: The key used to decrypt C{data} (must be 256 bits long). :type key: str :param method: The encryption method to use. :type method: str :param kwargs: Other parameters specific to each encryption method. :type kwargs: dict :return: The decrypted data. :rtype: str :raise UnknownEncryptionMethodError: Raised when C{method} is unknown. """ soledad_assert_type(key, str) # assert params soledad_assert(len(key) == 32, "Wrong key size: %s (must be 256 bits long)." % len(key)) # 32 x 8 = 256 bits. soledad_assert("iv" in kwargs, "%s needs an initial value." % method) _assert_known_encryption_method(method) # AES-256 in CTR mode if method == crypto.EncryptionMethods.AES_256_CTR: return AES(key=key, iv=binascii.a2b_base64(kwargs["iv"])).process(data) elif method == crypto.EncryptionMethods.XSALSA20: return XSalsa20(key=key, iv=binascii.a2b_base64(kwargs["iv"])).process(data)
def challenge_ok(b64cert, mychal, ourchal, signature): import bdocpython if not signature: return False, 'DDS did not return signed challenge' bmychal = binascii.a2b_hex(mychal) bchal = binascii.a2b_hex(ourchal) if (bmychal != bchal[0:10]): return False, 'My challenge not present in our challenge' bcert = binascii.a2b_base64(b64cert) bsign = binascii.a2b_base64(signature) cv = bdocpython.ChallengeVerifier() cv.setCertificate(bcert) cv.setChallenge(bchal) cv.setSignature(bsign) res = cv.isChallengeOk() if not res: return False, cv.error return True, None
def decode_seq(state): "Convert an encoded string to a sequence" state=translate(state, tminus) l=len(state) if l > 76: states=[] j=0 for i in range(l/76): k=j+76 states.append(a2b_base64(state[j:k])) j=k if j < l: state=state[j:] l=len(state) k=l%4 if k: state=state+'='*(4-k) states.append(a2b_base64(state)) state=''.join(states) else: l=len(state) k=l%4 if k: state=state+'='*(4-k) state=a2b_base64(state) state=decompress(state) if state.find('*') >= 0: raise 'Illegal State', state try: return list(eval(state,{'__builtins__':{}})) except: return []
def clean_nameserver_update_secret(self): secret = self.cleaned_data['nameserver_update_secret'] try: binascii.a2b_base64(secret.encode(encoding="ascii", errors="strict")) except (binascii.Error, UnicodeEncodeError): raise forms.ValidationError(_("Enter a valid secret in base64 format."), code='invalid') return secret
def verify_and_decrypt(pmsg, emsg, sig, senderPubPem, receiverPrivPem, hash = 'sha256', cipher = 'aes_256_cbc', padding = 'pkcs1_oaep'): padding = PADDING[padding] pmsg = binascii.a2b_base64(pmsg) emsg = binascii.a2b_base64(emsg) sig = binascii.a2b_base64(sig) key_len = int(cipher.split("_")[1]) md = EVP.MessageDigest(hash) md.update(pmsg) md.update(emsg) digest = md.digest() skey = RSA.load_pub_key_bio(BIO.MemoryBuffer(senderPubPem)) if not skey.verify(digest, sig, hash): raise Exception("could not verify signature") rkey = RSA.load_key_bio(BIO.MemoryBuffer(receiverPrivPem)) kv = rkey.private_decrypt(emsg, padding) key = kv[0:key_len/8] iv = kv[key_len/8:] c = EVP.Cipher(alg = cipher, key = key, iv = iv, op = m2.decrypt) msg = cipher_filter(c, pmsg) return msg
def _encryptPlayerUrl(self, data): printDBG("_encryptPlayerUrl data[%s]" % data) decrypted = '' try: data = byteify( json.loads(data) ) salt = a2b_hex(data["v"]) key, iv = EVP_BytesToKey(md5, "s05z9Gpd=syG^7{", salt, 32, 16, 1) if iv != a2b_hex(data.get('b', '')): prinDBG("_encryptPlayerUrl IV mismatched") if 0: from Crypto.Cipher import AES aes = AES.new(key, AES.MODE_CBC, iv, segment_size=128) decrypted = aes.decrypt(a2b_base64(data["a"])) decrypted = decrypted[0:-ord(decrypted[-1])] else: kSize = len(key) alg = AES_CBC(key, keySize=kSize) decrypted = alg.decrypt(a2b_base64(data["a"]), iv=iv) decrypted = decrypted.split('\x00')[0] decrypted = "%s" % json.loads( decrypted ).encode('utf-8') except: printExc() decrypted = '' return decrypted
def __parse_doc_from_couch(self, result, doc_id, check_for_conflicts=False): # restrict to u1db documents if 'u1db_rev' not in result: return None doc = ServerDocument(doc_id, result['u1db_rev']) # set contents or make tombstone if '_attachments' not in result \ or 'u1db_content' not in result['_attachments']: doc.make_tombstone() else: doc.content = json.loads( binascii.a2b_base64( result['_attachments']['u1db_content']['data'])) # determine if there are conflicts if check_for_conflicts \ and '_attachments' in result \ and 'u1db_conflicts' in result['_attachments']: doc.set_conflicts( self._build_conflicts( doc.doc_id, json.loads(binascii.a2b_base64( result['_attachments']['u1db_conflicts']['data'])))) # store couch revision doc.couch_rev = result['_rev'] # store transactions doc.transactions = result['u1db_transactions'] return doc
def issue_row(raw_row): issue_row = {} for column in COLUMN_HEADERS: column_data_raw = raw_row.findtext(column) if column_data_raw: if column in ['issueDetail', 'issueBackground', 'remediationBackground']: issue_row[column] = htmltext(column_data_raw) else: issue_row[column] = column_data_raw if len(issue_row[column]) > 32000: issue_row[column] = "".join(issue_row[column][:32000], " [Text Cut Due To Length]") request = raw_row.findtext('./requestresponse/request') if request: parsed_request = HTTPRequest(binascii.a2b_base64(request)) formatted_request_a = "command : {}\nuri : {}\nrequest_version : {}".format(parsed_request.command, parsed_request.path, parsed_request.request_version) formatted_request_b = "\n".join("{}: {}".format(header, parsed_request.headers[header]) for header in parsed_request.headers.keys()) issue_row['requestHeaders'] = "{}\n{}".format(formatted_request_a, formatted_request_b) response = raw_row.findtext('./requestresponse/response') if response: parsed_response = HTTPResponse(FakeSocket(binascii.a2b_base64(response))) parsed_response.begin() formatted_response = "\n".join(["{} : {}".format(header_item[0], header_item[1]) for header_item in parsed_response.getheaders()]) issue_row['responseHeaders'] = formatted_response return issue_row
def verify_password(verifier, password): hashfun, iterations, salt, hashed = verifier.split(b"$") hashfun = hashfun.decode("ascii") try: hashlib.new(hashfun) except ValueError as err: raise LookupError( "Hash function not supported: {}".format(hashfun)) from err try: iterations = int(iterations.decode("ascii")) except ValueError as err: raise ValueError("Hash database entry corrupted") from err hashfun_constructor = functools.partial(hashlib.new, hashfun) if isinstance(password, str): password = prepare_password(password) hashed = binascii.a2b_base64(hashed) salt = binascii.a2b_base64(salt) new_hashed = pbkdf2(hashfun_constructor, password, salt, iterations, len(hashed)) return hmac.compare_digest(hashed, new_hashed)
def _decrypt_v1(self, data): # get encrypted secret from dictionary: the old format allowed for # storage of more than one secret, but this feature was never used and # soledad has been using only one secret so far. As there is a corner # case where the old 'active_secret' key might not be set, we just # ignore it and pop the only secret found in the 'storage_secrets' key. secret_id = data['storage_secrets'].keys().pop() encrypted = data['storage_secrets'][secret_id] # assert that we know how to decrypt the secret soledad_assert('cipher' in encrypted) cipher = encrypted['cipher'] if cipher == 'aes256': cipher = ENC_METHOD.aes_256_ctr soledad_assert(cipher in ENC_METHOD) # decrypt salt = binascii.a2b_base64(encrypted['kdf_salt']) key = self._get_key(salt) separator = ':' iv, ciphertext = encrypted['secret'].split(separator, 1) ciphertext = binascii.a2b_base64(ciphertext) plaintext = self._decrypt(key, iv, ciphertext, encrypted, cipher) # create secrets dictionary secrets = { 'remote_secret': plaintext[0:512], 'local_salt': plaintext[512:576], 'local_secret': plaintext[576:1024], } return secrets
def base64(v): try: import binascii binascii.a2b_base64(v) except binascii.Error, e: raise ValueError("badly base64-encoded string: %s" % (e))
def fromString(cls, string): """ Load a hashed entry from a string representing a line in a known_hosts file. @param string: A complete single line from a I{known_hosts} file, formatted as defined by OpenSSH. @type string: L{bytes} @raise DecodeError: if the key, the hostname, or the is not valid encoded as valid base64 @raise InvalidEntry: if the entry does not have the right number of elements and is therefore invalid, or the host/hash portion contains more items than just the host and hash. @raise BadKeyError: if the key, once decoded from base64, is not actually an SSH key. @return: The newly created L{HashedEntry} instance, initialized with the information from C{string}. """ stuff, keyType, key, comment = _extractCommon(string) saltAndHash = stuff[len(cls.MAGIC):].split(b"|") if len(saltAndHash) != 2: raise InvalidEntry() hostSalt, hostHash = saltAndHash self = cls(a2b_base64(hostSalt), a2b_base64(hostHash), keyType, key, comment) return self
def dataReceived(self, data): self._buf += data while True: i = self._buf.find(self.SEP) if i > 0: data = self._buf[:i] try: obj = json.loads(data.decode('utf8')) except Exception as e: self.log.warn('JSON parsing of etcd streaming response from failed: {}'.format(e)) else: for evt in obj[u'result'].get(u'events', []): if u'kv' in evt: d = evt[u'kv'] key = binascii.a2b_base64(d[u'key']) value = binascii.a2b_base64(d[u'value']) version = d[u'version'] create_revision = d[u'create_revision'] mod_revision = d[u'mod_revision'] try: self._cb(key, Value(value, version=version, create_revision=create_revision, mod_revision=mod_revision)) except Exception as e: self.log.warn('exception raised from etcd watch callback {} swallowed: {}'.format(self._cb, e)) self._buf = self._buf[i + len(self.SEP):] else: break
def test_encode_images(): # invalid data, but the header and footer are from real files pngdata = b'\x89PNG\r\n\x1a\nblahblahnotactuallyvalidIEND\xaeB`\x82' jpegdata = b'\xff\xd8\xff\xe0\x00\x10JFIFblahblahjpeg(\xa0\x0f\xff\xd9' pdfdata = b'%PDF-1.\ntrailer<</Root<</Pages<</Kids[<</MediaBox[0 0 3 3]>>]>>>>>>' bindata = b'\xff\xff\xff\xff' fmt = { 'image/png' : pngdata, 'image/jpeg' : jpegdata, 'application/pdf' : pdfdata, 'application/unrecognized': bindata, } encoded = json_clean(encode_images(fmt)) for key, value in fmt.items(): # encoded has unicode, want bytes decoded = a2b_base64(encoded[key]) assert decoded == value encoded2 = json_clean(encode_images(encoded)) assert encoded == encoded2 # test that we don't double-encode base64 str b64_str = {} for key, encoded in encoded.items(): b64_str[key] = unicode_to_str(encoded) encoded3 = json_clean(encode_images(b64_str)) assert encoded3 == b64_str for key, value in fmt.items(): decoded = a2b_base64(encoded3[key]) assert decoded == value
def test_base64invalid(self): # Test base64 with random invalid characters sprinkled throughout # (This requires a new version of binascii.) MAX_BASE64 = 57 lines = [] for i in range(0, len(self.data), MAX_BASE64): b = self.data[i:i+MAX_BASE64] a = binascii.b2a_base64(b) lines.append(a) fillers = bytearray() valid = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/" for i in range(256): if i not in valid: fillers.append(i) def addnoise(line): noise = fillers ratio = len(line) // len(noise) res = bytearray() while line and noise: if len(line) // len(noise) > ratio: c, line = line[0], line[1:] else: c, noise = noise[0], noise[1:] res.append(c) return res + noise + line res = bytearray() for line in map(addnoise, lines): b = binascii.a2b_base64(line) res += b self.assertEqual(res, self.data) # Test base64 with just invalid characters, which should return # empty strings. TBD: shouldn't it raise an exception instead ? self.assertEqual(binascii.a2b_base64(fillers), b'')
def checkHeuristic(self, address, reference, refFirstCall=[]): """ Check a given address with a precomputed hash of a function. Return a percentage of match (you can use a threasold to consider a real match) @type address: DWORD @param address: Address of the function to compare @type reference: STRING @param reference: base64 representation of the compressed information about the function @type refFirstCall: STRING @param refFirstCall: the same, but following the function pointed by the first call in the first BB. (OPTIONAL) @rtype: INTEGER @return: heuristic threasold to consider a real function match """ # self.imm.log("checking heuristically: %08X" % address) # do the hard work just one time if self.heuristicCache.has_key(address): cfg = self.heuristicCache[address] else: cfg = self.makeFunctionHashHeuristic(address) self.heuristicCache[address] = cfg # check reference against our cache sha1 = hashlib.sha1(reference + refFirstCall).digest() if self.heuristicReferencesCache.has_key(sha1): refcfg = self.heuristicReferencesCache[sha1] else: # This's the reference hash to compare with (uncompress just once and cache the results) # Decode each BB-hash refcfg = [] refcfg.append([]) refcfg.append([]) data = binascii.a2b_base64(reference) for o in range(0, len(data), 12): (start, left, right) = struct.unpack("LLL", data[o : o + 12]) refcfg[0].append([start, left, right]) if refFirstCall: data = binascii.a2b_base64(refFirstCall) for o in range(0, len(data), 12): (start, left, right) = struct.unpack("LLL", data[o : o + 12]) refcfg[1].append([start, left, right]) self.heuristicReferencesCache[sha1] = refcfg perc1 = self.compareHeuristic(cfg[0][:], refcfg[0][:]) if cfg[1] or refcfg[1]: perc2 = self.compareHeuristic(cfg[1][:], refcfg[1][:]) # use the average perc = (perc1 + perc2) / 2 else: perc = perc1 return perc
def add_contact(window, ratchet_textbox, handshake_textbox, identity_textbox, other_nick_textbox): OTHER_NICK = other_nick_textbox.get() identity = identity_textbox.get() handshake = handshake_textbox.get() ratchet = ratchet_textbox.get() newaxo.initState(OTHER_NICK, binascii.a2b_base64(identity), binascii.a2b_base64(handshake), binascii.a2b_base64(ratchet), verify=True) newaxo.saveState() window.destroy()
def toByteArray(data): if data is None: return None t = type(data) if t is bytearray: return data elif t is str: return binascii.a2b_base64(data) elif t is unicode: return binascii.a2b_base64(str(data)) raise TypeError(str(t))
def a2b(s): '''Decode a b2a-encoded string.''' s = translate(s, u2a_map) if len(s) <= 76: return a2b_base64(s) frags = [] for i in range(0, len(s), 76): frags.append(a2b_base64(s[i:i + 76])) return ''.join(frags)
def get_items(self, queue_name): items = [] # XXX this might need some explicit sorting dbitems = self.all_items.find({"queue_name": queue_name}) for item in dbitems: items.append(Message(uuid=a2b_base64(item["uuid"]), data=a2b_base64(item["data"]), ttl=item["ttl"], flags=item["flags"])) return items
def _next(self): try: if not self.legacy: gluid = retrieve_gluid(self.dbfile) if self.usedb else self.gluid binascii.a2b_base64(gluid) except: showerror("Error", "Bad decryption key") else: self.go_next = True self.destroy()
def save_str_to_image(self, data, filename): """Save string object into a file converting into binary""" with open(filename,'wb') as f: import binascii try: #python3 newres = binascii.a2b_base64(bytes(data, "utf-8")) except: newres = binascii.a2b_base64(data) f.write(newres)
def post(self): # Just print the publicKey URL dataJson = self.request.get("encrypted-message") dataObject = json.loads(dataJson,encoding="UTF-8") #self.response.write(dataObject) if True: webkeys = db.GqlQuery("SELECT * FROM WebKeyIdentity LIMIT 1") [webkey]= webkeys key=RSA.importKey(webkey.private_key) PKCSCipher = PKCS1_OAEP.new(key) #self.response.write(webkey.private_key) iv_enc = dataObject['initializationVector'] ivec_enc = binascii.a2b_base64(iv_enc) ivec = PKCSCipher.decrypt(ivec_enc) encKeyec_enc = dataObject['cipherKey'] encKey_enc = binascii.a2b_base64(encKeyec_enc) encKey = PKCSCipher.decrypt(encKey_enc) dataec_enc = dataObject['cipherData'] data_enc = binascii.a2b_base64(dataec_enc) AESCipher = AES.new(key=encKey, mode=AES.MODE_CBC, IV=ivec ) data = AESCipher.decrypt(data_enc) #self.response.write(data) #data after dyc. it DecdataObject = json.loads(data,encoding="UTF-8") decType = DecdataObject["type"] decOwner = DecdataObject["owner"] decDestination = DecdataObject["destination"] decPublicKey = DecdataObject["publicKey"] decContext = DecdataObject["@context"] decSigType = DecdataObject["signature"]["type"] decSigCreator = DecdataObject["signature"]["creator"] decSigCreated = DecdataObject["signature"]["created"] decSigSignatureValue = DecdataObject["signature"]["signatureValue"] decSigNonce = DecdataObject["signature"]["nonce"] registerationDate = datetime.datetime.now() decSigCreated = datetime.datetime.strptime(decSigCreated , '%Y-%m-%dT%H:%M:%SZ') if (self.session['nonce']==decSigNonce): webkey = WebKeyIdentity(public_key=webkey.public_key, private_key=webkey.private_key, creation_date = decSigCreated , payswarm_identity = decOwner , payswarm_key = decPublicKey , payswarm_financial_account = decDestination, is_registered = True, registration_date = registerationDate) webkey.put() #registered = "True" #self.session['registered']=registered self.redirect("/",True)
def get_label(self): package_results = self.accept_result.dict_response['ShipmentAcceptResponse']['ShipmentResults']['PackageResults'] label_list = [] if isinstance(package_results, dict): raw_epl = package_results['LabelImage']['GraphicImage'] label_list.append(a2b_base64(raw_epl)) elif isinstance(package_results, list): for label in package_results: raw_epl = label['LabelImage']['GraphicImage'] label_list.append(a2b_base64(raw_epl)) return label_list
def b64ToBinary(self): for index, lines in enumerate(self.content): self.content[index] = binascii.a2b_base64(lines)
def deserialize_from_string(data): return pickle.loads(binascii.a2b_base64(data.encode('utf-8')))
def a2b_base64(s): try: b = bytearray(binascii.a2b_base64(s)) except Exception as e: raise SyntaxError("base64 error: %s" % e) return b
else: request[ticker] = date.strftime("%Y-%m-%d %H:%M:%S") request["__UNIQUEID__"] = str(appGlobal.getApp().getUniqueId()) try: if status: status.setStatus("Receiving Stock Data", 70) data = self.s.getStockZip(request) except Exception, inst: print "Exception from server: ", inst raise # Try decompressing # Ignore errors (assume not compressed) try: unencoded = binascii.a2b_base64(data) uncompressed = zlib.decompress(unencoded) data = uncompressed except Exception, inst: pass if status: status.setStatus("Updating Stock Database", 80) self.db.beginTransaction() gotData = False for line in data.split("\n"): #print line values = line.split(",") if len(values) < 4: continue
def _read_crypto_key(self): return binascii.a2b_base64(open(self.crypto_key_path).read().strip())
def b64ToHex(self): for index, lines in enumerate(self.content): lines = binascii.a2b_base64(lines) self.content[index] = binascii.b2a_hex(lines)
def importKey(extern_key, passphrase=None, verify_x509_cert=True): """Import a DSA key (public or private). :Parameters: extern_key : (byte) string The DSA key to import. An DSA *public* key can be in any of the following formats: - X.509 certificate (binary or PEM format) - X.509 ``subjectPublicKeyInfo`` (binary or PEM) - OpenSSH (one line of text, see `RFC4253`_) A DSA *private* key can be in any of the following formats: - `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo`` DER SEQUENCE (binary or PEM encoding) - OpenSSL/OpenSSH (binary or PEM) For details about the PEM encoding, see `RFC1421`_/`RFC1423`_. The private key may be encrypted by means of a certain pass phrase either at the PEM level or at the PKCS#8 level. passphrase : string In case of an encrypted private key, this is the pass phrase from which the decryption key is derived. verify_x509_cert : bool When importing the public key from an X.509 certificate, whether the certificate should be validated. **Since verification is not yet supported, this value must always be set to False**. This value is ignored if an X.509 certificate is not passed. :Return: A DSA key object (`DsaKey`). :Raise ValueError: When the given key cannot be parsed (possibly because the pass phrase is wrong). .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt .. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt .. _PKCS#8: http://www.ietf.org/rfc/rfc5208.txt """ extern_key = tobytes(extern_key) if passphrase is not None: passphrase = tobytes(passphrase) if extern_key.startswith(b('-----')): # This is probably a PEM encoded key (der, marker, enc_flag) = PEM.decode(tostr(extern_key), passphrase) if enc_flag: passphrase = None return _importKeyDER(der, passphrase, None, verify_x509_cert) if extern_key.startswith(b('ssh-dss ')): # This is probably a public OpenSSH key keystring = binascii.a2b_base64(extern_key.split(b(' '))[1]) keyparts = [] while len(keystring) > 4: length = struct.unpack(">I", keystring[:4])[0] keyparts.append(keystring[4:4 + length]) keystring = keystring[4 + length:] if keyparts[0] == b("ssh-dss"): tup = [Integer.from_bytes(keyparts[x]) for x in (4, 3, 1, 2)] return construct(tup) if bord(extern_key[0]) == 0x30: # This is probably a DER encoded key return _importKeyDER(extern_key, passphrase, None, verify_x509_cert) raise ValueError("DSA key format is not supported")
def decodebytes(s): """Decode a bytestring of base-64 data into a bytes object.""" _input_type_check(s) return binascii.a2b_base64(s)
def tx_from_b64(h): f = io.BytesIO(binascii.a2b_base64(h.encode("utf8"))) return Tx.parse(f)
# Be slow so we don't depend on other modules testdata = testdata + chr(i) testdata = testdata + "\r\nHello world.\n" # Test base64 with valid data print "base64 test" MAX_BASE64 = 57 lines = [] for i in range(0, len(testdata), MAX_BASE64): b = testdata[i:i + MAX_BASE64] a = binascii.b2a_base64(b) lines.append(a) print a, res = "" for line in lines: b = binascii.a2b_base64(line) res = res + b assert res == testdata # Test base64 with random invalid characters sprinkled throughout # (This requires a new version of binascii.) fillers = "" valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/" for i in range(256): c = chr(i) if c not in valid: fillers = fillers + c def addnoise(line): noise = fillers