Python binascii.a2b_base64() Examples

The following are 30 code examples of binascii.a2b_base64(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module binascii , or try the search function .
Example #1
Source File: base64.py    From jawfish with MIT License 8 votes vote down vote up
def b64decode(s, altchars=None, validate=False):
    """Decode a Base64 encoded byte string.

    s is the byte string to decode.  Optional altchars must be a
    string of length 2 which specifies the alternative alphabet used
    instead of the '+' and '/' characters.

    The decoded string is returned.  A binascii.Error is raised if s is
    incorrectly padded.

    If validate is False (the default), non-base64-alphabet characters are
    discarded prior to the padding check.  If validate is True,
    non-base64-alphabet characters in the input result in a binascii.Error.
    """
    s = _bytes_from_decode_data(s)
    if altchars is not None:
        altchars = _bytes_from_decode_data(altchars)
        assert len(altchars) == 2, repr(altchars)
        s = s.translate(bytes.maketrans(altchars, b'+/'))
    if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
        raise binascii.Error('Non-base64 digit found')
    return binascii.a2b_base64(s) 
Example #2
Source File: account.py    From selene-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def _build_login_schematic(self) -> Login:
        login = None
        login_data = self.request.json.get('login')
        if login_data is not None:
            email = login_data.get('email')
            if email is not None:
                email = a2b_base64(email).decode()
            password = login_data.get('password')
            if password is not None:
                password = a2b_base64(password).decode()
            login = Login(dict(
                federated_platform=login_data.get('federatedPlatform'),
                federated_token=login_data.get('federatedToken'),
                email=email,
                password=password
            ))

        return login 
Example #3
Source File: keybag.py    From pyaff4 with Apache License 2.0 6 votes vote down vote up
def create(vek, keySizeBytes, certificatePath):
        #print("VEK: " + str(binascii.hexlify(vek)))
        publicKeyPem = open(certificatePath).read()
        publicKey = RSA.importKey(publicKeyPem)
        # Convert from PEM to DER

        lines = publicKeyPem.replace(" ", '').split()
        publicKeyDer = binascii.a2b_base64(''.join(lines[1:-1]))

        cert = x509.load_pem_x509_certificate(SmartStr(publicKeyPem), default_backend())
        subjectName = cert.subject.rfc4514_string()
        serial = cert.serial_number

        cipher = PKCS1_OAEP.new(key=publicKey, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1(x, y, SHA1))
        wrapped_key = cipher.encrypt(vek)
        #print("WrappedKey: " + str(binascii.hexlify(wrapped_key)))

        return CertEncryptedKeyBag(subjectName, serial, keySizeBytes, wrapped_key) 
Example #4
Source File: qr.py    From specter-diy with MIT License 6 votes vote down vote up
def parse(self, data):
        # TODO: refactor with ramfiles
        if data is None:
            return None, None
        # probably base64-encoded PSBT
        if data[:4] == b"cHNi":
            try:
                psbt = a2b_base64(data)
                if psbt[:5] != b"psbt\xff":
                    raise HostError("Not a PSBT")
                return self.SIGN_PSBT, BytesIO(psbt)
            except:
                pass
        # probably wallet descriptor
        if b"&" in data and "?" not in data:
            return self.ADD_WALLET, BytesIO(data)
        # probably verifying address
        if data.startswith(b"bitcoin:") or b"index=" in data:
            return self.VERIFY_ADDRESS, BytesIO(data)
        return self.UNKNOWN, BytesIO(data) 
Example #5
Source File: tasks.py    From Politikon with GNU General Public License v2.0 6 votes vote down vote up
def send_email_task(
    subject, message, from_email, recipient_list, fail_silently=True, attachments=None, cc=None, bcc=None
):
    """
    Common Celery task to send e-mail message to given recipients.
    :param subject: subject of the e-mail
    :param message: e-mail message (in plain text)
    :param from_email: sender address
    :param recipient_list: list of recipient addresses
    :param fail_silently: if True, won't raise exceptions
    :param attachments: optional list of attachments to add to the message
    :param cc: list of cc e-mails
    :param bcc: list of bcc e-mails
    """
    if attachments:
        for attachment in attachments:
            attachment[1] = binascii.a2b_base64(attachment[1])  # decoding

    send_mail(subject, message, from_email, recipient_list, fail_silently, attachments, cc, bcc)
    logger.info(
        u"'events:tasks:send_email_task' finished sending e-mail to '{0}' with subject '{1}'."
        .format('; '.join(recipient_list), subject)
    ) 
Example #6
Source File: base64.py    From BinderFilter with MIT License 6 votes vote down vote up
def b64decode(s, altchars=None):
    """Decode a Base64 encoded string.

    s is the string to decode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies the
    alternative alphabet used instead of the '+' and '/' characters.

    The decoded string is returned.  A TypeError is raised if s were
    incorrectly padded or if there are non-alphabet characters present in the
    string.
    """
    if altchars is not None:
        s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
    try:
        return binascii.a2b_base64(s)
    except binascii.Error, msg:
        # Transform this exception for consistency
        raise TypeError(msg) 
Example #7
Source File: base64mime.py    From BinderFilter with MIT License 6 votes vote down vote up
def decode(s, convert_eols=None):
    """Decode a raw base64 string.

    If convert_eols is set to a string value, all canonical email linefeeds,
    e.g. "\\r\\n", in the decoded text will be converted to the value of
    convert_eols.  os.linesep is a good choice for convert_eols if you are
    decoding a text attachment.

    This function does not parse a full MIME header value encoded with
    base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
    level email.header class for that functionality.
    """
    if not s:
        return s

    dec = a2b_base64(s)
    if convert_eols:
        return dec.replace(CRLF, convert_eols)
    return dec


# For convenience and backwards compatibility w/ standard base64 module 
Example #8
Source File: usb.py    From specter-diy with MIT License 6 votes vote down vote up
def sign_psbt(self, stream):
        # decode to file
        with open(self.path+"/psbt", "wb") as f:
            chunk = bytearray(4)
            l = stream.readinto(chunk)
            while l > 0:
                f.write(a2b_base64(chunk[:l]))
                l = stream.readinto(chunk)
        # reopen to read
        with open(self.path+"/psbt", "rb") as f:
            # ask the manager to sign transaction
            # if tx is not ok - it will raise an error
            psbt = await self.manager.sign_psbt(f, remote=True)
            if psbt is None:
                self.respond(b'error: User cancelled')
        # serialize, convert to base64, send back
        raw_tx_stream = BytesIO(psbt.serialize())
        # convert to base64 in chunks
        chunk = bytearray(3)
        l = raw_tx_stream.readinto(chunk)
        while l > 0:
            self.usb.write(b2a_base64(chunk[:l]).strip())
            l = raw_tx_stream.readinto(chunk)
        # add EOL
        self.respond(b'') 
Example #9
Source File: httpRequest.py    From MicroWebSrv2 with MIT License 6 votes vote down vote up
def CheckBasicAuth(self, username, password) :
        if not isinstance(username, str) :
            raise ValueError('"username" must be a string.')
        if not isinstance(password, str) :
            raise ValueError('"password" must be a string.')
        auth = self.Authorization
        if auth :
            try :
                auth = auth.split()
                if len(auth) == 2 and auth[0].lower() == 'basic' :
                    auth = a2b_base64(auth[1].encode()).decode()
                    auth = auth.split(':')
                    return ( auth[0].lower() == username.lower() and \
                             auth[1] == password )
            except :
                pass
        return False

    # ------------------------------------------------------------------------ 
Example #10
Source File: base64mime.py    From meddle with MIT License 6 votes vote down vote up
def decode(s, convert_eols=None):
    """Decode a raw base64 string.

    If convert_eols is set to a string value, all canonical email linefeeds,
    e.g. "\\r\\n", in the decoded text will be converted to the value of
    convert_eols.  os.linesep is a good choice for convert_eols if you are
    decoding a text attachment.

    This function does not parse a full MIME header value encoded with
    base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
    level email.header class for that functionality.
    """
    if not s:
        return s

    dec = a2b_base64(s)
    if convert_eols:
        return dec.replace(CRLF, convert_eols)
    return dec


# For convenience and backwards compatibility w/ standard base64 module 
Example #11
Source File: base64mime.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def decode(string):
    """Decode a raw base64 string, returning a bytes object.

    This function does not parse a full MIME header value encoded with
    base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
    level email.header class for that functionality.
    """
    if not string:
        return bytes()
    elif isinstance(string, str):
        return a2b_base64(string.encode('raw-unicode-escape'))
    else:
        return a2b_base64(string)


# For convenience and backwards compatibility w/ standard base64 module 
Example #12
Source File: base64mime.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def decode(string):
    """Decode a raw base64 string, returning a bytes object.

    This function does not parse a full MIME header value encoded with
    base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
    level email.header class for that functionality.
    """
    if not string:
        return bytes()
    elif isinstance(string, str):
        return a2b_base64(string.encode('raw-unicode-escape'))
    else:
        return a2b_base64(string)


# For convenience and backwards compatibility w/ standard base64 module 
Example #13
Source File: base64mime.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def decode(string):
    """Decode a raw base64 string, returning a bytes object.

    This function does not parse a full MIME header value encoded with
    base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
    level email.header class for that functionality.
    """
    if not string:
        return bytes()
    elif isinstance(string, str):
        return a2b_base64(string.encode('raw-unicode-escape'))
    else:
        return a2b_base64(string)


# For convenience and backwards compatibility w/ standard base64 module 
Example #14
Source File: base64mime.py    From pmatic with GNU General Public License v2.0 6 votes vote down vote up
def decode(s, convert_eols=None):
    """Decode a raw base64 string.

    If convert_eols is set to a string value, all canonical email linefeeds,
    e.g. "\\r\\n", in the decoded text will be converted to the value of
    convert_eols.  os.linesep is a good choice for convert_eols if you are
    decoding a text attachment.

    This function does not parse a full MIME header value encoded with
    base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
    level email.header class for that functionality.
    """
    if not s:
        return s

    dec = a2b_base64(s)
    if convert_eols:
        return dec.replace(CRLF, convert_eols)
    return dec


# For convenience and backwards compatibility w/ standard base64 module 
Example #15
Source File: base64.py    From pmatic with GNU General Public License v2.0 6 votes vote down vote up
def b64decode(s, altchars=None):
    """Decode a Base64 encoded string.

    s is the string to decode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies the
    alternative alphabet used instead of the '+' and '/' characters.

    The decoded string is returned.  A TypeError is raised if s were
    incorrectly padded or if there are non-alphabet characters present in the
    string.
    """
    if altchars is not None:
        s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
    try:
        return binascii.a2b_base64(s)
    except binascii.Error, msg:
        # Transform this exception for consistency
        raise TypeError(msg) 
Example #16
Source File: base64.py    From meddle with MIT License 6 votes vote down vote up
def b64decode(s, altchars=None):
    """Decode a Base64 encoded string.

    s is the string to decode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies the
    alternative alphabet used instead of the '+' and '/' characters.

    The decoded string is returned.  A TypeError is raised if s were
    incorrectly padded or if there are non-alphabet characters present in the
    string.
    """
    if altchars is not None:
        s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
    try:
        return binascii.a2b_base64(s)
    except binascii.Error, msg:
        # Transform this exception for consistency
        raise TypeError(msg) 
Example #17
Source File: base64mime.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def decode(string):
    """Decode a raw base64 string, returning a bytes object.

    This function does not parse a full MIME header value encoded with
    base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
    level email.header class for that functionality.
    """
    if not string:
        return bytes()
    elif isinstance(string, str):
        return a2b_base64(string.encode('raw-unicode-escape'))
    else:
        return a2b_base64(string)


# For convenience and backwards compatibility w/ standard base64 module 
Example #18
Source File: base64.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def b64decode(s, altchars=None, validate=False):
    """Decode the Base64 encoded bytes-like object or ASCII string s.

    Optional altchars must be a bytes-like object or ASCII string of length 2
    which specifies the alternative alphabet used instead of the '+' and '/'
    characters.

    The result is returned as a bytes object.  A binascii.Error is raised if
    s is incorrectly padded.

    If validate is False (the default), characters that are neither in the
    normal base-64 alphabet nor the alternative alphabet are discarded prior
    to the padding check.  If validate is True, these non-alphabet characters
    in the input result in a binascii.Error.
    """
    s = _bytes_from_decode_data(s)
    if altchars is not None:
        altchars = _bytes_from_decode_data(altchars)
        assert len(altchars) == 2, repr(altchars)
        s = s.translate(bytes.maketrans(altchars, b'+/'))
    if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
        raise binascii.Error('Non-base64 digit found')
    return binascii.a2b_base64(s) 
Example #19
Source File: authenticate_internal.py    From selene-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def _authenticate_credentials(self):
        """Compare credentials in request to credentials in database.

        :raises AuthenticationError when no match found on database
        """
        basic_credentials = self.request.headers['authorization']
        binary_credentials = a2b_base64(basic_credentials[6:])
        email_address, password = binary_credentials.decode().split(':||:')
        acct_repository = AccountRepository(self.db)
        self.account = acct_repository.get_account_from_credentials(
                email_address,
                password
        )
        if self.account is None:
            raise AuthenticationError('provided credentials not found')
        self.access_token.account_id = self.account.id
        self.refresh_token.account_id = self.account.id 
Example #20
Source File: validate_email.py    From selene-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_email_address(self):
        if self.request.args['platform'] == 'Google':
            email_address = get_google_account_email(
                self.request.args['token']
            )
        elif self.request.args['platform'] == 'Facebook':
            email_address = get_facebook_account_email(
                self.request.args['token']
            )
        elif self.request.args['platform'] == 'GitHub':
            email_address = get_github_account_email(
                self.request.args['token']
            )
        else:
            coded_email = self.request.args['token']
            email_address = a2b_base64(coded_email).decode()

        return email_address 
Example #21
Source File: security_keys.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_dictionary_verification(self):
		test_data = {}
		for _ in range(5):
			test_data['_' + utilities.random_string(10)] = utilities.random_string(10)
		self.sk = security_keys.SigningKey.generate(curve=ecdsa.NIST521p)
		test_data = self.sk.sign_dict(test_data, signature_encoding='base64')
		self.assertIsInstance(test_data, dict)
		# make sure the 'signature' key was added
		self.assertIn('signature', test_data)
		self.assertEqual(len(test_data), 6)

		try:
			binascii.a2b_base64(test_data['signature'])
		except ValueError:
			self.fail('signature could not be decoded as base64')

		vk = self.sk.get_verifying_key()
		vk.verify_dict(test_data, signature_encoding='base64')

		test_data['_' + utilities.random_string(10)] = utilities.random_string(10)
		with self.assertRaises(ecdsa.keys.BadSignatureError):
			vk.verify_dict(test_data, signature_encoding='base64') 
Example #22
Source File: base64.py    From GDCTSCP with GNU Affero General Public License v3.0 6 votes vote down vote up
def b64decode(s, altchars=None):
    """Decode a Base64 encoded string.

    s is the string to decode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies the
    alternative alphabet used instead of the '+' and '/' characters.

    The decoded string is returned.  A TypeError is raised if s were
    incorrectly padded or if there are non-alphabet characters present in the
    string.
    """
    if altchars is not None:
        s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
    try:
        return binascii.a2b_base64(s)
    except binascii.Error, msg:
        # Transform this exception for consistency
        raise TypeError(msg) 
Example #23
Source File: pdf-parser.py    From ACE with Apache License 2.0 6 votes vote down vote up
def YARACompile(ruledata):
    if ruledata.startswith('#'):
        if ruledata.startswith('#h#'):
            rule = binascii.a2b_hex(ruledata[3:])
        elif ruledata.startswith('#b#'):
            rule = binascii.a2b_base64(ruledata[3:])
        elif ruledata.startswith('#s#'):
            rule = 'rule string {strings: $a = "%s" ascii wide nocase condition: $a}' % ruledata[3:]
        elif ruledata.startswith('#q#'):
            rule = ruledata[3:].replace("'", '"')
        else:
            rule = ruledata[1:]
        return yara.compile(source=rule)
    else:
        dFilepaths = {}
        if os.path.isdir(ruledata):
            for root, dirs, files in os.walk(ruledata):
                for file in files:
                    filename = os.path.join(root, file)
                    dFilepaths[filename] = filename
        else:
            for filename in ProcessAt(ruledata):
                dFilepaths[filename] = filename
        return yara.compile(filepaths=dFilepaths) 
Example #24
Source File: base64mime.py    From Computable with MIT License 6 votes vote down vote up
def decode(s, convert_eols=None):
    """Decode a raw base64 string.

    If convert_eols is set to a string value, all canonical email linefeeds,
    e.g. "\\r\\n", in the decoded text will be converted to the value of
    convert_eols.  os.linesep is a good choice for convert_eols if you are
    decoding a text attachment.

    This function does not parse a full MIME header value encoded with
    base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
    level email.header class for that functionality.
    """
    if not s:
        return s

    dec = a2b_base64(s)
    if convert_eols:
        return dec.replace(CRLF, convert_eols)
    return dec


# For convenience and backwards compatibility w/ standard base64 module 
Example #25
Source File: base64mime.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def decode(s, convert_eols=None):
    """Decode a raw base64 string.

    If convert_eols is set to a string value, all canonical email linefeeds,
    e.g. "\\r\\n", in the decoded text will be converted to the value of
    convert_eols.  os.linesep is a good choice for convert_eols if you are
    decoding a text attachment.

    This function does not parse a full MIME header value encoded with
    base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the high
    level email.header class for that functionality.
    """
    if not s:
        return s

    dec = a2b_base64(s)
    if convert_eols:
        return dec.replace(CRLF, convert_eols)
    return dec


# For convenience and backwards compatibility w/ standard base64 module 
Example #26
Source File: base64.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def b64decode(s, altchars=None):
    """Decode a Base64 encoded string.

    s is the string to decode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies the
    alternative alphabet used instead of the '+' and '/' characters.

    The decoded string is returned.  A TypeError is raised if s is
    incorrectly padded.  Characters that are neither in the normal base-64
    alphabet nor the alternative alphabet are discarded prior to the padding
    check.
    """
    if altchars is not None:
        s = s.translate(string.maketrans(altchars[:2], '+/'))
    try:
        return binascii.a2b_base64(s)
    except binascii.Error, msg:
        # Transform this exception for consistency
        raise TypeError(msg) 
Example #27
Source File: base64.py    From oss-ftp with MIT License 6 votes vote down vote up
def b64decode(s, altchars=None):
    """Decode a Base64 encoded string.

    s is the string to decode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies the
    alternative alphabet used instead of the '+' and '/' characters.

    The decoded string is returned.  A TypeError is raised if s were
    incorrectly padded or if there are non-alphabet characters present in the
    string.
    """
    if altchars is not None:
        s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
    try:
        return binascii.a2b_base64(s)
    except binascii.Error, msg:
        # Transform this exception for consistency
        raise TypeError(msg) 
Example #28
Source File: base64mime.py    From oss-ftp with MIT License 6 votes vote down vote up
def decode(s, convert_eols=None):
    """Decode a raw base64 string.

    If convert_eols is set to a string value, all canonical email linefeeds,
    e.g. "\\r\\n", in the decoded text will be converted to the value of
    convert_eols.  os.linesep is a good choice for convert_eols if you are
    decoding a text attachment.

    This function does not parse a full MIME header value encoded with
    base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
    level email.header class for that functionality.
    """
    if not s:
        return s

    dec = a2b_base64(s)
    if convert_eols:
        return dec.replace(CRLF, convert_eols)
    return dec


# For convenience and backwards compatibility w/ standard base64 module 
Example #29
Source File: helpers.py    From specter-desktop with MIT License 6 votes vote down vote up
def verify_password(stored_password, provided_password):
    """Verify a stored password against one provided by user"""
    pwdhash = hashlib.pbkdf2_hmac('sha256', 
                                  provided_password.encode('utf-8'), 
                                  stored_password['salt'].encode(), 
                                  10000)
    return pwdhash == binascii.a2b_base64(stored_password['pwdhash']) 
Example #30
Source File: base64.py    From Computable with MIT License 6 votes vote down vote up
def b64decode(s, altchars=None):
    """Decode a Base64 encoded string.

    s is the string to decode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies the
    alternative alphabet used instead of the '+' and '/' characters.

    The decoded string is returned.  A TypeError is raised if s were
    incorrectly padded or if there are non-alphabet characters present in the
    string.
    """
    if altchars is not None:
        s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
    try:
        return binascii.a2b_base64(s)
    except binascii.Error, msg:
        # Transform this exception for consistency
        raise TypeError(msg)