def encrypt_and_sign(msg, senderPrivPem, receiverPubPem, hash = 'sha256', cipher = 'aes_256_cbc', padding = 'pkcs1_oaep'): padding = PADDING[padding] key_len = int(cipher.split("_")[1]) key = os.urandom(key_len/8) iv = os.urandom(key_len/8) c = EVP.Cipher(alg = cipher, key = key, iv = iv, op = m2.encrypt) pmsg = cipher_filter(c, msg) rkey = RSA.load_pub_key_bio(BIO.MemoryBuffer(receiverPubPem)) emsg = rkey.public_encrypt(key + iv, padding) md = EVP.MessageDigest(hash) md.update(pmsg) md.update(emsg) digest = md.digest() skey = RSA.load_key_bio(BIO.MemoryBuffer(senderPrivPem)) sig = skey.sign(digest, hash) return (binascii.b2a_base64(pmsg).strip(), binascii.b2a_base64(emsg).strip(), binascii.b2a_base64(sig).strip())
def encode(f): var_name = ''.join( random.choice(string.ascii_lowercase + string.ascii_uppercase) for i in range(50)) if _version is 2: rev_data = binascii.b2a_base64(f)[-2::-1] data = var_name + ' = "' + str(rev_data) + '"' if _version is 3: rev_data = binascii.b2a_base64(f.encode('utf8')).decode('utf8')[-2::-1] data = var_name + ' = "' + str(rev_data) + '"' func_name = ''.join( random.choice(string.ascii_lowercase + string.ascii_uppercase) for i in range(50)) func_argv = ''.join( random.choice(string.ascii_lowercase + string.ascii_uppercase) for i in range(50)) f = ''' import binascii import sys %s def %s(%s): if sys.version_info.major is 2: return str(binascii.a2b_base64(%s[::-1])) elif sys.version_info.major is 3: return str(binascii.a2b_base64(%s[::-1]).encode('utf8'))[::-1].decode('utf8') else: sys.exit('Your python version is not supported!') exec(%s(%s)) ''' % (data, func_name, func_argv, func_argv, func_argv, func_name, var_name) return f
def setUp(self): self.client.put = curry(self.client.post, REQUEST_METHOD='PUT') self.client.delete = curry(self.client.get, REQUEST_METHOD='DELETE') self.headers = {'HTTP_AUTHORIZATION': 'Basic %s' % b2a_base64('rest:rest')[:-1]} self.advancedheaders = {'HTTP_AUTHORIZATION': 'Basic %s' % b2a_base64('restadvanced:restadvanced')[:-1]} self.adminheaders = {'HTTP_AUTHORIZATION': 'Basic %s' % b2a_base64('restadmin:restadmin')[:-1]} set_permissions()
def authenticate(self, mechanism, *auth_objects): mechanism = mechanism.upper() if not mechanism in self.login_mechs: raise ManageSieveClientError("Server doesn't allow %s " "authentication" % mechanism) if mechanism == self.AUTH_LOGIN: auth_objects = [self._sieve_name(binascii.b2a_base64(ao)[:-1]) for ao in auth_objects] elif mechanism == self.AUTH_PLAIN: if len(auth_objects) < 3: # assume authorization identity (authzid) is missing # and these two authobjects are username and password auth_objects.insert(0, '') ao = '\0'.join(auth_objects) ao = binascii.b2a_base64(ao)[:-1] auth_objects = [ self._sieve_string(ao) ] else: raise ManageSieveClientError("Unsupported authentication: %s" % mechanism) response = self._send_command("AUTHENTICATE", self._sieve_name(mechanism), *auth_objects) if response.status == Response.OK: log.debug("Authenticated") self.state = "AUTH" else: log.error("Authentication failed") return response
def login(self, mechanism, user, password, admin=""): """Authenticate command - requires response processing.""" # command-authenticate = "AUTHENTICATE" SP auth-type [SP string] *(CRLF string) # response-authenticate = *(string CRLF) (response-oknobye) mech = mechanism.upper() if not mech in self.loginmechs: raise self.error("Server doesn't allow %s authentication." % mech) if mechanism == 'PLAIN': if admin != '': encoded = binascii.b2a_base64("%s\0%s\0%s" % (user, admin, password)).strip() else: encoded = binascii.b2a_base64("%s\0%s\0%s" % (user, user, password)).strip() typ, data = self._command('AUTHENTICATE', sieve_name(mech)+" {"+str(len(encoded))+"+}", None, encoded) elif mechanism == 'LOGIN': encoded = binascii.b2a_base64("%s\0%s\0%s" % (user, user, password)).strip() typ, data = self._command('AUTHENTICATE', sieve_name(mech)+" {"+str(len(encoded))+"+}", encoded) else: raise self.error("Authentication %s dont implemented." % mech) if typ == 'OK': self.state = 'AUTH' return True else: return False
def start_auth_session(request): log = logging.getLogger("get_layers") log.debug("start") try: brand_identifier = request.POST['brand_id'] except KeyError: log.error("Got bad request.") return HttpResponseBadRequest() challenge = b2a_base64(os.urandom(32)) request.session['challenge'] = (challenge, time.time()) auth = request.session.get('auth', False) if auth: del request.session['auth'] try: layer_data = server.get_escrow_layers(brand_identifier) except (KeyError, IOError,): log.warn("Got missing brand_identifier: %s" % (brand_identifier,)) return HttpResponseNotFound() log.info("Returning escrow keys for %s" % (brand_identifier,)) data = dict(layer_data=b2a_base64(layer_data), challenge=challenge) return HttpResponse(json.dumps(data))
def generateNetstatus(nickname, idkey_digest, server_desc_digest, timestamp, ipv4, orport, ipv6=None, dirport=None, flags='Fast Guard Running Stable Valid', bandwidth_line=None): """Generate an ``@type networkwork-status`` document (unsigned). DOCDOC :param str nickname: The router's nickname. :param string idkey_digest: The SHA-1 digest of the router's public identity key. :param XXX server_desc_digest: The SHA-1 digest of the router's ``@type [bridge-]server-descriptor``, before the descriptor is signed. :param XXX timestamp: """ idkey_b64 = binascii.b2a_base64(idkey_digest) idb64 = str(idkey_b64).strip().rstrip('==') server_b64 = binascii.b2a_base64(server_desc_digest) srvb64 = str(server_b64).strip().rstrip('==') if bandwidth_line is not None: bw = int(bandwidth_line.split()[-1]) / 1024 # The 'observed' value dirport = dirport if dirport else 0 status = [] status.append("r %s %s %s %s %s %s %d" % (nickname, idb64, srvb64, timestamp, ipv4, orport, dirport)) if ipv6 is not None: status.append("a [%s]:%s" % (ipv6, orport)) status.append("s %s\nw Bandwidth=%s\np reject 1-65535\n" % (flags, bw)) return '\n'.join(status)
def check(s): """Check that `s' is a properly encoded base64 string.""" try: binascii.b2a_base64(s) except binascii.Error: return False return True
def upldfile(): if request.method == 'POST': files = request.files['file'] print(files.filename) print('bad dog') if files and allowed_file(files.filename): filename = secure_filename(files.filename) print(filename) updir = os.path.join(basedir, 'upload/') files.save(os.path.join(updir, filename)) file_size = os.path.getsize(os.path.join(updir, filename)) else: app.logger.info('ext name error') return jsonify(error='ext name error') result = execute_solver(files) if result == 'good': with open("static/images/solution.jpg", "rb") as image_file: encoded_string = binascii.b2a_base64(image_file.read()) return encoded_string elif result == 'error': print(result) with open("static/images/error.jpg", "rb") as image_file: encoded_string = binascii.b2a_base64(image_file.read()) return encoded_string
def doLogin(self,gameID,login,password): result = client.login(gameID, login, password) self.win.hide() if result == 1: gdata.config.game.lastlogin = login # TODO: remove in 0.6 gdata.config.game.lastpassword = None # if gdata.savePassword: gdata.config.game.lastpasswordcrypted = binascii.b2a_base64(password).strip() else: gdata.config.game.lastpasswordcrypted = None gdata.config.game.lastgameid = gameID gdata.config.game.accountcreated = 1 # write configuration gdata.config.save() gdata.config.game.lastpasswordcrypted = binascii.b2a_base64(password).strip() self.playerSelectDlg.display(self) elif result == 2: pass else: # login failed self.win.vPassword.text = '' self.win.vMessage.text = _('Wrong login and/or password') self.win.show()
def make_escrow_layer(pub_key_id, pub_key, data, sign_key): """ make an escrow layer (string) that includes the binary data pub_key_id = string to identify the private key the layer can be read with pub_key = public key object for the escrow party at this layer data = binary data to store sign_key = private key object of the user signing the layer returns binary string """ aes_key = new_session_key(pub_key.size() / 8) aes_iv = sha256(str(time.time())).digest()[:AES_NONCE_SIZE] aes = AES.new(sha256(aes_key).digest(), AES.MODE_CFB, aes_iv) aes_encoded_data = aes.encrypt(data) payload = zlib.compress(json.dumps(dict( aes_key = b2a_base64( pub_key.encrypt(aes_key, random_string(len(aes_key)))[0]), aes_iv = b2a_base64(aes_iv), data = b2a_base64(aes_encoded_data)))) sig_hmac = hmac.new(key='', msg=payload, digestmod=sha256).digest() sig = long_to_bytes(sign_key.sign(sig_hmac, random_string(len(sig_hmac)))[0]) struct_format = "!HHHL%ds%ds%ds%ds" % ( len(pub_key_id), len(sig_hmac), len(sig), len(payload), ) return struct.pack(struct_format, len(pub_key_id), len(sig_hmac), len(sig), len(payload), pub_key_id, sig_hmac, sig, payload)
def test_undo_multiple_with_text_in_POST(self): import binascii request = testing.DummyRequest() context = testing.DummyResource() inst = self._makeOne(context, request) conn = DummyConnection() def get_connection(req): self.assertEqual(req, request) return conn inst.get_connection = get_connection def authenticated_userid(req): self.assertEqual(req, request) return 1 post = testing.DummyResource() enca = binascii.b2a_base64(b'a').decode('ascii') encb = binascii.b2a_base64(b'b').decode('ascii') info = [enca + ' b', encb + ' f'] def getall(n): self.assertEqual(n, 'transaction') return info post.getall = getall request.POST = post request.sdiapi = DummySDIAPI() inst.authenticated_userid = authenticated_userid txn = DummyTransaction() inst.transaction = txn result = inst.undo_multiple() self.assertEqual(result.location, '/mgmt_path') self.assertEqual(conn._db.tids, [b'a', b'b']) self.assertTrue(txn.committed) self.assertEqual(txn.user, 1)
def genLogisticTags(self, digest, nonce, created): tmp = '' tmp = (self.xml["wp_open"] + "%s" + self.xml["wp_close"]) % binascii.b2a_base64(digest).strip() tmp = tmp + (self.xml["wn_open"] + "%s" + self.xml["wn_close"]) % binascii.b2a_base64(nonce).strip() tmp = tmp + (self.xml["wc_open"] + "%s" + self.xml["wc_close"]) % created.strip() return tmp
def encode(f): val_name = ''.join(random.choice(string.ascii_lowercase+string.ascii_uppercase) for i in range(50)) data = '' eval = '$' + val_name if _version is 2: data = '$' + val_name + ' = "' + str(binascii.b2a_base64(f)).replace('\n','') +'";\n' if _version is 3: data = '$' + val_name + ' = "' + str(binascii.b2a_base64(f.encode('latin-1')).decode('latin-1').replace('\n','')) +'";\n' var_str = '$' + ''.join(random.choice(string.ascii_lowercase+string.ascii_uppercase) for i in range(50)) var_data = '$' + ''.join(random.choice(string.ascii_lowercase+string.ascii_uppercase) for i in range(50)) func_name = ''.join(random.choice(string.ascii_lowercase+string.ascii_uppercase) for i in range(50)) func_argv = '$' + ''.join(random.choice(string.ascii_lowercase+string.ascii_uppercase) for i in range(50)) f = ''' use MIME::Base64 qw(decode_base64); %s sub %s { %s = shift; %s = decode_base64(%s); return %s; } %s = %s; eval %s(%s); '''%(data,func_name,func_argv,var_str,func_argv,var_str,var_data,eval,func_name,var_data) return f
def generate_keys(press_count, text_area, nick_textbox, other_nick_textbox, password_textbox): NICK = nick_textbox.get() OTHER_NICK = other_nick_textbox.get() password = password_textbox.get() print "nick: " + NICK print "other nick: " + OTHER_NICK print "password: "******"make sure nick, other nick and password entries are filled out!\n\n") text_area.config(fg="red",state=tk.DISABLED) else: global newaxo newaxo = Axolotl(NICK, dbname=OTHER_NICK+'.db', dbpassphrase=password) newaxo.printKeys() identity_key = "identity key: " + binascii.b2a_base64(newaxo.state['DHIs']) fingerprint = hashlib.sha224(newaxo.state['DHIs']).hexdigest().upper() #getting fingerprint fprint = '' for i in range(0, len(fingerprint), 4): fprint += fingerprint[i:i+2] + ':' fingerprint = "fingerprint:" + fprint[:-1] + "\n" rachet_key="rachet_key: " + binascii.b2a_base64(newaxo.state['DHRs']) handshake_key = "handshake key: " + binascii.b2a_base64(newaxo.handshakePKey) text_area.config(state=tk.NORMAL) text_area.insert(tk.END, identity_key+fingerprint+rachet_key+handshake_key) text_area.config(fg="black",state=tk.DISABLED)
def __get_header(self): nonce = str(time.time()) base64nonce = binascii.b2a_base64(binascii.a2b_qp(nonce)) created_date = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.localtime()) sha_object = sha.new(nonce + created_date + self.shared_secret) password_64 = binascii.b2a_base64(sha_object.digest()) return 'UsernameToken Username="******", PasswordDigest="%s", Nonce="%s", Created="%s"' % (self.user_name, password_64.strip(), base64nonce.strip(), created_date)
def create_apache_vhost( self, domain_name, farm_id, farm_role_id, document_root_dir, enable_ssl, ssl_private_key=None, ssl_certificate=None, ): """ @return Result """ params = {} params["DomainName"] = domain_name params["FarmID"] = farm_id params["FarmRoleID"] = farm_role_id params["DocumentRootDir"] = document_root_dir params["EnableSSL"] = enable_ssl if ssl_private_key: params["SSLPrivateKey"] = binascii.b2a_base64(ssl_private_key).strip() if ssl_certificate: params["SSLCertificate"] = binascii.b2a_base64(ssl_certificate).strip() return self._request( command="ApacheVhostCreate", params=params, response_reader=self._read_create_apache_vhost_response )
def exportKey(self, format='PEM', public=False, type=None): """Export the RSA key. A string is returned with the encoded public or the private half under the selected format. format: 'DER' (PKCS#1) or 'PEM' (RFC1421) """ if type == 'ssh-rsa' and public: return ''.join(binascii.b2a_base64('\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x03' + '\x00\x00\x01\x01\x00'.join([long_to_bytes(self.e), long_to_bytes(self.n)])).split("\n")) der = DerSequence() if not public and self.has_private(): keyType = "RSA PRIVATE" der[:] = [ 0, self.n, self.e, self.d, self.p, self.q, self.d % (self.p-1), self.d % (self.q-1), self.u ] else: keyType = "PUBLIC" der.append('\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01\x05\x00') bitmap = DerObject('BIT STRING') derPK = DerSequence() derPK[:] = [ self.n, self.e ] bitmap.payload = '\x00' + derPK.encode() der.append(bitmap.encode()) if format=='DER': return der.encode() if format=='PEM': pem = "-----BEGIN %s KEY-----\n" % keyType binaryKey = der.encode() # Each BASE64 line can take up to 64 characters (=48 bytes of data) chunks = [ binascii.b2a_base64(binaryKey[i:i+48]) for i in range(0, len(binaryKey), 48) ] pem += ''.join(chunks) pem += "-----END %s KEY-----" % keyType return pem return ValueError("")
def delete(self, key, range_end=None, prev_kv=False): """ Delete value(s) from etcd. URL: /v3alpha/kv/deleterange :param key: key is the first key to delete in the range. :type key: bytes :param range_end: range_end is the key following the last key to delete for the range [key, range_end).\nIf range_end is not given, the range is defined to contain only the key argument.\nIf range_end is one bit larger than the given key, then the range is all keys with the prefix (the given key).\nIf range_end is '\\0', the range is all keys greater than or equal to the key argument. :key range_end: bytes :param prev_kv: If prev_kv is set, etcd gets the previous key-value pairs before deleting it.\nThe previous key-value pairs will be returned in the delete response. :key prev_kv: bool """ url = u'{}/v3alpha/kv/deleterange'.format(self._url).encode() obj = { u'key': binascii.b2a_base64(key).decode(), u'range_end': binascii.b2a_base64(range_end).decode() if range_end else None, u'prev_kv': prev_kv } data = json.dumps(obj).encode('utf8') response = yield treq.post(url, data, headers=self.REQ_HEADERS) obj = yield treq.json_content(response) res = Deleted.parse(obj) returnValue(res)
def set(self, key, value, lease=None, prev_kv=None): """ Put puts the given key into the key-value store. A put request increments the revision of the key-value store and generates one event in the event history. URL: /v3alpha/kv/put :param key: key is the key, in bytes, to put into the key-value store. :type key: bytes :param lease: lease is the lease ID to associate with the key in the key-value store. A lease\nvalue of 0 indicates no lease. :type lease: int :param prev_kv: If prev_kv is set, etcd gets the previous key-value pair before changing it.\nThe previous key-value pair will be returned in the put response. :type prev_kv: bool :param value: value is the value, in bytes, to associate with the key in the key-value store. :key value: bytes """ url = u'{}/v3alpha/kv/put'.format(self._url).encode() obj = { u'key': binascii.b2a_base64(key).decode(), u'value': binascii.b2a_base64(value).decode() } data = json.dumps(obj).encode('utf8') response = yield treq.post(url, data, headers=self.REQ_HEADERS) obj = yield treq.json_content(response) revision = obj[u'header'][u'revision'] returnValue(revision)
def encode_str(state): """Convert bytes to a base64-encoded bytes. 'state' should be bytes """ if not isinstance(state, bytes): raise ValueError("state should be bytes") l_ = len(state) if l_ > 57: states = [] for i in range(0, l_, 57): states.append(b2a_base64(state[i:i + 57])[:-1]) state = b''.join(states) else: state = b2a_base64(state)[:-1] # state is still bytes, but all in 'ascii' encoding. l_ = state.find(b'=') if l_ >= 0: state = state[:l_] state = state.translate(tplus) return state
def test_undo_multiple_with_exception(self): import binascii from ZODB.POSException import POSError request = testing.DummyRequest() context = testing.DummyResource() inst = self._makeOne(context, request) conn = DummyConnection() def get_connection(req): self.assertEqual(req, request) return conn conn._db.undo_exc = POSError inst.get_connection = get_connection def authenticated_userid(req): self.assertEqual(req, request) return 1 post = testing.DummyResource() enca = binascii.b2a_base64(b'a') encb = binascii.b2a_base64(b'b') info = [enca + b' b', encb + b' f'] def getall(n): self.assertEqual(n, 'transaction') return info post.getall = getall request.POST = post request.sdiapi = DummySDIAPI() inst.authenticated_userid = authenticated_userid txn = DummyTransaction() inst.transaction = txn result = inst.undo_multiple() self.assertEqual(result.location, '/mgmt_path') self.assertTrue(txn.aborted) self.assertEqual( request.sdiapi.flashed, 'Could not undo, sorry' )
def gen_password(): """ Generate a random 24-character password. """ password1 = binascii.b2a_base64(os.urandom(9))[:-1] password2 = binascii.b2a_base64(os.urandom(9))[:-1] if len(password1) != 12 or len(password2) != 12 or password1 == password2: raise PasswordGenerationException() return password1 + password2
def refresh(self): self.news = [] for i in self.links: data = feedparser.parse(i) self.news += [News(binascii.b2a_base64(i['title'].encode()).decode(),\ binascii.b2a_base64(i['link'].encode()).decode(),\ int(time.mktime(i['published_parsed']))) for i in data['entries']]
def wait(self): try: # Communicate with process self.logger.debug('Communicating with %s (pid: %s)', self.interpreter, self.pid) while time.time() - self.start_time < self.exec_timeout: if self._proc_poll() is None: time.sleep(0.5) else: # Process terminated self.logger.debug('Process terminated') self.return_code = self._proc_complete() break else: # Process timeouted self.logger.debug('Timeouted: %s seconds. Killing process %s (pid: %s)', self.exec_timeout, self.interpreter, self.pid) self.return_code = self._proc_kill() if not os.path.exists(self.stdout_path): open(self.stdout_path, 'w+').close() if not os.path.exists(self.stderr_path): open(self.stderr_path, 'w+').close() elapsed_time = time.time() - self.start_time self.logger.debug('Finished %s' '\n %s' '\n 1: %s' '\n 2: %s' '\n return code: %s' '\n elapsed time: %s', self.interpreter, self.exec_path, format_size(os.path.getsize(self.stdout_path)), format_size(os.path.getsize(self.stderr_path)), self.return_code, elapsed_time) ret = dict( stdout=binascii.b2a_base64(get_truncated_log(self.stdout_path)), stderr=binascii.b2a_base64(get_truncated_log(self.stderr_path)), time_elapsed=elapsed_time, script_name=self.name, script_path=self.exec_path, event_name=self.event_name or '', return_code=self.return_code, event_server_id=self.event_server_id, event_id=self.event_id ) return ret except: if threading.currentThread().name != 'MainThread': self.logger.exception('Exception in script execution routine') else: raise finally: f = os.path.dirname(self.exec_path) if os.path.exists(f): shutil.rmtree(f)
def RegisterAuthorizedUser(request, name, surname, idNo, role, Password, mail): text_name = binascii.b2a_base64(encrypt(name)) text_surname = binascii.b2a_base64(encrypt(surname)) text_password = binascii.b2a_base64(encrypt(Password)) text_email = binascii.b2a_base64(encrypt(mail)) user = Person(first_name=text_name, last_name=text_surname, id=idNo, email=text_email,password=text_password, userRole= role) user.save() return True
def CertToAscii(cert): ser = cert.SerializeToString() crc = binascii.crc32(ser) & 0xFFFFFF # keep only last 24 bit (should use CRC-24 like OpenPGP) # OpenPGP uses initializations for its crc-24, see http://tools.ietf.org/html/rfc2440 asc = binascii.b2a_base64(cert.SerializeToString())[:-1] # without trailing newline asc += "=" # checksum is seperated by = asc += binascii.b2a_base64(("%06x" % crc).decode("hex")) return asc
def print_chksums( fnm, with_crc64, only_md5 ): if not only_md5: print( "\n"+fnm+":\n" ) inp = open(fnm,"rb") PART_SIZE = 1024*1024 # 1 MiB txt = inp.read( PART_SIZE ) h_md5 = hashlib.new( 'md5', txt ) if not only_md5: h_crc32 = binascii.crc32(txt) h_md4 = hashlib.new( 'md4', txt ) if with_crc64: h64,l64 = crc64update( txt, 0, 0 ) h_sha = hashlib.new( 'sha', txt ) h_sha1 = hashlib.new( 'sha1', txt ) # == 'DSA' 'DSA-SHA' 'ecdsa-with-SHA1' 'dsaWithSHA' 'dsaEncryption' h_sha224 = hashlib.new( 'sha224', txt ) h_sha256 = hashlib.new( 'sha256', txt ) h_sha384 = hashlib.new( 'sha384', txt ) h_sha512 = hashlib.new( 'sha512', txt ) h_ripemd160 = hashlib.new( 'ripemd160', txt ) h_whirlpool = hashlib.new( 'whirlpool', txt ) while len(txt) == PART_SIZE: txt = inp.read( PART_SIZE ) h_md5.update( txt ) if not only_md5: h_crc32 = binascii.crc32(txt,h_crc32) h_md4.update( txt ) if with_crc64: h64,l64 = crc64update( txt, h64, l64 ) h_sha.update( txt ) h_sha1.update( txt ) h_sha224.update( txt ) h_sha256.update( txt ) h_sha384.update( txt ) h_sha512.update( txt ) h_ripemd160.update( txt ) h_whirlpool.update( txt ) inp.close() if only_md5: print( h_md5.hexdigest(), "[%s]" % binascii.b2a_base64( h_md5.digest() )[:-1].decode('ascii'), fnm ) else: print( ' crc32 ', '%08x' % (h_crc32 & 0xFFFFFFFF) ) if with_crc64: print( ' crc64 ', "%08x%08x" % (h64,l64) ) print( ' md4 ', h_md4.hexdigest() ) print( ' md5 ', h_md5.hexdigest(), "'%s'" % binascii.b2a_base64( h_md5.digest() )[:-1].decode('ascii') ) print( ' ripemd160', h_ripemd160.hexdigest() ) print( ' sha ', h_sha.hexdigest() ) print( ' sha1 ', h_sha1.hexdigest(), "'%s'" % binascii.b2a_base64( h_sha1.digest() )[:-1].decode('ascii') ) print( ' sha224 ', h_sha224.hexdigest() ) print( ' sha256 ', h_sha256.hexdigest() ) s = h_sha384.hexdigest(); print( ' sha384 ', s[:64]+"\n", ' '*10, s[64:] ) s = h_sha512.hexdigest(); print( ' sha512 ', s[:64]+"\n", ' '*10, s[64:] ) s = h_whirlpool.hexdigest(); print( ' whirlpool', s[:64]+"\n", ' '*10, s[64:] )
def encode_images(format_dict): """b64-encodes images in a displaypub format dict Perhaps this should be handled in json_clean itself? Parameters ---------- format_dict : dict A dictionary of display data keyed by mime-type Returns ------- format_dict : dict A copy of the same dictionary, but binary image data ('image/png', 'image/jpeg' or 'application/pdf') is base64-encoded. """ # no need for handling of ambiguous bytestrings on Python 3, # where bytes objects always represent binary data and thus # base64-encoded. if py3compat.PY3: return format_dict encoded = format_dict.copy() pngdata = format_dict.get('image/png') if isinstance(pngdata, bytes): # make sure we don't double-encode if not pngdata.startswith(PNG64): pngdata = b2a_base64(pngdata) encoded['image/png'] = pngdata.decode('ascii') jpegdata = format_dict.get('image/jpeg') if isinstance(jpegdata, bytes): # make sure we don't double-encode if not jpegdata.startswith(JPEG64): jpegdata = b2a_base64(jpegdata) encoded['image/jpeg'] = jpegdata.decode('ascii') gifdata = format_dict.get('image/gif') if isinstance(gifdata, bytes): # make sure we don't double-encode if not gifdata.startswith((GIF_64, GIF89_64)): gifdata = b2a_base64(gifdata) encoded['image/gif'] = gifdata.decode('ascii') pdfdata = format_dict.get('application/pdf') if isinstance(pdfdata, bytes): # make sure we don't double-encode if not pdfdata.startswith(PDF64): pdfdata = b2a_base64(pdfdata) encoded['application/pdf'] = pdfdata.decode('ascii') return encoded
def test_b2a_base64_newline(self): # Issue #25357: test newline parameter b = self.type2test(b'hello') self.assertEqual(binascii.b2a_base64(b), b'aGVsbG8=\n') self.assertEqual(binascii.b2a_base64(b, newline=True), b'aGVsbG8=\n') self.assertEqual(binascii.b2a_base64(b, newline=False), b'aGVsbG8=')
def login(self, username=None, password=None): # Modified from: # https://github.com/retrospect-addon/plugin.video.retrospect/blob/master/channels/channel.se/sbs/chn_sbs.py # Local import to not slow down any other stuff import binascii try: # If running on Leia import pyaes except: # If running on Pre-Leia from resources.lib import pyaes import random now = int(time.time()) b64_now = binascii.b2a_base64(str(now).encode()).decode().strip() user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " \ "(KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36" window_id = "{}|{}".format( binascii.hexlify(os.urandom(16)).decode(), binascii.hexlify(os.urandom(16)).decode()) fe = ["DNT:unknown", "L:en-US", "D:24", "PR:1", "S:1920,975", "AS:1920,935", "TO:-120", "SS:true", "LS:true", "IDB:true", "B:false", "ODB:true", "CPUC:unknown", "PK:Win32", "CFP:990181251", "FR:false", "FOS:false", "FB:false", "JSF:Arial", "P:Chrome PDF Plugin", "T:0,false,false", "H:4", "SWF:false"] fs_murmur_hash = '48bf49e1796939175b0406859d00baec' data = [ {"key": "api_type", "value": "js"}, {"key": "p", "value": 1}, # constant {"key": "f", "value": self.device_id}, # browser instance ID {"key": "n", "value": b64_now}, # base64 encoding of time.now() {"key": "wh", "value": window_id}, # WindowHandle ID {"key": "fe", "value": fe}, # browser properties {"key": "ife_hash", "value": fs_murmur_hash}, # hash of browser properties {"key": "cs", "value": 1}, # canvas supported 0/1 {"key": "jsbd", "value": "{\"HL\":41,\"NCE\":true,\"DMTO\":1,\"DOTO\":1}"} ] data_value = json.dumps(data) stamp = now - (now % (60 * 60 * 6)) key_password = "******".format(user_agent, stamp) salt_bytes = os.urandom(8) key_iv = self.__evp_kdf(key_password.encode(), salt_bytes, key_size=8, iv_size=4, iterations=1, hash_algorithm="md5") key = key_iv["key"] iv = key_iv["iv"] encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(key, iv)) encrypted = encrypter.feed(data_value) # Again, make a final call to flush any remaining bytes and strip padding encrypted += encrypter.feed() salt_hex = binascii.hexlify(salt_bytes) iv_hex = binascii.hexlify(iv) encrypted_b64 = binascii.b2a_base64(encrypted) bda = { "ct": encrypted_b64.decode(), "iv": iv_hex.decode(), "s": salt_hex.decode() } bda_str = json.dumps(bda) bda_base64 = binascii.b2a_base64(bda_str.encode()) req_dict = { "bda": bda_base64.decode(), "public_key": "FE296399-FDEA-2EA2-8CD5-50F6E3157ECA", "site": "https://client-api.arkoselabs.com", "userbrowser": user_agent, "simulate_rate_limit": "0", "simulated": "0", "rnd": "{}".format(random.random()) } req_data = "" for k, v in req_dict.items(): req_data = "{}{}={}&".format(req_data, k, self.url_encode(v)) req_data = req_data.rstrip("&") arkose_headers = {"user-agent": user_agent} arkose_data = self.make_request('https://client-api.arkoselabs.com/fc/gt2/public_key/FE296399-FDEA-2EA2-8CD5-50F6E3157ECA', 'get', params=req_data, headers=arkose_headers) arkose_json = json.loads(arkose_data) arkose_token = arkose_json.get("token") if "rid=" not in arkose_token: self.log("Error logging in. Invalid Arkose token.") self.log(arkose_token) raise self.DplayError('Error logging in. Invalid Arkose token.') self.log("Succesfully required a login token from Arkose.") # Get new token self.get_token() discoveryplus_username = username discoveryplus_password = password creds = {"credentials": {"username": discoveryplus_username, "password": discoveryplus_password}} headers = { "x-disco-arkose-token": arkose_token, "x-disco-arkose-sitekey": "FE296399-FDEA-2EA2-8CD5-50F6E3157ECA", "Origin": "https://www.{site_url}".format(site_url=self.site_url), "x-disco-client": "WEB:10.16.0:AUTH_DPLAY_V1:4.0.1-rc2-gi1", # is not specified a captcha is required # "Sec-Fetch-Site": "same-site", # "Sec-Fetch-Mode": "cors", # "Sec-Fetch-Dest": "empty", "Referer": "https://www.{site_url}/myaccount/login".format(site_url=self.site_url), "User-Agent": user_agent } login_url = '{api_url}/login'.format(api_url=self.api_url) return self.make_request(login_url, 'post', payload=json.dumps(creds), headers=headers)
def makeFunctionHashHeuristic(self, address, compressed=False, followCalls=True): """ Consider: - Control Flow Graph - generalized instructions that: access memory/write memory/use registers/use constant/call/jmp/jmc and all his combinations. - special case of functions with just 1 BB and a couple of calls (follow the first call) @type address: DWORD @param address: address of the function to hash @type compressed: Boolean @param compressed: return a compressed base64 representation or the raw data @type followCalls: Boolean @param followCalls: follow the first call in a single basic block function @rtype: LIST @return: the first element is described below and the second is the result of this same function but over the first call of a single basic block function (if applies), each element is like this: a base64 representation of the compressed version of each bb hash: [4 bytes BB(i) start][4 bytes BB(i) 1st edge][4 bytes BB(i) 2nd edge] 0 <= i < BB count or the same but like a LIST with raw data. """ f = self.imm.getFunction(address) bbs = f.getBasicBlocks() bbmap = {} cfg = {} #Make a control flow graph for bb in bbs: cfg[bb.getStart()] = bb.getEdges() #Make a hash of each BB for bb in bbs: bbhash_data = [] for op in bb.getInstructions(self.imm): #take into account just information about the opcode instr = [] instr.append(op.getMemType()) instr.append(op.indexed) instr.append(op.getCmdType()) instr.append(op.optype[0]) instr.append(op.optype[1]) instr.append(op.optype[2]) instr.append(op.getSize()) bbhash_data.append(self.hash_a_list(instr)) bbhash = self.hash_a_list(bbhash_data) bbmap[bb.getStart()] = bbhash #Replace BB addresses with hashes rcfg = [] for start, edges in cfg.iteritems(): rstart = 0 redges = [0, 0] rstart = bbmap[start] if bbmap.has_key(edges[0]): redges[0] = bbmap[edges[0]] if bbmap.has_key(edges[1]): redges[1] = bbmap[edges[1]] rcfg.append([rstart, redges[0], redges[1]]) #special case for functions with just one basic block and one or more calls firstcall = [] if followCalls and len(bbs) == 1 and len(bbs[0].getCalls()) > 0: #we follow the first call and do the same work there, but avoiding recursion #XXX: why the first? op = self.imm.Disasm(bbs[0].getCalls()[0]) if op.getJmpConst(): firstcall = self.makeFunctionHashHeuristic( op.getJmpConst(), compressed, followCalls=False)[0] #self.imm.Log("following first call to: %08X" % op.getJmpConst()) del op del bbs del f rcfg.sort() if compressed: #make the final hash fhash = "" for data in rcfg: #[4 bytes BB(i) start][4 bytes BB(i) 1st edge][4 bytes BB(i) 2nd edge] fhash += struct.pack("LLL", data[0], data[1], data[2]) return [binascii.b2a_base64(fhash)[:-1], firstcall] else: return [rcfg, firstcall]
preklady = res.json()['data'] preklad = preklady[2] # roh identifier = preklad['identifier'] books = preklad['books'] params = { 'timestamp': int(time.time() * 1000), 'key': '597133743677397A24432646294A404E635166546A576E5A7234753778214125', } for i, book in enumerate(books): chapters = {} abbr = book['abbreviation'] for chapter in book['chapters']: params['timestamp'] = int(time.time() * 1000) code = '|'.join([identifier, abbr, str(chapter)]) code = binascii.b2a_base64(code.encode()).strip().decode() while True: res = requests.get('https://biblia.sk/api/text/%s' % (code, ), params=params) print(res.status_code, res.url) if res.status_code == 429: print('Too Many Requests, sleeping') time.sleep(40) continue break try: text = res.json() except Exception as e: print(res.content) raise e chapters[chapter] = [v['content'] for v in text['data']]
def b2a_base64(b): return binascii.b2a_base64(compat26Str(b))
def create_temp_xml(self): temp_buf = "" # delete the temp file if it exists try: os.stat(self.SSD_MD_INT_FILE_NAME) os.remove(self.SSD_MD_INT_FILE_NAME) except: print "" fd = open(self.SSD_MD_INT_FILE_NAME, 'w') fd.write("<MD_SIGN>\r") fd.write(" <MD_VERSION>" + self.MD_VERSION_VAL + "</MD_VERSION>\r") fd.write(" <MFG_ID>" + self.MFG_ID_VAL + "</MFG_ID>\r") fd.write(" <SW_VERSION>" + self.SW_VERSION_VAL + "</SW_VERSION>\r") fd.write(" <IMG_ENC_INFO>\r") fd.write(" <IMG_ENC_ALGO>" + self.IMG_ENC_ALGO_VAL + "</IMG_ENC_ALGO>\r") # Skip everything the IMG is not encrypted if "NULL" == self.IMG_ENC_ALGO_VAL: fd.write(" </IMG_ENC_INFO>\r" + "</MD_SIGN>") fd.close() return fd.write(" <IMG_ENC_PADDING_TYPE>" + self.IMG_ENC_PADDING_TYPE + "</IMG_ENC_PADDING_TYPE>\r") fd.write(" <IMG_ENC_OPERATION_MODE>" + self.IMG_ENC_OPERATION_MODE + "</IMG_ENC_OPERATION_MODE>\r") iv_bin_fp = open(self.IV_BIN_FILE_NAME, "rb") fd.write(" <IMG_ENC_IV>" + (binascii.b2a_base64(iv_bin_fp.read())).rstrip() + "</IMG_ENC_IV>\r") iv_bin_fp.close() fd.write(" </IMG_ENC_INFO>\r") fd.write(" <IEK_ENC_INFO>\r") fd.write(" <IEK_ENC_ALGO>" + self.IEK_ENC_ALGO + "</IEK_ENC_ALGO>\r") fd.write(" <IEK_ENC_PADDING_TYPE>" + self.IEK_ENC_PADDING_TYPE + "</IEK_ENC_PADDING_TYPE>\r") temp_key_id = open(self.DEV_PUB_KEY_ID_FILE_NAME, 'rb') fd.write(" <IEK_ENC_PUB_KEY_ID>" + (temp_key_id.read()).rstrip() + "</IEK_ENC_PUB_KEY_ID>\r") temp_key_id.close() # encrypt the IEK with Device public key os.system("openssl rsautl -encrypt -pkcs -in " + \ self.IEK_BIN_FILE_NAME + \ " -inkey " + self.DEV_PUB_KEY_FILE_NAME + \ " -pubin -out temp_iek.dat") # convert the encrypted key to b64 format os.system("openssl enc -base64 -A -in temp_iek.dat -out temp_iek.b64") temp_iek = open("temp_iek.b64") fd.write(" <IEK_CIPHER_VALUE>" + (temp_iek.read()).rstrip() + "</IEK_CIPHER_VALUE>\r") fd.write(" </IEK_ENC_INFO>\r") fd.write(" <MD_SIG_INFO>\r") fd.write(" <MD_SIG_ALGO>" + self.MD_SIG_ALGO + "</MD_SIG_ALGO>\r") fd.write(" <MD_SIG_DGST_ALGO>" + self.MD_SIG_DGST_ALGO + "</MD_SIG_DGST_ALGO>\r") fd.write(" <MD_SIG_PADDING_TYPE>" + self.MD_SIG_PADDING_TYPE + "</MD_SIG_PADDING_TYPE>\r") temp_key_id = open(self.OEM_PUB_KEY_ID_FILE_NAME, 'rb') fd.write(" <MD_SIG_OEM_PUB_KEY_ID>" + temp_key_id.read().rstrip() + "</MD_SIG_OEM_PUB_KEY_ID>\r") temp_key_id.close() fd.write(" </MD_SIG_INFO>\r") fd.write("</MD_SIGN>") # close files & remove temp files fd.close() temp_iek.close() os.remove("temp_iek.dat") os.remove("temp_iek.b64")
def _auth(self, load): ''' Authenticate the client, use the sent public key to encrypt the AES key which was generated at start up. This method fires an event over the master event manager. The event is tagged "auth" and returns a dict with information about the auth event # Verify that the key we are receiving matches the stored key # Store the key if it is not there # Make an RSA key with the pub key # Encrypt the AES key as an encrypted salt.payload # Package the return and return it ''' if not salt.utils.verify.valid_id(self.opts, load['id']): log.info( 'Authentication request from invalid id {id}'.format(**load)) return {'enc': 'clear', 'load': {'ret': False}} log.info('Authentication request from {id}'.format(**load)) # 0 is default which should be 'unlimited' if self.opts['max_minions'] > 0: # use the ConCache if enabled, else use the minion utils if self.cache_cli: minions = self.cache_cli.get_cached() else: minions = self.ckminions.connected_ids() if len(minions) > 1000: log.info('With large numbers of minions it is advised ' 'to enable the ConCache with \'con_cache: True\' ' 'in the masters configuration file.') if not len(minions) <= self.opts['max_minions']: # we reject new minions, minions that are already # connected must be allowed for the mine, highstate, etc. if load['id'] not in minions: msg = ('Too many minions connected (max_minions={0}). ' 'Rejecting connection from id ' '{1}'.format(self.opts['max_minions'], load['id'])) log.info(msg) eload = { 'result': False, 'act': 'full', 'id': load['id'], 'pub': load['pub'] } self.event.fire_event( eload, salt.utils.event.tagify(prefix='auth')) return {'enc': 'clear', 'load': {'ret': 'full'}} # Check if key is configured to be auto-rejected/signed auto_reject = self.auto_key.check_autoreject(load['id']) auto_sign = self.auto_key.check_autosign(load['id']) pubfn = os.path.join(self.opts['pki_dir'], 'minions', load['id']) pubfn_pend = os.path.join(self.opts['pki_dir'], 'minions_pre', load['id']) pubfn_rejected = os.path.join(self.opts['pki_dir'], 'minions_rejected', load['id']) pubfn_denied = os.path.join(self.opts['pki_dir'], 'minions_denied', load['id']) if self.opts['open_mode']: # open mode is turned on, nuts to checks and overwrite whatever # is there pass elif os.path.isfile(pubfn_rejected): # The key has been rejected, don't place it in pending log.info('Public key rejected for {0}. Key is present in ' 'rejection key dir.'.format(load['id'])) eload = {'result': False, 'id': load['id'], 'pub': load['pub']} self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth')) return {'enc': 'clear', 'load': {'ret': False}} elif os.path.isfile(pubfn): # The key has been accepted, check it with salt.utils.files.fopen(pubfn, 'r') as pubfn_handle: if pubfn_handle.read().strip() != load['pub'].strip(): log.error( 'Authentication attempt from {id} failed, the public ' 'keys did not match. This may be an attempt to compromise ' 'the Salt cluster.'.format(**load)) # put denied minion key into minions_denied with salt.utils.files.fopen(pubfn_denied, 'w+') as fp_: fp_.write(load['pub']) eload = { 'result': False, 'id': load['id'], 'act': 'denied', 'pub': load['pub'] } self.event.fire_event( eload, salt.utils.event.tagify(prefix='auth')) return {'enc': 'clear', 'load': {'ret': False}} elif not os.path.isfile(pubfn_pend): # The key has not been accepted, this is a new minion if os.path.isdir(pubfn_pend): # The key path is a directory, error out log.info('New public key {id} is a directory'.format(**load)) eload = {'result': False, 'id': load['id'], 'pub': load['pub']} self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth')) return {'enc': 'clear', 'load': {'ret': False}} if auto_reject: key_path = pubfn_rejected log.info( 'New public key for {id} rejected via autoreject_file'. format(**load)) key_act = 'reject' key_result = False elif not auto_sign: key_path = pubfn_pend log.info( 'New public key for {id} placed in pending'.format(**load)) key_act = 'pend' key_result = True else: # The key is being automatically accepted, don't do anything # here and let the auto accept logic below handle it. key_path = None if key_path is not None: # Write the key to the appropriate location with salt.utils.files.fopen(key_path, 'w+') as fp_: fp_.write(load['pub']) ret = {'enc': 'clear', 'load': {'ret': key_result}} eload = { 'result': key_result, 'act': key_act, 'id': load['id'], 'pub': load['pub'] } self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth')) return ret elif os.path.isfile(pubfn_pend): # This key is in the pending dir and is awaiting acceptance if auto_reject: # We don't care if the keys match, this minion is being # auto-rejected. Move the key file from the pending dir to the # rejected dir. try: shutil.move(pubfn_pend, pubfn_rejected) except (IOError, OSError): pass log.info('Pending public key for {id} rejected via ' 'autoreject_file'.format(**load)) ret = {'enc': 'clear', 'load': {'ret': False}} eload = { 'result': False, 'act': 'reject', 'id': load['id'], 'pub': load['pub'] } self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth')) return ret elif not auto_sign: # This key is in the pending dir and is not being auto-signed. # Check if the keys are the same and error out if this is the # case. Otherwise log the fact that the minion is still # pending. with salt.utils.files.fopen(pubfn_pend, 'r') as pubfn_handle: if pubfn_handle.read() != load['pub']: log.error( 'Authentication attempt from {id} failed, the public ' 'key in pending did not match. This may be an ' 'attempt to compromise the Salt cluster.'.format( **load)) # put denied minion key into minions_denied with salt.utils.files.fopen(pubfn_denied, 'w+') as fp_: fp_.write(load['pub']) eload = { 'result': False, 'id': load['id'], 'act': 'denied', 'pub': load['pub'] } self.event.fire_event( eload, salt.utils.event.tagify(prefix='auth')) return {'enc': 'clear', 'load': {'ret': False}} else: log.info( 'Authentication failed from host {id}, the key is in ' 'pending and needs to be accepted with salt-key ' '-a {id}'.format(**load)) eload = { 'result': True, 'act': 'pend', 'id': load['id'], 'pub': load['pub'] } self.event.fire_event( eload, salt.utils.event.tagify(prefix='auth')) return {'enc': 'clear', 'load': {'ret': True}} else: # This key is in pending and has been configured to be # auto-signed. Check to see if it is the same key, and if # so, pass on doing anything here, and let it get automatically # accepted below. with salt.utils.files.fopen(pubfn_pend, 'r') as pubfn_handle: if pubfn_handle.read() != load['pub']: log.error( 'Authentication attempt from {id} failed, the public ' 'keys in pending did not match. This may be an ' 'attempt to compromise the Salt cluster.'.format( **load)) # put denied minion key into minions_denied with salt.utils.files.fopen(pubfn_denied, 'w+') as fp_: fp_.write(load['pub']) eload = { 'result': False, 'id': load['id'], 'pub': load['pub'] } self.event.fire_event( eload, salt.utils.event.tagify(prefix='auth')) return {'enc': 'clear', 'load': {'ret': False}} else: os.remove(pubfn_pend) else: # Something happened that I have not accounted for, FAIL! log.warning('Unaccounted for authentication failure') eload = {'result': False, 'id': load['id'], 'pub': load['pub']} self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth')) return {'enc': 'clear', 'load': {'ret': False}} log.info('Authentication accepted from {id}'.format(**load)) # only write to disk if you are adding the file, and in open mode, # which implies we accept any key from a minion. if not os.path.isfile(pubfn) and not self.opts['open_mode']: with salt.utils.files.fopen(pubfn, 'w+') as fp_: fp_.write(load['pub']) elif self.opts['open_mode']: disk_key = '' if os.path.isfile(pubfn): with salt.utils.files.fopen(pubfn, 'r') as fp_: disk_key = fp_.read() if load['pub'] and load['pub'] != disk_key: log.debug('Host key change detected in open mode.') with salt.utils.files.fopen(pubfn, 'w+') as fp_: fp_.write(load['pub']) pub = None # the con_cache is enabled, send the minion id to the cache if self.cache_cli: self.cache_cli.put_cache([load['id']]) # The key payload may sometimes be corrupt when using auto-accept # and an empty request comes in try: with salt.utils.files.fopen(pubfn) as f: pub = RSA.importKey(f.read()) except (ValueError, IndexError, TypeError) as err: log.error('Corrupt public key "{0}": {1}'.format(pubfn, err)) return {'enc': 'clear', 'load': {'ret': False}} cipher = PKCS1_OAEP.new(pub) ret = { 'enc': 'pub', 'pub_key': self.master_key.get_pub_str(), 'publish_port': self.opts['publish_port'] } # sign the master's pubkey (if enabled) before it is # sent to the minion that was just authenticated if self.opts['master_sign_pubkey']: # append the pre-computed signature to the auth-reply if self.master_key.pubkey_signature(): log.debug('Adding pubkey signature to auth-reply') log.debug(self.master_key.pubkey_signature()) ret.update({'pub_sig': self.master_key.pubkey_signature()}) else: # the master has its own signing-keypair, compute the master.pub's # signature and append that to the auth-reply log.debug("Signing master public key before sending") pub_sign = salt.crypt.sign_message( self.master_key.get_sign_paths()[1], ret['pub_key']) ret.update({'pub_sig': binascii.b2a_base64(pub_sign)}) mcipher = PKCS1_OAEP.new(self.master_key.key) if self.opts['auth_mode'] >= 2: if 'token' in load: try: mtoken = mcipher.decrypt(load['token']) aes = '{0}_|-{1}'.format( salt.master.SMaster.secrets['aes']['secret'].value, mtoken) except Exception: # Token failed to decrypt, send back the salty bacon to # support older minions pass else: aes = salt.master.SMaster.secrets['aes']['secret'].value ret['aes'] = cipher.encrypt(aes) else: if 'token' in load: try: mtoken = mcipher.decrypt(load['token']) ret['token'] = cipher.encrypt(mtoken) except Exception: # Token failed to decrypt, send back the salty bacon to # support older minions pass aes = salt.master.SMaster.secrets['aes']['secret'].value ret['aes'] = cipher.encrypt( salt.master.SMaster.secrets['aes']['secret'].value) # Be aggressive about the signature digest = hashlib.sha256(aes).hexdigest() ret['sig'] = salt.crypt.private_encrypt(self.master_key.key, digest) eload = { 'result': True, 'act': 'accept', 'id': load['id'], 'pub': load['pub'] } self.event.fire_event(eload, salt.utils.event.tagify(prefix='auth')) return ret
def HMAC_SHA1(self, keys_string, base_string): hashed = hmac.new(keys_string, base_string, hashlib.sha1) return binascii.b2a_base64(hashed.digest())[:-1]
sam = sam.text sr = a2b_base64(sr.text).decode() if sam == 'POST': html, uri = sr, None elif sam == 'REDIRECT': uri, html = sr, None else: p.error("Unknown SAML method (%s)" % sam) # launch external browser for debugging if args.external: print("Got SAML %s, opening external browser for debugging..." % sam, file=stderr) import webbrowser if html: uri = 'data:text/html;base64,' + b2a_base64(html.encode()).decode() webbrowser.open(uri) raise SystemExit # spawn WebKit view to do SAML interactive login if args.verbose: print("Got SAML %s, opening browser..." % sam, file=stderr) slv = SAMLLoginView(uri, html, verbose=args.verbose, cookies=args.cookies, verify=args.verify) Gtk.main() if not slv.success: p.error('''Login window closed without producing SAML cookie''')
def dump_board_info(self): # OTP added in v4: print("Bootloader Protocol: %u" % self.bl_rev) if self.bl_rev > 3: otp = b'' for byte in range(0, 32*6, 4): x = self.__getOTP(byte) otp = otp + x # print(binascii.hexlify(x).decode('Latin-1') + ' ', end='') # see src/modules/systemlib/otp.h in px4 code: otp_id = otp[0:4] otp_idtype = otp[4:5] otp_vid = otp[8:4:-1] otp_pid = otp[12:8:-1] otp_coa = otp[32:160] # show user: try: print("OTP:") print(" type: " + otp_id.decode('Latin-1')) print(" idtype: " + binascii.b2a_qp(otp_idtype).decode('Latin-1')) print(" vid: " + binascii.hexlify(otp_vid).decode('Latin-1')) print(" pid: " + binascii.hexlify(otp_pid).decode('Latin-1')) print(" coa: " + binascii.b2a_base64(otp_coa).decode('Latin-1'), end='') print(" sn: ", end='') for byte in range(0, 12, 4): x = self.__getSN(byte) x = x[::-1] # reverse the bytes print(binascii.hexlify(x).decode('Latin-1'), end='') # show user print('') except Exception: # ignore bad character encodings pass if self.bl_rev >= 5: des = self.__getCHIPDes() if (len(des) == 2): print("ChipDes:") print(" family: %s" % des[0]) print(" revision: %s" % des[1]) print("Chip:") if self.bl_rev > 4: chip = self.__getCHIP() mcu_id = chip & 0xfff revs = {} F4_IDS = { 0x413: "STM32F40x_41x", 0x419: "STM32F42x_43x", 0x421: "STM32F42x_446xx", } F7_IDS = { 0x449: "STM32F74x_75x", 0x451: "STM32F76x_77x", } H7_IDS = { 0x450: "STM32H74x_75x", } family = mcu_id & 0xfff if family in F4_IDS: mcu = F4_IDS[family] MCU_REV_STM32F4_REV_A = 0x1000 MCU_REV_STM32F4_REV_Z = 0x1001 MCU_REV_STM32F4_REV_Y = 0x1003 MCU_REV_STM32F4_REV_1 = 0x1007 MCU_REV_STM32F4_REV_3 = 0x2001 revs = { MCU_REV_STM32F4_REV_A: ("A", True), MCU_REV_STM32F4_REV_Z: ("Z", True), MCU_REV_STM32F4_REV_Y: ("Y", True), MCU_REV_STM32F4_REV_1: ("1", True), MCU_REV_STM32F4_REV_3: ("3", False), } rev = (chip & 0xFFFF0000) >> 16 if rev in revs: (label, flawed) = revs[rev] if flawed and family == 0x419: print(" %x %s rev%s (flawed; 1M limit, see STM32F42XX Errata sheet sec. 2.1.10)" % (chip, mcu, label,)) elif family == 0x419: print(" %x %s rev%s (no 1M flaw)" % (chip, mcu, label,)) else: print(" %x %s rev%s" % (chip, mcu, label,)) elif family in F7_IDS: print(" %s %08x" % (F7_IDS[family], chip)) elif family in H7_IDS: print(" %s %08x" % (H7_IDS[family], chip)) else: print(" [unavailable; bootloader too old]") print("Info:") print(" flash size: %u" % self.fw_maxsize) name = self.board_name_for_board_id(self.board_type) if name is not None: print(" board_type: %u (%s)" % (self.board_type, name)) else: print(" board_type: %u" % self.board_type) print(" board_rev: %u" % self.board_rev) print("Identification complete")
def assemble_http_basic_auth(scheme, username, password): v = binascii.b2a_base64( (username + ":" + password).encode("utf8")).decode("ascii") return scheme + " " + v
try: r = requests.get(wall_url, params=params) while r.json()['response']['items']: for item in r.json()['response']['items']: # TODO: parse date and an author if not item.get('is_pinned'): if not (item.get('attachments') and item.get('attachments')[0].get('photo')): poems.append(escape(item['text'].replace( '\r', ''))) # TODO: should not depends on platform else: # TODO: parse all attached images image = requests.get( item.get('attachments')[0].get('photo').get( 'photo_604')) images.append(b2a_base64(image.content).decode('utf-8')) poems.append('<image l:href="#image_{}.jpg"/>'.format( len(images))) print('Got {} items. Getting +{} more...'.format( len(poems), params['count'])) params['offset'] += params['count'] sleep(1) # to avoid "Too many requests per second" error r = requests.get(wall_url, params=params) print('{} items retrieved. Writing a file...'.format(len(poems))) except: print('Something is wrong. Response text: \n{}'.format(r.text)) quit() # TODO: use xml builder or any template engine instead of horrible flat text result_file_name = '{}-{}.fb2'.format(date.today(), params['domain'])
print("Connecting to NTRIP caster at %s:%d (NTRIP v%d)" % (c['caster']['host'], c['caster']['port'], c['caster']['version'])) try: s.connect( socket.getaddrinfo(c['caster']['host'], c['caster']['port'])[0][-1]) except: print("Error connecting to mountpoint") s.close() continue print("Mounting on /%s" % (c['mountpoint'])) authorization = binascii.b2a_base64( bytes(c['caster']['username'] + ':' + c['caster']['password'], 'utf-8')).decode('ascii') s.write(("GET /%s HTTP/1.1\r\n" "User-Agent: NTRIP Ortner2.0\r\n" "Authorization: Basic %s\r\n" "Accept: */*\r\nConnection: close\r\n" "\r\n") % (c['mountpoint'], authorization)) response = s.readline().decode('utf-8').strip() if response.startswith('HTTP/1.1'): response_code = response[9:12] if response_code == "200": print("Successfully connected to mountpoint") while s.readline() != b'\r\n':
def exportKey(self, format='PEM', passphrase=None, pkcs=1, protection=None): """Export this RSA key. :Parameters: format : string The format to use for wrapping the key: - *'DER'*. Binary encoding. - *'PEM'*. Textual encoding, done according to `RFC1421`_/`RFC1423`_. - *'OpenSSH'*. Textual encoding, done according to OpenSSH specification. Only suitable for public keys (not private keys). passphrase : string For private keys only. The pass phrase used for deriving the encryption key. pkcs : integer For *DER* and *PEM* format only. The PKCS standard to follow for assembling the components of the key. You have two choices: - **1** (default): the public key is embedded into an X.509 ``SubjectPublicKeyInfo`` DER SEQUENCE. The private key is embedded into a `PKCS#1`_ ``RSAPrivateKey`` DER SEQUENCE. - **8**: the private key is embedded into a `PKCS#8`_ ``PrivateKeyInfo`` DER SEQUENCE. This value cannot be used for public keys. protection : string The encryption scheme to use for protecting the private key. If ``None`` (default), the behavior depends on ``format``: - For *DER*, the *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC* scheme is used. The following operations are performed: 1. A 16 byte Triple DES key is derived from the passphrase using `Crypto.Protocol.KDF.PBKDF2` with 8 bytes salt, and 1 000 iterations of `Crypto.Hash.HMAC`. 2. The private key is encrypted using CBC. 3. The encrypted key is encoded according to PKCS#8. - For *PEM*, the obsolete PEM encryption scheme is used. It is based on MD5 for key derivation, and Triple DES for encryption. Specifying a value for ``protection`` is only meaningful for PKCS#8 (that is, ``pkcs=8``) and only if a pass phrase is present too. The supported schemes for PKCS#8 are listed in the `Crypto.IO.PKCS8` module (see ``wrap_algo`` parameter). :Return: A byte string with the encoded public or private half of the key. :Raise ValueError: When the format is unknown or when you try to encrypt a private key with *DER* format and PKCS#1. :attention: If you don't provide a pass phrase, the private key will be exported in the clear! .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt """ if passphrase is not None: passphrase = tobytes(passphrase) if format == 'OpenSSH': eb = long_to_bytes(self.e) nb = long_to_bytes(self.n) if bord(eb[0]) & 0x80: eb = bchr(0x00) + eb if bord(nb[0]) & 0x80: nb = bchr(0x00) + nb keyparts = [b('ssh-rsa'), eb, nb] keystring = b('').join( [struct.pack(">I", len(kp)) + kp for kp in keyparts]) return b('ssh-rsa ') + binascii.b2a_base64(keystring)[:-1] # DER format is always used, even in case of PEM, which simply # encodes it into BASE64. if self.has_private(): binary_key = newDerSequence(0, self.n, self.e, self.d, self.p, self.q, self.d % (self.p - 1), self.d % (self.q - 1), inverse(self.q, self.p)).encode() if pkcs == 1: keyType = 'RSA PRIVATE' if format == 'DER' and passphrase: raise ValueError("PKCS#1 private key cannot be encrypted") else: # PKCS#8 if format == 'PEM' and protection is None: keyType = 'PRIVATE' binary_key = PKCS8.wrap(binary_key, oid, None) else: keyType = 'ENCRYPTED PRIVATE' if not protection: protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC' binary_key = PKCS8.wrap(binary_key, oid, passphrase, protection) passphrase = None else: keyType = "RSA PUBLIC" binary_key = newDerSequence( algorithmIdentifier, newDerBitString(newDerSequence(self.n, self.e))).encode() if format == 'DER': return binary_key if format == 'PEM': pem_str = PEM.encode(binary_key, keyType + " KEY", passphrase, self._randfunc) return tobytes(pem_str) raise ValueError( "Unknown key format '%s'. Cannot export the RSA key." % format)
def sign(ui, repo, *revs, **opts): """add a signature for the current or given revision If no revision is given, the parent of the working directory is used, or tip if no revision is checked out. See :hg:`help dates` for a list of formats valid for -d/--date. """ mygpg = newgpg(ui, **opts) sigver = "0" sigmessage = "" date = opts.get('date') if date: opts['date'] = util.parsedate(date) if revs: nodes = [repo.lookup(n) for n in revs] else: nodes = [ node for node in repo.dirstate.parents() if node != hgnode.nullid ] if len(nodes) > 1: raise util.Abort( _('uncommitted merge - please provide a ' 'specific revision')) if not nodes: nodes = [repo.changelog.tip()] for n in nodes: hexnode = hgnode.hex(n) ui.write( _("signing %d:%s\n") % (repo.changelog.rev(n), hgnode.short(n))) # build data data = node2txt(repo, n, sigver) sig = mygpg.sign(data) if not sig: raise util.Abort(_("error while signing")) sig = binascii.b2a_base64(sig) sig = sig.replace("\n", "") sigmessage += "%s %s %s\n" % (hexnode, sigver, sig) # write it if opts['local']: repo.opener.append("localsigs", sigmessage) return msigs = match.exact(repo.root, '', ['.hgsigs']) s = repo.status(match=msigs, unknown=True, ignored=True)[:6] if util.any(s) and not opts["force"]: raise util.Abort( _("working copy of .hgsigs is changed " "(please commit .hgsigs manually " "or use --force)")) sigsfile = repo.wfile(".hgsigs", "ab") sigsfile.write(sigmessage) sigsfile.close() if '.hgsigs' not in repo.dirstate: repo[None].add([".hgsigs"]) if opts["no_commit"]: return message = opts['message'] if not message: # we don't translate commit messages message = "\n".join([ "Added signature for changeset %s" % hgnode.short(n) for n in nodes ]) try: repo.commit(message, opts['user'], opts['date'], match=msigs, editor=cmdutil.getcommiteditor(**opts)) except ValueError, inst: raise util.Abort(str(inst))
def bcur2base64(encoded): raw = bcur_decode(encoded.split("/")[-1]) return binascii.b2a_base64(raw).strip()
def _dosign(ui, repo, *revs, **opts): mygpg = newgpg(ui, **opts) sigver = "0" sigmessage = "" date = opts.get('date') if date: opts['date'] = util.parsedate(date) if revs: nodes = [repo.lookup(n) for n in revs] else: nodes = [ node for node in repo.dirstate.parents() if node != hgnode.nullid ] if len(nodes) > 1: raise error.Abort( _('uncommitted merge - please provide a ' 'specific revision')) if not nodes: nodes = [repo.changelog.tip()] for n in nodes: hexnode = hgnode.hex(n) ui.write( _("signing %d:%s\n") % (repo.changelog.rev(n), hgnode.short(n))) # build data data = node2txt(repo, n, sigver) sig = mygpg.sign(data) if not sig: raise error.Abort(_("error while signing")) sig = binascii.b2a_base64(sig) sig = sig.replace("\n", "") sigmessage += "%s %s %s\n" % (hexnode, sigver, sig) # write it if opts['local']: repo.vfs.append("localsigs", sigmessage) return if not opts["force"]: msigs = match.exact(repo.root, '', ['.hgsigs']) if any(repo.status(match=msigs, unknown=True, ignored=True)): raise error.Abort(_("working copy of .hgsigs is changed "), hint=_("please commit .hgsigs manually")) sigsfile = repo.wvfs(".hgsigs", "ab") sigsfile.write(sigmessage) sigsfile.close() if '.hgsigs' not in repo.dirstate: repo[None].add([".hgsigs"]) if opts["no_commit"]: return message = opts['message'] if not message: # we don't translate commit messages message = "\n".join([ "Added signature for changeset %s" % hgnode.short(n) for n in nodes ]) try: editor = cmdutil.getcommiteditor(editform='gpg.sign', **opts) repo.commit(message, opts['user'], opts['date'], match=msigs, editor=editor) except ValueError as inst: raise error.Abort(str(inst))
def _b64encode(s): """ Encode a binary string as base64 with no trailing newline. """ return b2a_base64(s).strip()
def encode_b64_buffer() -> bytes: return (binascii.b2a_base64("".join(b64_buffer).encode("utf-16be")) # .rstrip(b"\n=").replace(b"/", b","))
def getMessageSignature(secret_key, message): #http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html return binascii.b2a_base64( hmac.new(secret_key, message, hashlib.sha1).digest())[:-1] # get rid of newline
def upload(self, fw): # Make sure we are doing the right thing if self.board_type != fw.property('board_id'): msg = "Firmware not suitable for this board (board_type=%u board_id=%u)" % ( self.board_type, fw.property('board_id')) print("WARNING: %s" % msg) if args.force: print("FORCED WRITE, FLASHING ANYWAY!") else: raise IOError(msg) if self.fw_maxsize < fw.property('image_size'): raise RuntimeError("Firmware image is too large for this board") # OTP added in v4: if self.bl_rev > 3: for byte in range(0, 32 * 6, 4): x = self.__getOTP(byte) self.otp = self.otp + x print(binascii.hexlify(x).decode('Latin-1') + ' ', end='') # see src/modules/systemlib/otp.h in px4 code: self.otp_id = self.otp[0:4] self.otp_idtype = self.otp[4:5] self.otp_vid = self.otp[8:4:-1] self.otp_pid = self.otp[12:8:-1] self.otp_coa = self.otp[32:160] # show user: try: print("type: " + self.otp_id.decode('Latin-1')) print("idtype: " + binascii.b2a_qp(self.otp_idtype).decode('Latin-1')) print("vid: " + binascii.hexlify(self.otp_vid).decode('Latin-1')) print("pid: " + binascii.hexlify(self.otp_pid).decode('Latin-1')) print("coa: " + binascii.b2a_base64(self.otp_coa).decode('Latin-1')) print("sn: ", end='') for byte in range(0, 12, 4): x = self.__getSN(byte) x = x[::-1] # reverse the bytes self.sn = self.sn + x print(binascii.hexlify(x).decode('Latin-1'), end='') # show user print('') print("chip: %08x" % self.__getCHIP()) if (self.bl_rev >= 5): des = self.__getCHIPDes() if (len(des) == 2): print("family: %s" % des[0]) print("revision: %s" % des[1]) print("flash %d" % self.fw_maxsize) except Exception: # ignore bad character encodings pass self.__erase("Erase ") self.__program("Program", fw) if self.bl_rev == 2: self.__verify_v2("Verify ", fw) else: self.__verify_v3("Verify ", fw) if args.boot_delay is not None: self.__set_boot_delay(args.boot_delay) print("\nRebooting.\n") self.__reboot() self.port.close()
def b2a_base64(b): return binascii.b2a_base64(b).decode("ascii")
def b2a_base64(b): return binascii.b2a_base64(b)
import httplib import binascii import time userName = "******" password = "******" blogId = "1234567890" path = "http://www.blogger.com/atom/%s" % blogId created = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()) cookie = binascii.b2a_base64("%s:%s" % (userName, password)) headers = { "Content-type": 'application/atom+xml', "Authorization": 'BASIC %s' % cookie.strip(), "UserAgent": 'pyatomblogger', } body = """<?xml version="1.0" encoding="UTF-8" ?> <entry xmlns="http://purl.org/atom/ns#"> <generator url="http://jpa.berlios.de/">JPA-1.0</generator> <title mode="escaped" type="text/html">Hello world</title> <issued>%s</issued> <content type="application/xhtml+xml"> <div xmlns="http://www.w3.org/1999/xhtml">Testing the AtomAPI</div> </content> </entry>""" % created conn = httplib.HTTPConnection('proxy_host:8081') conn.set_debuglevel(1) conn.request("POST", path, body, headers)
def CutBytes(expression, filename, options): data = cBinaryFile(filename, C2BIP3(options.password), options.noextraction, options.literalfilenames).Data() if options.grep or options.grepno: start = 0 if options.jsonoutput: object = [] counter = 1 while True: result = CutData(data[start:], expression) if result[0] == '': break else: oDump = cDump(result[0], offset=start + result[1], dumplinelength=dumplinelength) if options.hexdump: StdoutWriteChunked(oDump.HexDump() + '\n') elif options.hexdumpnows: StdoutWriteChunked(binascii.b2a_hex(result[0]) + '\n') elif options.base64: StdoutWriteChunked(oDump.Base64Dump()) elif options.base64nows: StdoutWriteChunked(oDump.Base64Dump(True) + '\n') elif options.asciidump: StdoutWriteChunked(oDump.HexAsciiDump() + '\n') elif options.asciidumprle: StdoutWriteChunked(oDump.HexAsciiDump(True) + '\n') elif options.jsonoutput: object.append({ 'id': counter, 'name': '0x%08x' % (start + result[1]), 'content': binascii.b2a_base64(result[0]).strip('\n') }) counter += 1 else: if start == 0: IfWIN32SetBinary(sys.stdout) StdoutWriteChunked(result[0]) if options.grep: start += result[1] + 1 else: start += result[2] if options.jsonoutput: print( json.dumps({ 'version': 2, 'id': 'didierstevens.com', 'type': 'content', 'fields': ['id', 'name', 'content'], 'items': object })) else: if options.hexdump: DumpFunction = lambda x: C2BIP3(HexDump(x)) elif options.hexdumpnows: DumpFunction = lambda x: binascii.b2a_hex(x) elif options.base64: DumpFunction = Base64Dump elif options.base64nows: DumpFunction = lambda x: Base64Dump(x, True) elif options.asciidump: DumpFunction = lambda x: C2BIP3(HexAsciiDump(x, False)) elif options.asciidumprle: DumpFunction = lambda x: C2BIP3(HexAsciiDump(x, True)) else: DumpFunction = lambda x: x IfWIN32SetBinary(sys.stdout) data = CutData(data, expression)[0] if options.prefix != '': fch, prefix = FilenameCheckHash(options.prefix, False, data) if fch != FCH_DATA: raise Exception('Error %s parsing prefix: %s' % (prefix, options.prefix)) else: data = prefix + data if options.suffix != '': fch, suffix = FilenameCheckHash(options.suffix, False, data) if fch != FCH_DATA: raise Exception('Error %s parsing suffix: %s' % (suffix, options.suffix)) else: data = data + suffix StdoutWriteChunked(DumpFunction(data))
def connection_init(self, port, ip): """Метод отвечающий за устанновку соединения с сервером.""" # Инициализация сокета и сообщение серверу о нашем появлении self.transport = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Таймаут необходим для освобождения сокета. self.transport.settimeout(5) # Соединяемся, 5 попыток соединения, флаг успеха ставим в True если # удалось connected = False for i in range(5): logger.info(f'Попытка подключения №{i + 1}') try: self.transport.connect((ip, port)) except (OSError, ConnectionRefusedError): pass else: connected = True logger.debug("Connection established.") break time.sleep(1) # Если соединится не удалось - исключение if not connected: logger.critical('Не удалось установить соединение с сервером') raise ServerError('Не удалось установить соединение с сервером') logger.debug('Starting auth dialog.') # Запускаем процедуру авторизации # Получаем хэш пароля passwd_bytes = self.password.encode('utf-8') salt = self.username.lower().encode('utf-8') passwd_hash = hashlib.pbkdf2_hmac('sha512', passwd_bytes, salt, 10000) passwd_hash_string = binascii.hexlify(passwd_hash) logger.debug(f'Passwd hash ready: {passwd_hash_string}') # Получаем публичный ключ и декодируем его из байтов pubkey = self.keys.publickey().export_key().decode('ascii') # Авторизируемся на сервере with socket_lock: presense = { ACTION: PRESENCE, TIME: time.time(), USER: { ACCOUNT_NAME: self.username, PUBLIC_KEY: pubkey } } logger.debug(f"Presense message = {presense}") # Отправляем серверу приветственное сообщение. try: send_message(self.transport, presense) ans = get_message(self.transport) logger.debug(f'Server response = {ans}.') # Если сервер вернул ошибку, бросаем исключение. if RESPONSE in ans: if ans[RESPONSE] == 400: raise ServerError(ans[ERROR]) elif ans[RESPONSE] == 511: # Если всё нормально, то продолжаем процедуру # авторизации. ans_data = ans[DATA] hash = hmac.new(passwd_hash_string, ans_data.encode('utf-8'), 'MD5') digest = hash.digest() my_ans = RESPONSE_511 my_ans[DATA] = binascii.b2a_base64(digest).decode( 'ascii') send_message(self.transport, my_ans) self.process_server_ans(get_message(self.transport)) except (OSError, json.JSONDecodeError) as err: logger.debug(f'Connection error.', exc_info=err) raise ServerError('Сбой соединения в процессе авторизации.')
# Convert hex to base64 # The string: 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d # Should produce: SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t # from binascii import b2a_base64 hexString = '49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d' # Get byte representation of hex string bytesOfHexString = bytes.fromhex(hexString) #base64 encode hex string bytes base64RepOFHexBytes = b2a_base64(bytesOfHexString) #Print base64 rep of Hex string with no new line print(base64RepOFHexBytes.rstrip())
def export_key(self, format='PEM', pkcs8=None, passphrase=None, protection=None, randfunc=None): """Export this DSA key. Args: format (string): The encoding for the output: - *'PEM'* (default). ASCII as per `RFC1421`_/ `RFC1423`_. - *'DER'*. Binary ASN.1 encoding. - *'OpenSSH'*. ASCII one-liner as per `RFC4253`_. Only suitable for public keys, not for private keys. passphrase (string): *Private keys only*. The pass phrase to protect the output. pkcs8 (boolean): *Private keys only*. If ``True`` (default), the key is encoded with `PKCS#8`_. If ``False``, it is encoded in the custom OpenSSL/OpenSSH container. protection (string): *Only in combination with a pass phrase*. The encryption scheme to use to protect the output. If :data:`pkcs8` takes value ``True``, this is the PKCS#8 algorithm to use for deriving the secret and encrypting the private DSA key. For a complete list of algorithms, see :mod:`Cryptodome.IO.PKCS8`. The default is *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*. If :data:`pkcs8` is ``False``, the obsolete PEM encryption scheme is used. It is based on MD5 for key derivation, and Triple DES for encryption. Parameter :data:`protection` is then ignored. The combination ``format='DER'`` and ``pkcs8=False`` is not allowed if a passphrase is present. randfunc (callable): A function that returns random bytes. By default it is :func:`Cryptodome.Random.get_random_bytes`. Returns: byte string : the encoded key Raises: ValueError : when the format is unknown or when you try to encrypt a private key with *DER* format and OpenSSL/OpenSSH. .. warning:: If you don't provide a pass phrase, the private key will be exported in the clear! .. _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 """ if passphrase is not None: passphrase = tobytes(passphrase) if randfunc is None: randfunc = Random.get_random_bytes if format == 'OpenSSH': tup1 = [self._key[x].to_bytes() for x in ('p', 'q', 'g', 'y')] def func(x): if (bord(x[0]) & 0x80): return bchr(0) + x else: return x tup2 = [func(x) for x in tup1] keyparts = [b'ssh-dss'] + tup2 keystring = b''.join( [struct.pack(">I", len(kp)) + kp for kp in keyparts]) return b'ssh-dss ' + binascii.b2a_base64(keystring)[:-1] # DER format is always used, even in case of PEM, which simply # encodes it into BASE64. params = DerSequence([self.p, self.q, self.g]) if self.has_private(): if pkcs8 is None: pkcs8 = True if pkcs8: if not protection: protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC' private_key = DerInteger(self.x).encode() binary_key = PKCS8.wrap(private_key, oid, passphrase, protection, key_params=params, randfunc=randfunc) if passphrase: key_type = 'ENCRYPTED PRIVATE' else: key_type = 'PRIVATE' passphrase = None else: if format != 'PEM' and passphrase: raise ValueError("DSA private key cannot be encrypted") ints = [0, self.p, self.q, self.g, self.y, self.x] binary_key = DerSequence(ints).encode() key_type = "DSA PRIVATE" else: if pkcs8: raise ValueError("PKCS#8 is only meaningful for private keys") binary_key = _create_subject_public_key_info( oid, DerInteger(self.y), params) key_type = "PUBLIC" if format == 'DER': return binary_key if format == 'PEM': pem_str = PEM.encode(binary_key, key_type + " KEY", passphrase, randfunc) return tobytes(pem_str) raise ValueError( "Unknown key format '%s'. Cannot export the DSA key." % format)
def pil_to_data_url(image, format='png', **kwargs): mime_types = {'jpeg': 'image/jpeg', 'png': 'image/png'} header = f'data:{mime_types[format]};base64,' buf = io.BytesIO() image.save(buf, format=format, **kwargs) return header + binascii.b2a_base64(buf.getvalue()).decode()
def encode(item): return binascii.b2a_base64(pickle.dumps(item))[:-1] # remove trailing newline