Ejemplo n.º 1
0
def decode(inval, outval):
    """Decode a file; input and output are binary files."""
    while True:
        line = inval.readline()
        if not line:
            break
        outval.write(binascii.a2b_base64(line))
Ejemplo n.º 2
0
 def urlsafe_b64decode(payload):
     """Decode bytes-like object or ASCII string using the URL
     and filesystem-safe alphabet
     :param bytes payload: bytes-like object or ASCII string
     """
     return a2b_base64(
         STRING_TOOLS._bytes_from_decode_data(payload)).decode("utf-8")
Ejemplo n.º 3
0
def decode(input, output):
    """Decode a file; input and output are binary files."""
    while True:
        line = input.readline()
        if not line:
            break
        s = binascii.a2b_base64(line)
        output.write(s)
Ejemplo n.º 4
0
def b64decode(todecode: str) -> bytes:
    """Decode a Base64 encoded byte string.

    todecode 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 todecode 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.
    """
    return binascii.a2b_base64(_bytes_from_decode_data(todecode))
Ejemplo n.º 5
0
def b64decode(todecode, altchars=None, validate=False):
    """Decode a Base64 encoded byte string.

    todecode 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 todecode 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.
    """
    todecode = _bytes_from_decode_data(todecode)
    if altchars is not None:
        altchars = _bytes_from_decode_data(altchars)
        assert len(altchars) == 2, repr(altchars)
        todecode = todecode.translate(bytes.maketrans(altchars, b"+/"))
    if validate and not re.match(b"^[A-Za-z0-9+/]*={0,2}$", todecode):
        raise binascii.Error("Non-base64 digit found")
    return binascii.a2b_base64(todecode)
Ejemplo n.º 6
0
def decodebytes(todecode):
    """Decode a bytestring of base-64 data into a bytestring."""
    if not isinstance(todecode, BYTES_TYPES):
        raise TypeError("expected bytes, not %s" % todecode.__class__.__name__)
    return binascii.a2b_base64(todecode)
Ejemplo n.º 7
0
print("-- Binary<->Hex Conversions --")
# Binary data.
data = b"CircuitPython is Awesome!"
print("Original Binary Data: ", data)

# Get the hexadecimal representation of the binary data
hex_data = hexlify(data)
print("Hex Data: ", hex_data)
# Verify data
assert (
    hex_data == b"43697263756974507974686f6e20697320417765736f6d6521",
), "hexlified data does not match expected data."
# Get the binary data represented by hex_data
bin_data = unhexlify(hex_data)
print("Binary Data: ", bin_data)
# Verify data
assert bin_data == data, "unhexlified binary data does not match original binary data."

print("-- Base64 ASCII <-> Binary Conversions --")
data = b"Blinka"
print("Original Binary Data: ", data)
# Convert binary data to a line of ASCII characters in base64 coding.
b64_ascii_data = b2a_base64(data)
print("Base64 ASCII Data: ", b64_ascii_data)
assert b64_ascii_data == b"Qmxpbmth\n", "Expected base64 coding does not match."

# Convert a block of base64 data back to binary data.
bin_data = a2b_base64(b"Qmxpbmth\n")
print("Converted b64 ASCII->Binary Data: ", bin_data)
assert bin_data == data, "Expected binary data does not match."
Ejemplo n.º 8
0
def load_pem(contents, pem_marker):
    """Loads a PEM file.

    :param contents: the contents of the file to interpret
    :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
        when your file has '-----BEGIN RSA PRIVATE KEY-----' and
        '-----END RSA PRIVATE KEY-----' markers.

    :return: the base64-decoded content between the start and end markers.

    @raise ValueError: when the content is invalid, for example when the start
        marker cannot be found.

    """

    # We want bytes, not text. If it's text, it can be converted to ASCII bytes.
    if not is_bytes(contents):
        contents = contents.encode("ascii")

    (pem_start, pem_end) = _markers(pem_marker)

    pem_lines = []
    in_pem_part = False

    for line in contents.split(b"\n"):
        line = line.strip()

        # Skip empty lines
        if not line:
            continue

        # Handle start marker
        if line == pem_start:
            if in_pem_part:
                raise ValueError('Seen start marker "%s" twice' % pem_start)

            in_pem_part = True
            continue

        # Skip stuff before first marker
        if not in_pem_part:
            continue

        # Handle end marker
        if in_pem_part and line == pem_end:
            in_pem_part = False
            break

        # Load fields
        if b":" in line:
            continue

        pem_lines.append(line)

    # Do some sanity checks
    if not pem_lines:
        raise ValueError('No PEM start marker "%s" found' % pem_start)

    if in_pem_part:
        raise ValueError('No PEM end marker "%s" found' % pem_end)

    # Base64-decode the contents
    pem = b"".join(pem_lines)
    return a2b_base64(pem)
Ejemplo n.º 9
0
def decodebytes(s):
    """Decode a bytestring of base-64 data into a bytestring."""
    if not isinstance(s, bytes_types):
        raise TypeError("expected bytes, not %s" % s.__class__.__name__)
    return binascii.a2b_base64(s)