def ReplaceCerts(data): """Given a string of data, replace all occurences of a set of X509 certs with a newer set of X509 certs and return the updated data string.""" for old, new in OPTIONS.key_map.iteritems(): try: if OPTIONS.verbose: print " Replacing %s.x509.pem with %s.x509.pem" % (old, new) f = open(old + ".x509.pem") old_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower() f.close() f = open(new + ".x509.pem") new_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower() f.close() # Only match entire certs. pattern = "\\b"+old_cert16+"\\b" (data, num) = re.subn(pattern, new_cert16, data, flags=re.IGNORECASE) if OPTIONS.verbose: print " Replaced %d occurence(s) of %s.x509.pem with " \ "%s.x509.pem" % (num, old, new) except IOError as e: if e.errno == errno.ENOENT and not OPTIONS.verbose: continue print " Error accessing %s. %s. Skip replacing %s.x509.pem " \ "with %s.x509.pem." % (e.filename, e.strerror, old, new) return data
def set_state(self, channel, state, duration=None): """Set state of a channel :param channel: zero-based channel index :param state: new state (on, off, auto, manual) :param duration: how long to keep the new setting (None for indefinite) :type duration: datetime.timedelta """ if duration is None: # set state indefinitely try: state_code = CONTROL_MODES[state] except: raise LantopError("Cannot parse state") args = base64.b16encode(bytes([state_code])) self.tp.command("T04614B", "ak", channel, args) else: # keep new state only for a certain time try: state_code = TIMED_STATE_LABELS[state] except: raise LantopError("Cannot parse state") hours = 24 * duration.days + duration.seconds // 3600 minutes = (duration.seconds // 60) % 60 seconds = duration.seconds % 60 args = (4, hours, minutes, seconds, state_code) args = b''.join((base64.b16encode(bytes([c])) for c in args)) self.tp.command("T08614B", "ak", channel, args)
def _setRelation(self, document, previous_value, organisation_gid, domain, xml): """ Retrieve the organisation from its gid and do the link """ # first check if there is any conflict LOG('Organisation GID %s'%(b16encode(organisation_gid)), 300, "") LOG('Organisation GID %s'%(b16encode(organisation_gid)), 300, "") LOG('Organisation GID %s'%(b16encode(organisation_gid)), 300, "") synchronization_list = self.getSynchronizationObjectListForType(domain, 'Organisation', 'publication') if previous_value is not None and xml is not None: current_relation = document.getCareerSubordinationValue() if current_relation: for synchronization in synchronization_list: current_value = b16decode(synchronization.getGidFromObject(current_relation)) if current_value: break else: current_value = "" if current_value not in [organisation_gid, previous_value]: return [self._generateConflict(document.getPhysicalPath(), 'relation', xml, current_value, organisation_gid),] # now set the value if organisation_gid is None: document.setCareerSubordinationValue(None) else: for synchronization in synchronization_list: link_object = synchronization.getDocumentFromGid(b16encode(organisation_gid)) if link_object is not None: break if link_object is not None: document.setCareerSubordinationValue(link_object) else: raise ValueError, "Impossible to find organisation %s in %s" %(organisation_gid, synchronization_list) document.reindexObject() return []
def test_ReplaceCerts_skipNonExistentCerts(self): cert1_path = os.path.join(self.testdata_dir, 'platform.x509.pem') with open(cert1_path) as cert1_fp: cert1 = cert1_fp.read() cert2_path = os.path.join(self.testdata_dir, 'media.x509.pem') with open(cert2_path) as cert2_fp: cert2 = cert2_fp.read() cert3_path = os.path.join(self.testdata_dir, 'testkey.x509.pem') with open(cert3_path) as cert3_fp: cert3 = cert3_fp.read() input_xml = self.MAC_PERMISSIONS_XML.format( base64.b16encode(common.ParseCertificate(cert1)).lower(), base64.b16encode(common.ParseCertificate(cert2)).lower()) output_xml = self.MAC_PERMISSIONS_XML.format( base64.b16encode(common.ParseCertificate(cert3)).lower(), base64.b16encode(common.ParseCertificate(cert2)).lower()) common.OPTIONS.key_map = { cert1_path[:-9] : cert3_path[:-9], 'non-existent' : cert3_path[:-9], cert2_path[:-9] : 'non-existent', } self.assertEqual(output_xml, ReplaceCerts(input_xml))
def xor(bs1, bs2): n1 = len(bs1) n2 = len(bs2) # no support for differing length inputs at the moment assert n1 == n2 hex_res = hex_xor(b16encode(bs1), b16encode(bs2)) return decode_hex(hex_res)
def b16(): if sys.argv[2] == 'e': print base64.b16encode(sys.argv[3]) elif sys.argv[2] == 'd': print base64.b16decode(sys.argv[3]) else: usage()
def tf_config_cmd(full_cluster_spec, task_spec): task_type = task_spec['type'] task_id = task_spec['index'] print("Task id is %r"%(task_id,)) host = full_cluster_spec[task_type][task_id] # every worker needs its own location sparse_cluster_spec = defaultdict(dict) sparse_cluster_spec[task_type][task_id] = host # worker workers know about all ps workers if task_type == 'worker': sparse_cluster_spec['ps'] = full_cluster_spec['ps'] # ps workers know about all worker workers if task_type == 'ps': pass sparse_cluster_spec['worker'] = full_cluster_spec['worker'] #sparse_cluster_spec['worker'] = {0: full_cluster_spec['worker'][0]} sparse_cluster_config = {'cluster': sparse_cluster_spec, 'task': task_spec} print("Cluster config for %s %s is %s"%(task_type, task_id, sparse_cluster_spec)) json_string = json.dumps(sparse_cluster_config) json_string_encoded = base64.b16encode(json_string.encode('ascii')) json_string_encoded = json_string_encoded.decode('ascii') pickle_string = pickle.dumps(sparse_cluster_config) pickle_string_encoded = base64.b16encode(pickle_string) pickle_string_encoded = pickle_string_encoded.decode('ascii') export_command = "export TF_PICKLE_BASE16=%s"%(pickle_string_encoded,) return export_command
def write(self, data, ip, port): # we need to send responses to the IP/port that sent it. print "Sending message to %s:%d" % (ip, port) print b16encode(data) self.transport.getHandle().sendto(data, (ip, port)) print
def repeating_key_xor(plaintext, key): key_gen = cycle(key) return ''.join( hex_xor(b16encode(char), b16encode(key_char)) for char, key_char in izip(plaintext, key_gen) )
def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode(b'\x01\x02\xab\xcd\xef'), b'0102ABCDEF') eq(base64.b16encode(b'\x00'), b'00') # Non-bytes eq(base64.b16encode(bytearray(b'\x01\x02\xab\xcd\xef')), b'0102ABCDEF') self.assertRaises(TypeError, base64.b16encode, "")
def _safecookie_authchallenge(self, reply): """ Callback on AUTHCHALLENGE SAFECOOKIE """ if self._cookie_data is None: raise RuntimeError("Cookie data not read.") kw = parse_keywords(reply.replace(' ', '\n')) server_hash = base64.b16decode(kw['SERVERHASH']) server_nonce = base64.b16decode(kw['SERVERNONCE']) # FIXME put string in global. or something. expected_server_hash = hmac_sha256( "Tor safe cookie authentication server-to-controller hash", self._cookie_data + self.client_nonce + server_nonce ) if not compare_via_hash(expected_server_hash, server_hash): raise RuntimeError( 'Server hash not expected; wanted "%s" and got "%s".' % (base64.b16encode(expected_server_hash), base64.b16encode(server_hash)) ) client_hash = hmac_sha256( "Tor safe cookie authentication controller-to-server hash", self._cookie_data + self.client_nonce + server_nonce ) client_hash_hex = base64.b16encode(client_hash) return self.queue_command('AUTHENTICATE %s' % client_hash_hex)
def check_openssl(self, cipher_name, keysize, mode): cipher_desc = Descriptor(cipher=cipher_name) for i in range(1, 2): key = os.urandom(keysize // 8) iv = os.urandom(cipher_desc.block_size) pt = os.urandom(i * 128 // 8) if cipher_name == "aes": cipher_spec = "aes-%d-%s" % (keysize, mode) elif cipher_name == "des": cipher_spec = "des-%s" % mode elif cipher_name == "blowfish": cipher_spec = "bf-%s" % mode proc = Popen( ( "openssl enc -e -%s -nopad -nosalt -K %s -iv %s" % (cipher_spec, b16encode(key).decode(), b16encode(iv).decode()) ).split(), stdin=PIPE, stdout=PIPE, stderr=PIPE, ) out, err = proc.communicate(pt) self.assertFalse(err, err) cipher = Cipher(key=key, iv=iv, cipher=cipher_name, mode=mode) ct = cipher.encrypt(pt) self.assertEqual( ct, out, "%s %s %s: %s != %s" % (cipher_name, keysize, mode, b16encode(ct).decode(), b16encode(out).decode()), )
def update(self): account_no=self.read_exactly(8) auth_token_received=self.read_exactly(32) print "c#%i: request to update account_no=%s"%(self.conn_no, base64.b16encode(account_no)) filename=os.path.join(self.server.storage_dir, "%s.spr"%base64.b16encode(account_no)) fd=os.open(filename, os.O_RDWR, 0600) fcntl.lockf(fd, fcntl.LOCK_EX) with os.fdopen(fd, "r+") as f: auth_token_stored=f.read(32) if auth_token_stored!=auth_token_received: raise CommunicationError() btoken_send=f.read() self.sock.write(struct.pack("!L", len(btoken_send))) self.sock.write(btoken_send) print "c#%i: sent btoken of length=%i"%(self.conn_no,len(btoken_send)) len_btoken_recv=struct.unpack("!L", self.read_exactly(4))[0] if len_btoken_recv>self.server.max_btoken_length: raise CommunicationError() btoken_recv=self.read_exactly(len_btoken_recv) print "c#%i: received btoken of length=%i"%(self.conn_no,len_btoken_recv) f.seek(0) f.truncate(0) f.write(auth_token_stored) f.write(btoken_recv) self.sock.write(account_no) print "c#%i: returned existing account_no=%s"%(self.conn_no,base64.b16encode(account_no))
def test_authenticate_safecookie(self): with tempfile.NamedTemporaryFile() as cookietmp: cookiedata = bytes(bytearray([0] * 32)) cookietmp.write(cookiedata) cookietmp.flush() self.protocol._do_authenticate('''PROTOCOLINFO 1 AUTH METHODS=SAFECOOKIE COOKIEFILE="{}" VERSION Tor="0.2.2.35" OK'''.format(cookietmp.name)) self.assertTrue( b'AUTHCHALLENGE SAFECOOKIE ' in self.transport.value() ) x = self.transport.value().split()[-1] client_nonce = a2b_hex(x) self.transport.clear() server_nonce = bytes(bytearray([0] * 32)) server_hash = hmac_sha256( b"Tor safe cookie authentication server-to-controller hash", cookiedata + client_nonce + server_nonce, ) self.send( b'250 AUTHCHALLENGE SERVERHASH=' + base64.b16encode(server_hash) + b' SERVERNONCE=' + base64.b16encode(server_nonce) + b'\r\n' ) self.assertTrue(b'AUTHENTICATE ' in self.transport.value())
def test_authenticate_safecookie(self): with tempfile.NamedTemporaryFile() as cookietmp: cookiedata = str(bytearray([0] * 32)) cookietmp.write(cookiedata) cookietmp.flush() self.protocol._do_authenticate('''PROTOCOLINFO 1 AUTH METHODS=SAFECOOKIE COOKIEFILE="%s" VERSION Tor="0.2.2.35" OK''' % cookietmp.name) self.assertTrue( 'AUTHCHALLENGE SAFECOOKIE ' in self.transport.value() ) client_nonce = base64.b16decode(self.transport.value().split()[-1]) self.transport.clear() server_nonce = str(bytearray([0] * 32)) server_hash = hmac_sha256( "Tor safe cookie authentication server-to-controller hash", cookiedata + client_nonce + server_nonce ) self.send( '250 AUTHCHALLENGE SERVERHASH=%s SERVERNONCE=%s' % (base64.b16encode(server_hash), base64.b16encode(server_nonce)) ) self.assertTrue('AUTHENTICATE ' in self.transport.value())
def run_aes_cbc_encrypt_nopad_nist_test(testvectors, test_num): key = testvectors.key blocksize = A.BLOCKSIZE iv, vector, ciphertext = testvectors.vectors[test_num] result = A.aes_cbc_encrypt(key, vector, iv=iv, pad=False) result_iv, result_ciphertext = result[:blocksize], result[blocksize:] assert b16encode(result_iv) == iv assert b16encode(result_ciphertext) == ciphertext
def escape(s): try: s = b16encode(bytes(s, encoding='utf-8')).decode(encoding='utf-8') except TypeError: s = b16encode(s) for i in range(10): s = s.replace(chr(ord('0') + i), chr(ord('a') + i)) return s
def main(): ctx = krb5.Context() sprinc = ctx.build_principal(srealm, sname) print 'getting tickets for %s' % sprinc.unparse_name() cc = ctx.cc_default() creds = cc.get_credentials(cc.get_principal(), sprinc) print base64.b16encode(creds._handle.contents.ticket.as_str()) print base64.urlsafe_b64encode(creds._handle.contents.ticket.as_str()).strip('=')
def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode(b'\x01\x02\xab\xcd\xef'), b'0102ABCDEF') eq(base64.b16encode(b'\x00'), b'00') # Non-bytes self.check_other_types(base64.b16encode, b'\x01\x02\xab\xcd\xef', b'0102ABCDEF') self.check_encode_type_errors(base64.b16encode)
def test_aes_ctr_incr0(): bs = map(chr, [0, 0, 0, 0, 0, 0, 0, 1]) n = 1 assert n == B.bytes_to_int(bs) ctr = ''.join(bs) assert b16encode(ctr) == '0000000000000001' ctr2 = A.aes_ctr_incr(ctr) assert b16encode(ctr2) == '0000000000000002' assert B.bytes_to_int(ctr2) == n + 1
def main(all_args): boxes = [] output_format = None parser = _create_argument_parser() if not all_args: parser.print_help() sys.exit(1) arg_groups = _split_list_on(all_args, '--') for args in arg_groups: ns = parser.parse_args(args) if ns.format: if output_format: raise Exception('Can only specify one of: --base64, --hex, --human') else: output_format = ns.format if ns.input: boxes.extend(_parse_boxes(ns.input)) pssh_data = ns.pssh_data if pssh_data and ns.content_id: raise Exception('Cannot specify both --pssh-data and --content-id') if ns.protection_scheme: if ns.system_id != WIDEVINE_SYSTEM_ID: raise Exception( '--protection-scheme only valid with Widevine system ID') if ns.content_id: if ns.system_id != WIDEVINE_SYSTEM_ID: raise Exception('--content-id only valid with Widevine system ID') # Ignore if we have no data. if not pssh_data and not ns.key_id and not ns.system_id: continue if not ns.system_id: raise Exception('System ID is required') if ns.system_id == WIDEVINE_SYSTEM_ID: # Always generate version 0 for Widevine for backward compatibility. version = 0 if not pssh_data: if not ns.key_id and not ns.content_id: raise Exception('Widevine system needs key-id or content-id or both') pssh_data = _generate_widevine_data(ns.key_id, ns.content_id, ns.provider, ns.protection_scheme) else: version = 1 if ns.key_id else 0 boxes.append(Pssh(version, ns.system_id, ns.key_id, pssh_data)) if output_format == 'human' or not output_format: for box in boxes: print box.human_string() else: box_data = ''.join([x.binary_string() for x in boxes]) if output_format == 'hex': print base64.b16encode(box_data) else: print base64.b64encode(box_data)
def hexdigest(self, data=None): """ Returns digest in the hexadecimal form. For compatibility with hashlib """ from base64 import b16encode if pyver == 2: return b16encode(self.digest(data)) else: return b16encode(self.digest(data)).decode('us-ascii')
def _serializar_url_qrcode(self, nota_fiscal, tag_raiz='infNFeSupl', retorna_string=True): raiz = etree.Element(tag_raiz) data = base64.b16encode(nota_fiscal.data_emissao.isoformat()).decode() digest = base64.b16encode(digest).decode() try: cpf = nota_fiscal.emitente.numero_documento except: cpf = None if cpf is None: url = 'chNFe={}&nVersao={}&tpAmb={}&dhEmi={}&vNF={}&vICMS={}&digVal={}&cIdToken={}'.format( nota_fiscal.nota_fiscal.identificador_unico.replace('NFe', ''), VERSAO_QRCODE, self._ambiente, data.lower(), nota_fiscal.valor_total_nota, nota_fiscal.valor_icms, digest.lower(), nota_fiscal.emitente.token) else: url = 'chNFe={}&nVersao={}&tpAmb={}&cDest={}&dhEmi={}&vNF={}&vICMS={}&digVal={}&cIdToken={}'.format( nota_fiscal.nota_fiscal.identificador_unico.replace('NFe', ''), VERSAO_QRCODE, self._ambiente, cpf, data.lower(), nota_fiscal.totais_icms_total_nota, nota_fiscal.totais_icms_total, digest.lower(), nota_fiscal.emitente.token) url_hash = hashlib.sha1(url.encode()+nota_fiscal.emitente.csc.encode()).digest() url_hash = base64.b16encode(url_hash).decode() url = url + '&cHashQRCode=' + url_hash.upper() if nota_fiscal.uf.upper() == 'PR': url_qrcode = NFCE[nota_fiscal.uf.upper()]['QR'] + url else: if self._homologacao: url_qrcode = NFCE[nota_fiscal.uf.upper()]['HOMOLOGACAO'] +\ NFCE[nota_fiscal.uf.upper()]['QR'] + url else: url_qrcode = NFCE[nota_fiscal.uf.upper()]['HTTPS'] +\ NFCE[nota_fiscal.uf.upper()]['QR'] + url print url_qrcode etree.SubElement(raiz, 'qrCode').text = "<![CDATA[%s]]>" % (url_qrcode) if retorna_string: return etree.tostring(raiz, encoding="unicode", pretty_print=True) else: return raiz
def run_aes_cbc_decrypt_noraw_nist_test(testvectors, n): key = testvectors.key blocksize = 16 iv, vector, ciphertext = testvectors.vectors[n] padding = b16encode(enc_aes_cbc_padding_block(key, ciphertext)) data = iv + ciphertext + padding result = A.aes_cbc_decrypt(key, data, raw=False) assert len(result) == blocksize assert result == b16decode(vector, True) assert b16encode(result) == vector
def run_aes_ctr_encrypt_nist_test(testvectors, test_num): key, nonce = testvectors.key, testvectors.nonce keybytes, noncebytes = b16decode(key, True), b16decode(nonce, True) assert len(keybytes) in A.KEYSIZES assert len(noncebytes) == A.BLOCKSIZE nonce = incrhack(nonce, test_num) vector, ciphertext = testvectors.vectors[test_num] result = A.aes_ctr_encrypt(key, vector, nonce_ctr=nonce) assert len(b16encode(result)) == len(vector) assert b16encode(result).lower() == ciphertext.lower() assert result == b16decode(ciphertext, True)
def test_authenticate_cookie_without_reading(self): server_nonce = bytes(bytearray([0] * 32)) server_hash = bytes(bytearray([0] * 32)) try: self.protocol._safecookie_authchallenge( '250 AUTHCHALLENGE SERVERHASH=%s SERVERNONCE=%s' % (base64.b16encode(server_hash), base64.b16encode(server_nonce)) ) self.assertTrue(False) except RuntimeError as e: self.assertTrue('not read' in str(e))
def gerar_qrcode(self, token, csc, xml, uf, homologacao=False): """ Classe para gerar url do qrcode da NFC-e """ try: # Procura atributos no xml ns = {'ns': 'http://www.portalfiscal.inf.br/nfe'} sig = {'sig': 'http://www.w3.org/2000/09/xmldsig#'} # Tag Raiz NFe Ex: <NFe> nfe = xml[0] chave = nfe[0].attrib['Id'].replace('NFe', '') data = nfe.xpath( 'ns:infNFe/ns:ide/ns:dhEmi/text()', namespaces=ns)[0].encode() tpamb = nfe.xpath('ns:infNFe/ns:ide/ns:tpAmb/text()', namespaces=ns)[0] # tenta encontrar a tag cpf try: cpf = nfe.xpath('ns:infNFe/ns:dest/ns:CPF/text()', namespaces=ns)[0] except IndexError: # em caso de erro tenta procurar a tag cnpj try: cpf = nfe.xpath('ns:infNFe/ns:dest/ns:CNPJ/text()', namespaces=ns)[0] except IndexError: cpf = None cpf = None total = nfe.xpath( 'ns:infNFe/ns:total/ns:ICMSTot/ns:vNF/text()', namespaces=ns)[0] icms = nfe.xpath( 'ns:infNFe/ns:total/ns:ICMSTot/ns:vICMS/text()', namespaces=ns)[0] digest = nfe.xpath( 'sig:Signature/sig:SignedInfo/sig:Reference/sig:DigestValue/text()', namespaces=sig)[0].encode() data = base64.b16encode(data).decode() digest = base64.b16encode(digest).decode() if cpf is None: url = 'chNFe={}&nVersao={}&tpAmb={}&dhEmi={}&vNF={}&vICMS={}&digVal={}&cIdToken={}'.format( chave, VERSAO_QRCODE, tpamb, data.lower(), total, icms, digest.lower(), token) else: url = 'chNFe={}&nVersao={}&tpAmb={}&cDest={}&dhEmi={}&vNF={}&vICMS={}&digVal={}&cIdToken={}'.format( chave, VERSAO_QRCODE, tpamb, cpf, data.lower(), total, icms, digest.lower(), token) url_hash = hashlib.sha1(url.encode() + csc.encode()).digest() url_hash = base64.b16encode(url_hash).decode() url = url + '&cHashQRCode=' + url_hash.upper() if uf.upper() == 'PR': return NFCE[uf.upper()]['QR'] + url else: if homologacao: return NFCE[uf.upper()]['HOMOLOGACAO'] + NFCE[uf.upper()]['QR'] + url else: return NFCE[uf.upper()]['HTTPS'] + NFCE[uf.upper()]['QR'] + url except Exception as e: raise e
def printDupTable(DupTable, sortKey=2): groupID = 1 for [key, paths, size] in sorted(DupTable, key=lambda record: record[sortKey]): print "Group %d (%d b):" % (groupID, size) print base64.b16encode(key).lower() for path in paths: print "%s" % path if (os.path.getsize(path) != size): print "Files not all the same size: %d" % os.path.getsize(path) #raise NameError ("Something wrong with hash algorithm: files not all the same size") groupID += 1 print ""
def load_body_file(self, sequence_id, index): header, body, container = self.containers[index] container.seek(0) logging.debug("Container %d file has size %d" % (index, len(container.getvalue()))) hs, bs = self.container_sizes[index] logging.debug("Container %d file has header %s" % (index, base64.b16encode(container.getvalue()[:hs]))) logging.debug("Container %d file has body %s" % (index, base64.b16encode(container.getvalue()[hs:]))) assert hs + bs == len(container.getvalue()) return container
def ReplaceCerts(data): """Replaces all the occurences of X.509 certs with the new ones. The mapping info is read from OPTIONS.key_map. Non-existent certificate will be skipped. After the replacement, it additionally checks for duplicate entries, which would otherwise fail the policy loading code in frameworks/base/services/core/java/com/android/server/pm/SELinuxMMAC.java. Args: data: Input string that contains a set of X.509 certs. Returns: A string after the replacement. Raises: AssertionError: On finding duplicate entries. """ for old, new in OPTIONS.key_map.iteritems(): if OPTIONS.verbose: print(" Replacing %s.x509.pem with %s.x509.pem" % (old, new)) try: with open(old + ".x509.pem") as old_fp: old_cert16 = base64.b16encode( common.ParseCertificate(old_fp.read())).lower() with open(new + ".x509.pem") as new_fp: new_cert16 = base64.b16encode( common.ParseCertificate(new_fp.read())).lower() except IOError as e: if OPTIONS.verbose or e.errno != errno.ENOENT: print(" Error accessing %s: %s.\nSkip replacing %s.x509.pem with " "%s.x509.pem." % (e.filename, e.strerror, old, new)) continue # Only match entire certs. pattern = "\\b" + old_cert16 + "\\b" (data, num) = re.subn(pattern, new_cert16, data, flags=re.IGNORECASE) if OPTIONS.verbose: print(" Replaced %d occurence(s) of %s.x509.pem with %s.x509.pem" % ( num, old, new)) # Verify that there're no duplicate entries after the replacement. Note that # it's only checking entries with global seinfo at the moment (i.e. ignoring # the ones with inner packages). (Bug: 69479366) root = ElementTree.fromstring(data) signatures = [signer.attrib['signature'] for signer in root.findall('signer')] assert len(signatures) == len(set(signatures)), \ "Found duplicate entries after cert replacement: {}".format(data) return data
def get_share_id(self): return b16encode( ('{}.{}'.format(self.project_id, self.id)).encode('utf-8')).lower().decode('utf-8')
def num2str(num): tmp = hex(num)[2:].replace("L", "") if len(tmp) % 2 == 0: return tmp.decode("hex") else: return ("0" + tmp).decode("hex") print num2str(584734024210391580014049650557280915516226103165) from Crypto.Util.number import long_to_bytes, bytes_to_long flag = "flag{123}" print bytes_to_long(flag) print long_to_bytes(bytes_to_long(flag)) import urllib print urllib.quote("flag{url_encode_1234_!@#$}") d = {'name': '*****@*****.**', 'flag': 'flag{url_encode_1234_!@#$}'} print urllib.urlencode(d) import base64 print "flag".encode("base64") print base64.b16encode("flag") print base64.b32encode("flag") print base64.b64encode("flag") print "ZmxhZw==".decode("base64") print base64.b16decode("666C6167") print base64.b32decode("MZWGCZY=") print base64.b64decode("ZmxhZw==")
def b64_to_b16(b64): #if type(b64) == str: # b64 = b64.encode() return base64.b16encode(decode_base64(b64)).decode()
for c in s: result = result * 16 + b16[c] return result def base256encode(n): return chr(n) result = '' while n > 0: n = int(n) result = chr(n % 256) + result n /= 256 return result bytechars = {} for line in sys.stdin: line = line.strip().split( ' ') #.split() #bytes(line.strip(), encoding="utf-8") for tokens in line: tokens = str(tokens) if tokens in protectList: output.write(tokens) output.write(" ") continue tk = (str(base64.b16encode(tokens.encode("utf-8")))[2:-1]) output.write(tk) output.write(" ") output.write("\n")
def createFromColorMap(self, colormap): if "clrs" not in sys.modules: import plotly.colors as clrs colors = [] colorscale = [] luma = [] if colormap != None and len(colormap) > 0: if colormap.find("sas_") == 0: if colormap in Colors._sasThemes: colors.extend(Colors._sasThemes[colormap]) elif colormap in clrs.PLOTLY_SCALES: cmap = clrs.PLOTLY_SCALES[colormap] interval = 1 / (len(cmap) - 1) index = 0 for i, c in enumerate(cmap): s = c[1] if s[0] == '#': colors.append(s) else: i1 = s.index("(") i2 = s.index(")") s = s[i1 + 1:i2] colorscale.append([index, "rgb(" + s + ")"]) a = s.split(",") r = int(a[0]) g = int(a[1]) b = int(a[2]) value = (r, g, b) luma.append(0.2126 * r + 0.7152 * g + 0.0722 * b) s = "#" + b16encode(bytes(value)).decode() colors.append(s) if i == (len(cmap) - 2): index = 1 else: index += interval else: try: cmap = matplotlib.cm.get_cmap(colormap) norm = matplotlib.colors.Normalize(vmin=0, vmax=255) rgb = [] for i in range(0, 255): k = matplotlib.colors.colorConverter.to_rgb( cmap(norm(i))) rgb.append(k) entries = 255 h = 1.0 / (entries - 1) prev = None a = [] for i in range(entries): c = list(map(np.uint8, np.array(cmap(i * h)[:3]) * 255)) value = (c[0], c[1], c[2]) if value == prev: continue luma.append(0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]) prev = value a.append([ "#" + b16encode(bytes(value)).decode(), "rgb(" + str(c[0]) + "," + str(c[1]) + "," + str(c[2]) + ")" ]) if len(a) > 1: interval = 1 / (len(a) - 1) index = 0 for i, x in enumerate(a): colors.append(x[0]) colorscale.append([index, x[1]]) if i == (len(a) - 2): index = 1 else: index += interval except: pass if len(colors) == 0: interval = 1 / (len(clrs.DEFAULT_PLOTLY_COLORS) - 1) index = 0 for i, c in enumerate(clrs.DEFAULT_PLOTLY_COLORS): i1 = c.index("(") i2 = c.index(")") s = c[i1 + 1:i2] colorscale.append([index, "rgb(" + s + ")"]) a = s.split(",") r = int(a[0]) g = int(a[1]) b = int(a[2]) luma.append(0.2126 * r + 0.7152 * g + 0.0722 * b) value = (r, g, b) colors.append("#" + b16encode(bytes(value)).decode()) if i == (len(clrs.DEFAULT_PLOTLY_COLORS) - 2): index = 1 else: index += interval elif len(colorscale) == 0: interval = 1 / (len(colors) - 1) index = 0 for i, c in enumerate(colors): r = int(c[1:3], 16) g = int(c[3:5], 16) b = int(c[5:7], 16) colorscale.append([ index, "rgb(" + str(r) + "," + str(g) + "," + str(b) + ")" ]) luma.append(0.2126 * r + 0.7152 * g + 0.0722 * b) if i == (len(colors) - 2): index = 1 else: index += interval self._colors = colors self._colorscale = colorscale self._luma = luma
def CreateKey(): return base64.b16encode(uuid.uuid1().bytes).lower()
def generate_random_token(length): # type: (int) -> text_type return base64.b16encode(os.urandom(length // 2)).decode('utf-8').lower()
def get_symkey(link): md5 = hashlib.md5() md5.update(link.encode("utf-8")) return base64.b16encode(md5.digest()).decode("utf-8")
def downloadResult(self, result): """ Save the result to disk. """ # check for auth if not self._doLogin(): return False if self.providerType == GenericProvider.TORRENT: try: torrent_hash = re.findall('urn:btih:([\w]{32,40})', result.url)[0].upper() if len(torrent_hash) == 32: torrent_hash = b16encode(b32decode(torrent_hash)).lower() if not torrent_hash: logger.log( "Unable to extract torrent hash from link: " + ex(result.url), logger.ERROR) return False urls = [ 'http://torcache.net/torrent/' + torrent_hash + '.torrent', 'http://torrage.com/torrent/' + torrent_hash + '.torrent', 'http://zoink.it/torrent/' + torrent_hash + '.torrent', ] except: urls = [result.url] filename = ek.ek( os.path.join, sickbeard.TORRENT_DIR, helpers.sanitizeFileName(result.name) + '.' + self.providerType) elif self.providerType == GenericProvider.NZB: urls = [result.url] filename = ek.ek( os.path.join, sickbeard.NZB_DIR, helpers.sanitizeFileName(result.name) + '.' + self.providerType) else: return for url in urls: if helpers.download_file(url, filename, session=self.session): logger.log(u"Downloading a result from " + self.name + " at " + url) if self.providerType == GenericProvider.TORRENT: logger.log(u"Saved magnet link to " + filename, logger.INFO) else: logger.log(u"Saved result to " + filename, logger.INFO) if self._verify_download(filename): return True logger.log(u"Failed to download result", logger.ERROR) return False
def encrypt(): cipher = AES.new(base64.b16decode(key, casefold=True), AES.MODE_ECB) return base64.b16encode(cipher.encrypt(flag))
def test_b16encode(self): eq = self.assertEqual eq(base64.b16encode('\x01\x02\xab\xcd\xef'), '0102ABCDEF') eq(base64.b16encode('\x00'), '00')
def get_node_tls_cn(node_id_raw: bytes) -> str: return base64.b16encode(node_id_raw).decode('ascii').lower()
def main(): print('''选择编码方式: 1. Base64 2. 凯撒密码 3. Url编码 4. LMhash 5. NTLMhash 6. Hex 7. Unicode 8. Base32 9. Base16''') a = input('请选择: ') if a == '1': print('''Base64 1. 编码 2. 解码''') b = input('请选择: ') if b == '1': base64encode() elif b == '2': base64decode() else: print('您的输入有误!') if a == '2': print('''凯撒密码 1. 加密 2. 解密''') b = input('请选择:') if b == '1': kaisaencode() elif b == '2': kaisadecode() else: print('您的输入有误!') if a == '3': print('''Url解码、编码 1. 编码 2. 解码''') b = input('请选择: ') if b == '1': urlencode() elif b == '2': urldecode() else: print('您的输入有误!') if a == '4': passwd = input('''LMhash 输入带加密字符: ''') print('你的输入是:', passwd) print('转化为大写:', passwd.upper()) # 用户的密码转换为大写,并转换为16进制字符串 passwd = codecs.encode(passwd.upper().encode(), 'hex_codec') print('转为hex:', passwd.decode()) # 密码不足28位,用0在右边补全 passwd_len = len(passwd) if passwd_len < 28: passwd = passwd.decode().ljust(28, '0') print('补齐28位:', passwd) # 28位的密码被分成两个14位部分 PartOne = passwd[0:14] PartTwo = passwd[14:] print('两组14位的部分:', PartOne, PartTwo) # 每部分分别转换成比特流,并且长度为56位,长度不足用0在左边补齐长度 PartOne = bin(int(PartOne, 16)).lstrip('0b').rjust(56, '0') PartTwo = bin(int(PartTwo, 16)).lstrip('0b').rjust(56, '0') print('两组56位比特流:', PartOne, PartTwo) # 两组分别再分为7位一组末尾加0,再分别组合成新的字符 PartOne = ZeroPadding(PartOne) PartTwo = ZeroPadding(PartTwo) print('两组再7位一组末尾加0:', PartOne, PartTwo) # 两组数据转hex PartOne = hex(int(PartOne, 2))[2:] PartTwo = hex(int(PartTwo, 2))[2:] if '0' == PartTwo: PartTwo = "0000000000000000" print('两组转为hex:', PartOne, PartTwo) # 16位的二组数据,分别作为DES key为"KGS!@#$%"进行加密。 LMOne = DesEncrypt("KGS!@#$%", binascii.a2b_hex(PartOne)).decode() LMTwo = DesEncrypt("KGS!@#$%", binascii.a2b_hex(PartTwo)).decode() print('两组DES加密结果:', LMOne, LMTwo) # 将二组DES加密后的编码拼接,得到LM HASH值。 LM = LMOne + LMTwo print('LM hash:', LM) if a == '5': passwd = input('''NTLMhash 输入带加密字符: ''') os.system( '''python2 -c "import hashlib,binascii; print binascii.hexlify(hashlib.new('md4', '{}'.encode('utf-16le')).digest())"'''.format( passwd)) if a == '6': print('''Hex 1. hex转字符串 2. 字符串转hex''') b = input('请选择: ') if b == '1': code = input('输入hex: ') print(bytes.fromhex(code).decode()) if b == '2': code = input('输入字符串: ') print(code.encode().hex()) if a == '7': print('''Unicode 1. Unicode转中文 2. 中文转Unicode''') b = input('请选择: ') if b == '1': code = input('请输入Unicode字符: ') print(code.encode('utf-8').decode("unicode_escape")) if b == '2': code = input('请输入中文: ') print(code.encode("unicode_escape").decode()) if a == '8': print('''Base32 1. 编码 2. 解码''') b = input('请选择: ') if b == '1': code = input('请输入:') code = bytes(code, encoding="utf8") print(base64.b32encode(code).decode()) if b == '2': code = input('请输入:') code = bytes(code, encoding="utf8") print(base64.b32decode(code).decode()) if a == '9': print('''Base16 1. 编码 2. 解码''') b = input('请输入:') if b == '1': code = input('请输入:') code = bytes(code, encoding="utf8") print(base64.b16encode(code).decode()) if b == '2': code = input('请输入:') code = bytes(code, encoding="utf8") print(base64.b16decode(code).decode())
def md2(outputformat, importx, inputformat, raw, infilepath, outfilepath): if importx == 'file': f = open(infilepath, 'r') raw = f.read() f.close() elif importx == 'print': raw = raw else: print('\033[1;31m[-]\033[0m Unknown error.') return False inp = raw if inputformat == 'base64': iput = base64.b64decode(inp) elif inputformat == 'raw': iput = inp elif inputformat == 'base32': iput = base64.b32decode(inp) elif inputformat == 'base16': iput = base64.b16decode(inp) elif inputformat == 'base58': iput = base58.b58decode(inp) elif inputformat == 'base85': print('\033[1;31m[-]\033[0m Option not available yet') elif inputformat == 'hex': iput = inp.decode('hex') elif inputformat == 'dec': print('\033[1;31m[-]\033[0m Option not available yet') elif inputformat == 'octal': print('\033[1;31m[-]\033[0m Option not available yet') elif inputformat == 'binary': iput = text_from_bits(inp) else: print('\033[1;31m[-]\033[0m Unknown error.') return False md2hasher.update(iput) out = md2hasher.digest() if outputformat == 'base64': output = base64.b64encode(out) elif outputformat == 'raw': output = out elif outputformat == 'base32': output = base64.b32encode(out) elif outputformat == 'base16': output = base64.b16encode(out) elif outputformat == 'base58': output = base58.b58encode(out) elif outputformat == 'base85': print('\033[1;31m[-]\033[0m Option not available yet') elif outputformat == 'hex': output = out.encode('hex') elif outputformat == 'dec': print('\033[1;31m[-]\033[0m Option not available yet') elif outputformat == 'octal': print('\033[1;31m[-]\033[0m Option not available yet') elif outputformat == 'binary': output = text_to_bits(out) else: print('\033[1;31m[-]\033[0m Unknown error.') return False if importx == 'file': filename = open(outfilepath, 'w') filename.write(output) filename.close() return True elif importx == 'print': return output else: print('\033[1;31m[-]\033[0m Unknown error.') return False
assert iterations > 0 if not digest: digest = hashlib.sha1 password = b'' + password salt = b'' + salt hlen = digest().digest_size if not dklen: dklen = hlen if dklen > (2**32 - 1) * hlen: raise OverflowError('dklen too big') l = -(-dklen // hlen) r = dklen - (l - 1) * hlen hex_format_string = "%%0%ix" % (hlen * 2) def F(i): def U(): u = salt + struct.pack(b'>I', i) for j in range(int(iterations)): u = _fast_hmac(password, u, digest).digest() yield _bin_to_long(u) return _long_to_bin(reduce(operator.xor, U()), hex_format_string) T = [F(x) for x in range(1, l + 1)] return b''.join(T[:-1]) + T[-1][:r] pbkdf2 = lambda text, salt, iterations, dklen: base64.b16encode( _pbkdf2(text.encode('utf-8'), salt, iterations, dklen)).lower()
def b16encode(s): return bytesToString(base64.b16encode(stringToBytes(s)))
def _getSSHPublicKeyFingerprint(self, key): sshkey = self._getSSHPublicKeyRaw(key) md5 = EVP.MessageDigest('md5') md5.update(sshkey['blob']) return re.sub(r'(..)', r':\1', base64.b16encode(md5.digest()))[1:]
def download(self, data = None, media = None, filedata = None): """ Send a torrent/nzb file to the downloader :param data: dict returned from provider Contains the release information :param media: media dict with information Used for creating the filename when possible :param filedata: downloaded torrent/nzb filedata The file gets downloaded in the searcher and send to this function This is done to have failed checking before using the downloader, so the downloader doesn't need to worry about that :return: boolean One faile returns false, but the downloaded should log his own errors """ if not media: media = {} if not data: data = {} log.debug('Sending "%s" to rTorrent.', (data.get('name'))) if not self.connect(): return False torrent_params = {} if self.conf('label'): torrent_params['label'] = self.conf('label') if not filedata and data.get('protocol') == 'torrent': log.error('Failed sending torrent, no data') return False # Try download magnet torrents if data.get('protocol') == 'torrent_magnet': filedata = self.magnetToTorrent(data.get('url')) if filedata is False: return False data['protocol'] = 'torrent' info = bdecode(filedata)["info"] torrent_hash = sha1(bencode(info)).hexdigest().upper() # Convert base 32 to hex if len(torrent_hash) == 32: torrent_hash = b16encode(b32decode(torrent_hash)) # Send request to rTorrent try: # Send torrent to rTorrent torrent = self.rt.load_torrent(filedata, verify_retries=10) if not torrent: log.error('Unable to find the torrent, did it fail to load?') return False # Set label if self.conf('label'): torrent.set_custom(1, self.conf('label')) if self.conf('directory'): torrent.set_directory(self.conf('directory')) # Start torrent if not self.conf('paused', default = 0): torrent.start() return self.downloadReturnId(torrent_hash) except Exception as err: log.error('Failed to send torrent to rTorrent: %s', err) return False
def get_miner_address(): pk = crypto_key_gen.from_public_pem('./keys/public.pem') pk_hex = base64.b16encode(pk.to_string()).decode('utf-8') return pk_hex
def writeHash(password, salt): hashes = {} hashes[password] = "Plain-text" hashes[urllib.quote(password, safe='')] = "URL Encoded" hashes[password.encode("hex")] = "Hex" hashes[base64.b16encode(password)] = "Base16" hashes[base64.b32encode(password)] = "Base32" hashes[base64.b64encode(password)] = "Base64" hashes[base64.b64encode(salt + ":" + password)] = "Basic Auth" hashes[base64.b64encode(MD5.new(password).digest())] = "md5" hashes[base64.b64encode(MD5.new(password + salt).digest())] = "md5+salt" hashes[base64.b64encode(MD5.new(salt + password).digest())] = "salt+md5" hashes[base64.b64encode(HMAC.new( password, salt, SHA).digest())] = "hmac-sha1; key=password" hashes[base64.b64encode(HMAC.new(salt, password, SHA).digest())] = "hmac-sha1; key=salt" hashes[base64.b64encode(HMAC.new( password, salt, SHA256).digest())] = "hmac-sha256; key=password" hashes[base64.b64encode(HMAC.new( salt, password, SHA256).digest())] = "hmac-sha256; key=salt" hashes[base64.b64encode(HMAC.new( password, salt, SHA512).digest())] = "hmac-sha512; key=password" hashes[base64.b64encode(HMAC.new( salt, password, SHA512).digest())] = "hmac-sha512; key=salt" hashes[base64.b64encode(SHA.new(password).digest())] = "sha1" hashes[base64.b64encode(SHA224.new(password).digest())] = "sha224" hashes[base64.b64encode(SHA256.new(password).digest())] = "sha256" hashes[base64.b64encode(SHA512.new(password).digest())] = "sha512" hashes[base64.b64encode(SHA.new(password + salt).digest())] = "sha1+salt" hashes[base64.b64encode(SHA224.new(password + salt).digest())] = "sha224+salt" hashes[base64.b64encode(SHA256.new(password + salt).digest())] = "sha256+salt" hashes[base64.b64encode(SHA512.new(password + salt).digest())] = "sha512+salt" hashes[base64.b64encode(SHA.new(salt + password).digest())] = "salt+sha1" hashes[base64.b64encode(SHA224.new(salt + password).digest())] = "salt+sha224" hashes[base64.b64encode(SHA256.new(salt + password).digest())] = "salt+sha256" hashes[base64.b64encode(SHA512.new(salt + password).digest())] = "salt+sha512" hashes[base64.b64encode(MD4.new(password).digest())] = "md4" hashes[MD5.new(password).hexdigest()] = "md5" hashes[MD5.new(password + salt).hexdigest()] = "md5+salt" hashes[MD5.new(salt + password).hexdigest()] = "salt+md5" hashes[HMAC.new(password, salt, SHA).hexdigest()] = "hmac-sha1; key=password" hashes[HMAC.new(salt, password, SHA).hexdigest()] = "hmac-sha1; key=salt" hashes[HMAC.new(password, salt, SHA256).hexdigest()] = "hmac-sha256; key=password" hashes[HMAC.new(salt, password, SHA256).hexdigest()] = "hmac-sha256; key=salt" hashes[HMAC.new(password, salt, SHA512).hexdigest()] = "hmac-sha512; key=password" hashes[HMAC.new(salt, password, SHA512).hexdigest()] = "hmac-sha512; key=salt" hashes[SHA.new(password).hexdigest()] = "sha1" hashes[SHA224.new(password).hexdigest()] = "sha224" hashes[SHA256.new(password).hexdigest()] = "sha256" hashes[SHA512.new(password).hexdigest()] = "sha512" hashes[SHA.new(password + salt).hexdigest()] = "sha1+salt" hashes[SHA224.new(password + salt).hexdigest()] = "sha224+salt" hashes[SHA256.new(password + salt).hexdigest()] = "sha256+salt" hashes[SHA512.new(password + salt).hexdigest()] = "sha512+salt" hashes[SHA.new(salt + password).hexdigest()] = "salt+sha1" hashes[SHA224.new(salt + password).hexdigest()] = "salt+sha224" hashes[SHA256.new(salt + password).hexdigest()] = "salt+sha256" hashes[SHA512.new(salt + password).hexdigest()] = "salt+sha512" hashes[MD4.new(password).hexdigest()] = "md4" hashes[passlib.hash.mysql323.hash(password)] = "mysql323" hashes[passlib.hash.mysql41.hash(password)] = "mysql41" hashes[passlib.hash.mssql2005.hash(password).split("x")[1]] = "mssql2005" hashes[passlib.hash.mssql2000.hash(password).split("x")[1]] = "mssql2000" hashes[passlib.hash.md5_crypt.hash(password)] = "md5crypt (unix)" hashes[passlib.hash.nthash.hash(password)] = "nt" return hashes
def generate_unauthed_file_access_url(path_id: str) -> str: signed_data = TimestampSigner(salt=LOCAL_FILE_ACCESS_TOKEN_SALT).sign(path_id) token = base64.b16encode(signed_data.encode('utf-8')).decode('utf-8') filename = path_id.split('/')[-1] return reverse('zerver.views.upload.serve_local_file_unauthed', args=[token, filename])
def hex(self): if not self._hex: self._hex = base64.b16encode(self._bin) return self._hex
def main(): os.system("clear") print('''\033[1;31m __ __ __ __ __ __ __ __ __ /__\ |__|__|__|__|__|__|__|__|__| \/ | | | | | \__/ | | | | |_| |_| \033[1;36m[\033[1;35m01\033[1;36m] \033[1;35mBase64 encoding \033[1;36m[\033[1;35m02\033[1;36m] \033[1;35mGenerate MD5 Hash \033[1;36m[\033[1;35m03\033[1;36m] \033[1;35mGenerate MD4 Hash \033[1;36m[\033[1;35m04\033[1;36m] \033[1;35mBase16 encoding \033[1;36m[\033[1;35m05\033[1;36m] \033[1;35mBack/Credits ''') op = input("\033[1;93m>\033[1;92m>\033[1;36m>\033[1;34m ") if op == '01' or op == '1': os.system("clear") print('''\033[1;93m ██████╗ █████╗ ███████╗███████╗ ██████╗ ██╗ ██╗ ██╔══██╗██╔══██╗██╔════╝██╔════╝ ██╔════╝ ██║ ██║ ██████╔╝███████║███████╗█████╗ ███████╗ ███████║ ██╔══██╗██╔══██║╚════██║██╔══╝ ██╔═══██╗╚════██║ ██████╔╝██║ ██║███████║███████╗ ╚██████╔╝ ██║ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚═╝ ''') message = input( "\033[1;36mEnter the text you want to encode:\033[1;93m ") message_bytes = message.encode('utf-8') base64_bytes = base64.b64encode(message_bytes) base64_message = base64_bytes.decode('utf-8') print(f'\n\033[1;92mEncoded text: {base64_message}\n') back = input( "\033[1;33mDo you want to return to the menu? \033[1;32my\033[1;33m/\033[1;31mn\033[1;33m:\033[1;36m " ) if back == 'Y' or back == 'y': main() else: os.system("clear") FinalBanner() exit() elif op == '02' or op == '2': os.system("clear") print('''\033[1;93m ███╗ ███╗██████╗ ███████╗ ████╗ ████║██╔══██╗██╔════╝ ██╔████╔██║██║ ██║███████╗ ██║╚██╔╝██║██║ ██║╚════██║ ██║ ╚═╝ ██║██████╔╝███████║ ╚═╝ ╚═╝╚═════╝ ╚══════╝ ''') md5 = input("\033[1;36mEnter the text to generate a hash:\033[1;93m ") request = requests.get( 'https://api.hashify.net/hash/md5/hex?value={}'.format(md5)) address_data = request.json() if 'erro' not in address_data: print('\n\033[1;92mHash: {}\n'.format(address_data['Digest'])) back = input( '\033[1;33mDo you want to return to the menu? \033[1;32my\033[1;33m/\033[1;31mn\033[1;33m:\033[1;36m ' ) if back == 'Y' or back == 'y': main() else: os.system("clear") FinalBanner() exit() elif op == '03' or op == '3': os.system("clear") print('''\033[1;93m ███╗ ███╗██████╗ ██╗ ██╗ ████╗ ████║██╔══██╗██║ ██║ ██╔████╔██║██║ ██║███████║ ██║╚██╔╝██║██║ ██║╚════██║ ██║ ╚═╝ ██║██████╔╝ ██║ ╚═╝ ╚═╝╚═════╝ ╚═╝ ''') md4 = input("\033[1;36mEnter the text to generate a hash:\033[1;93m ") request = requests.get( 'https://api.hashify.net/hash/md4/hex?value={}'.format(md4)) address_data = request.json() if 'erro' not in address_data: print('\n\033[1;92mHash: {}\n'.format(address_data['Digest'])) back = input( '\033[1;33mDo you want to return to the menu? \033[1;32my\033[1;33m/\033[1;31mn\033[1;33m:\033[1;36m ' ) if back == 'Y' or back == 'y': main() else: os.system("clear") FinalBanner() exit() elif op == '04' or op == '4': os.system("clear") print('''\033[1;93m ██████╗ █████╗ ███████╗███████╗ ██╗ ██████╗ ██╔══██╗██╔══██╗██╔════╝██╔════╝ ███║██╔════╝ ██████╔╝███████║███████╗█████╗ ╚██║███████╗ ██╔══██╗██╔══██║╚════██║██╔══╝ ██║██╔═══██╗ ██████╔╝██║ ██║███████║███████╗ ██║╚██████╔╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ''') data = input("\033[1;36mEnter the text you want to encode:\033[1;93m ") encoded = data.encode("utf-8") b16 = base64.b16encode(encoded) print(f"\n\033[1;92mEncoded text: {b16}\n") back = input( '\033[1;33mDo you want to return to the menu? \033[1;32my\033[1;33m/\033[1;31mn\033[1;33m:\033[1;36m ' ) if back == 'y' or back == 'Y': main() else: os.system("clear") FinalBanner() exit() elif op == '05' or op == '5': os.system("clear") print('''\033[1;31m ____ _ _ _ _ _ _ _____ | __ )| | __ _ ___| | __ | | | | ___| | | |_ _|__ __ _ _ __ ___ | _ \| |/ _` |/ __| |/ / | |_| |/ _ \ | | | |/ _ \/ _` | '_ ` _ \ | |_) | | (_| | (__| < | _ | __/ | | | | __/ (_| | | | | | | |____/|_|\__,_|\___|_|\_\ |_| |_|\___|_|_| |_|\___|\__,_|_| |_| |_|\n \033[1;36mTeam:\033[1;32m Black Hell Team \033[1;36mCoded by:\033[1;32m Jo Power Tech (Leader) \033[1;36mTeam YT channel:\033[1;32m https://www.youtube.com/channel/UCFdCJf8YKHvOuWu2UxRI1fg \033[1;36mGithub ORG:\033[1;32m https://github.com/Black-Hell-Team \033[1;36mCountry:\033[1;32m Brazil ''') else: os.system("clear") print('\033[1;31mInvalid option') time.sleep(1.0) main()
#! /usr/bin/env/python # -*- coding:utf-8 -* import base64 original_string = 'This is the data,in the clear.' print 'Original:', original_string encoded_string = base64.b16encode(original_string) print 'Encoded:', encoded_string decoded_string = base64.b16decode(encoded_string) print 'Decoded:', decoded_string
def b16encode_text(update, context): user_reply = update.message.text encoded_text = base64.b16encode( str.encode(user_reply.replace('/b16encode ', '').strip())) update.message.reply_text(encoded_text.decode("utf-8"))
def _asXML(self): transaction = etree.Element('transaction', type="Sale Order") tiosafe_sync_list = self.getTioSafeSynchronizationObjectList(object_type='Product') erp5_sync_list = self.getERP5SynchronizationObjectList(object_type='Product') integration_site = self.getIntegrationSite() # marker for checking property existency MARKER = object() # specific value self.stop_date = self.start_date #self.reference = self.id # list of possible tags for a sale order tag_list = ( 'title', 'start_date', 'stop_date', 'reference', 'currency', ) self._setTagList(self, transaction, tag_list) self._setTagList(self, transaction, ['category', ], SEPARATOR) # set arrow list try: self._setPaymentMode(transaction) self._setArrowTagList(self, transaction) except ValueError: # A mapping must be missing return None # order the movement list movement_list = [] # build a list of 2-tuple # the first key contains the sort element # the second part of the tuple contains a dict which contains all the data # of the transaction line method_id = self.getPortalType().replace(' ', '') portal_type = self.getPortalType().replace(' ', '_').lower() module_id = "%s_module" %(portal_type) module = getattr(integration_site, module_id) getter_line_method = getattr( module, 'get%sLineList' % (method_id,), MARKER, ) if getter_line_method is not MARKER: # browse each transaction lines, build the sort element and set data parameter_kw = {'%s_id' % portal_type: str(self.getId()), } for line in getter_line_method(**parameter_kw): key_list = ['title', 'resource', 'reference', 'quantity', 'gross_price', 'vat', 'vat_price', 'net_price'] value_list = [getattr(line, x, '') for x in key_list] movement_dict = {'context': line,} # set to None the '' value of the list for k, v in zip(key_list, value_list): movement_dict[k] = v or None # Retrieve the gid of the resource for tiosafe_sync in tiosafe_sync_list: try: brain_node = tiosafe_sync.getObjectFromId(line.product_id) resource_gid = brain_node.getGid() break except (ValueError, AttributeError): resource_gid = " Unknown" for erp5_sync in erp5_sync_list: try: resource = erp5_sync.getDocumentFromGid(b16encode(resource_gid)) break except (ValueError, AttributeError): resource = None # after the work on the line set the resource value which will be # render in the xml movement_dict['resource'] = resource_gid # Work on vat if movement_dict['vat']: movement_dict['VAT'] = self.getVATCategory(movement_dict['vat']) if movement_dict['quantity'] is None: continue movement_dict['price'] = movement_dict['net_price'] # build the element which allows to sort movement_list.append(movement_dict) # Add Discount if getattr(self,'discount_price',0) > 0: discount_gid = b16decode(erp5_sync.getGidFromObject(integration_site.getSourceCarrierValue())) discount_dict = {'price': self.discount_price, 'quantity' : -1, 'title' : '%s' % (self.discount_title), 'reference' : '%s' % (self.discount_title), 'resource' : discount_gid, 'VAT' : self.getVATCategory(self.discount_tax_rate) } movement_list.append(discount_dict) # Add delivery if getattr(self,'delivery_price',0) > 0: delivery_gid = b16decode(erp5_sync.getGidFromObject(integration_site.getDestinationCarrierValue())) delivery_dict = {'price': self.delivery_price, 'quantity' : 1, 'title' : self.delivery_title, 'reference' : self.delivery_title, 'resource' : delivery_gid, 'VAT' : self.getVATCategory(self.delivery_tax_rate) } movement_list.append(delivery_dict) def cmp_resource(a,b): return cmp(a['resource'], b['resource']) movement_list.sort(cmp=cmp_resource) # the second part build the XML of the transaction # browse the ordered movement list and build the movement list as a result # the xml through of the line data in the dict for movement_dict in movement_list: movement = etree.SubElement(transaction, 'movement') # set arrow list on the movement if movement_dict.get("context", None) is not None: self._setArrowTagList(movement_dict['context'], movement) # if exist the following tags in the line dict, add them in the xml tag_list = ('resource', 'title', 'reference', 'quantity', 'price', 'VAT') for tag in tag_list: if tag in movement_dict: if movement_dict[tag] is not None: element = etree.SubElement(movement, tag) if tag == "price": element.text = "%.6f" % (float(movement_dict.get(tag, 0.0)),) elif tag == "quantity": element.text = "%.2f" % (float(movement_dict.get(tag, 0.0)),) else: element.text = movement_dict[tag] # add the categories to the movement #for category_value in movement_dict['category']: for category_value in movement_dict.get('category', []): LOG("category_value %s" %(category_value), 300, "") category = etree.SubElement(movement, 'category') category.text = category_value xml = etree.tostring(transaction, pretty_print=True, encoding='utf-8') LOG("asXML returns transaction %s" %(xml,), 300, "") return xml
def FunctionWithTwoParameter(self, funcion, parametros, exp1, exp2): if (parametros == 2): if (funcion == "div"): return Terminal(Tipo('decimal', exp1 / exp2, self.l(exp1 / exp2), -1), exp1 / exp2) elif (funcion == "gcd"): return Terminal(Tipo('integer', math.gcd(exp1, exp2), self.l(math.gcd(exp1, exp2)), -1), math.gcd(exp1, exp2)) elif (funcion == "mod"): return Terminal(Tipo('integer', exp1 % exp2, self.l(exp1 % exp2), -1), exp1 % exp2) elif (funcion == "power"): return Terminal(Tipo('decimal', math.pow(exp1, exp2), self.l(math.pow(exp1, exp2)), -1), math.pow(exp1, exp2)) elif (funcion == "round"): return Terminal(Tipo('decimal', round(exp1, exp2), self.l(round(exp1, exp2)), -1), round(exp1, exp2)) elif (funcion == "atan2"): return Terminal(Tipo('decimal', math.atan(exp1 / exp2), self.l(math.atan(exp1 / exp2)), -1), math.atan(exp1 / exp2)) elif (funcion == "atan2d"): return Terminal( Tipo('decimal', math.degrees(math.atan(exp1 / exp2)), self.l(math.atan(exp1 / exp2)), -1), math.degrees(math.atan(exp1 / exp2))) elif (funcion == "encode"): if (exp2.lower() == "base64"): cascci = exp1.encode('ascii') codificado = base64.b64encode(cascci) return Terminal(Tipo('varchar', codificado.decode('utf-8'), self.l(codificado.decode('utf-8')), -1), codificado.decode('utf-8')) elif (exp2.lower() == "hex"): cascci = exp1.encode('utf-8') codificado = base64.b16encode(cascci) return Terminal(Tipo('varchar', codificado.decode('utf-8'), self.l(codificado.decode('utf-8')), -1), codificado.decode('utf-8')) elif (exp2.lower() == "escape"): codificado = exp1.encode('unicode_escape').decode('utf-8') return Terminal(Tipo('varchar', codificado, self.l(codificado), -1), codificado) elif (funcion == "decode"): if (exp2.lower() == "base64"): codificado = base64.b64decode(exp1) return Terminal(Tipo('varchar', codificado.decode('utf-8'), self.l(codificado.decode('utf-8')), -1), codificado.decode('utf-8')) elif (exp2.lower() == "hex"): codificado = base64.b16decode(exp1) return Terminal(Tipo('varchar', codificado.decode('utf-8'), self.l(codificado.decode('utf-8')), -1), codificado.decode('utf-8')) elif (exp2.lower() == "escape"): codificado = exp1.encode('utf-8').decode('unicode_escape') return Terminal(Tipo('varchar', codificado, self.l(codificado), -1), codificado) elif (funcion == "date_part"): datepart = Date_Part(exp1, exp2) datepart=datepart.getval() return Terminal(Tipo('integer', datepart, self.l(datepart), -1), datepart) elif (funcion == "trim"): print('exp',exp2) trim = exp1.strip(exp2) return Terminal(Tipo('varchar', trim, self.l(trim), -1), trim) else: reporteerrores.append( Lerrores("Error Semantico", "La funcion" + funcion + "solo recibe 2 parametros", 0, 0)) return "Error: La funcion: " + funcion + " recibe 2 parametro"
def _GenSignedUrl(key, client_id, method, duration, gcs_path, logger, region, content_type=None, string_to_sign_debug=False): """Construct a string to sign with the provided key. Args: key: The private key to use for signing the URL. client_id: Client ID signing this URL. method: The HTTP method to be used with the signed URL. duration: timedelta for which the constructed signed URL should be valid. gcs_path: String path to the bucket of object for signing, in the form 'bucket' or 'bucket/object'. logger: logging.Logger for warning and debug output. region: Geographic region in which the requested resource resides. content_type: Optional Content-Type for the signed URL. HTTP requests using the URL must match this Content-Type. string_to_sign_debug: If true AND logger is enabled for debug level, print string to sign to debug. Used to differentiate user's signed URL from the probing permissions-check signed URL. Returns: The complete url (string). """ signing_time = _NowUTC() gs_host = config.get('Credentials', 'gs_host', 'storage.googleapis.com') signed_headers = {'host': gs_host} if method == 'RESUMABLE': method = 'POST' signed_headers['x-goog-resumable'] = 'start' if not content_type: logger.warn('Warning: no Content-Type header was specified with the -c ' 'flag, so uploads to the resulting Signed URL must not ' 'specify a Content-Type.') if content_type: signed_headers['content-type'] = content_type canonical_day = signing_time.strftime('%Y%m%d') canonical_time = signing_time.strftime('%Y%m%dT%H%M%SZ') canonical_scope = '{date}/{region}/storage/goog4_request'.format( date=canonical_day, region=region) signed_query_params = {} signed_query_params['x-goog-algorithm'] = _SIGNING_ALGO signed_query_params['x-goog-credential'] = client_id + '/' + canonical_scope signed_query_params['x-goog-date'] = canonical_time signed_query_params['x-goog-signedheaders'] = ';'.join( sorted(signed_headers.keys())) signed_query_params['x-goog-expires'] = '%d' % duration.total_seconds() canonical_resource = '/{}'.format(gcs_path) canonical_query_string = '&'.join( ['{}={}'.format(param, urllib.quote_plus(signed_query_params[param])) for param in sorted(signed_query_params.keys())]) canonical_headers = '\n'.join( ['{}:{}'.format(header.lower(), signed_headers[header]) for header in sorted(signed_headers.keys())]) + '\n' canonical_signed_headers = ';'.join(sorted(signed_headers.keys())) canonical_request = _CANONICAL_REQUEST_FORMAT.format( method=method, resource=canonical_resource, query_string=canonical_query_string, headers=canonical_headers, signed_headers=canonical_signed_headers, hashed_payload=_UNSIGNED_PAYLOAD) canonical_request_hasher = hashlib.sha256() canonical_request_hasher.update(canonical_request) hashed_canonical_request = base64.b16encode( canonical_request_hasher.digest()).lower() string_to_sign = _STRING_TO_SIGN_FORMAT.format( signing_algo=_SIGNING_ALGO, request_time=canonical_time, credential_scope=canonical_scope, hashed_request=hashed_canonical_request) if string_to_sign_debug and logger: logger.debug('Canonical request (ignore opening/closing brackets): [[[%s]]]' % canonical_request) logger.debug('String to sign (ignore opening/closing brackets): [[[%s]]]' % string_to_sign) signature = base64.b16encode(sign(key, string_to_sign, 'RSA-SHA256')).lower() final_url = _SIGNED_URL_FORMAT.format( host=gs_host, path=gcs_path, sig=signature, query_string=canonical_query_string) return final_url
#!/usr/bin/python import botan, base64, md5 class PyMD5(botan.HashFunctionImpl): def name(self): return "PyMD5" def update(self, input): self.md5.update(input) def final(self): output = self.md5.digest() self.md5 = md5.new() return output def __init__(self): botan.HashFunctionImpl.__init__(self, 16, 64) self.md5 = md5.new() hash = botan.HashFunction("SHA-256") print hash.name() print hash.digest_size hash.update("hi") hash.update(" ") hash.update("chappy") print base64.b16encode(hash.final()) hash2 = PyMD5() hash2.update("hi chappy") print base64.b16encode(hash2.final())
print 'Your Decryption : ' + sha384 elif select == '7': in_user = raw_input("Enter anything for Encryption : ") sha512 = hashlib.sha512(in_user).hexdigest() print 'Your Decryption : ' + sha512 elif select == '8': import base64 print ''' 1 > > > Encrypt 2 > > > Decrypt ''' select = raw_input('Select : ') if select == '1': encrypt = raw_input('Enter anything for Encryption : ') en = base64.b16encode(encrypt) print 'Your Encryption : ' + en elif select == '2': decrypt = raw_input('Enter anything for Decryption : ') de = base64.b16decode(decrypt) print 'Your Decryption : ' + de elif select == '9': import base64 print ''' 1 > > > Encrypt 2 > > > Decrypt ''' select = raw_input('Select : ') if select == '1': encrypt = raw_input('Enter anything for Encryption : ')