def save_pem(contents, pem_marker): """Saves a PEM file. :param contents: the contents to encode in PEM format :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-encoded content between the start and end markers, as bytes. """ (pem_start, pem_end) = _markers(pem_marker) b64 = b2a_base64(contents).replace(b"\n", b"") pem_lines = [pem_start] for block_start in range(0, len(b64), 64): block = b64[block_start:block_start + 64] pem_lines.append(block) pem_lines.append(pem_end) pem_lines.append(b"") return b"\n".join(pem_lines)
def urlsafe_b64encode(payload): """Encode bytes-like object using the URL- and filesystem-safe alphabet, which substitutes - instead of + and _ instead of / in the standard Base64 alphabet, and return the encoded bytes. :param bytes payload: bytes-like object. """ return STRING_TOOLS.translate( b2a_base64(payload)[:-1].decode("utf-8"), {ord("+"): "-", ord("/"): "_"} )
def encodebytes(toencode): """Encode a bytestring into a bytestring containing multiple lines of base-64 data.""" if not isinstance(toencode, BYTES_TYPES): raise TypeError("expected bytes, not %s" % toencode.__class__.__name__) pieces = [] for i in range(0, len(toencode), MAXBINSIZE): chunk = toencode[i:i + MAXBINSIZE] pieces.append(binascii.b2a_base64(chunk)) return b"".join(pieces)
def b64encode(toencode: bytes) -> bytes: """Encode a byte string using Base64. toencode is the byte string to encode. Optional altchars must be a byte string of length 2 which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. generate url or filesystem safe Base64 strings. The encoded byte string is returned. """ # Strip off the trailing newline return binascii.b2a_base64(toencode)[:-1]
def encode(inval, outval): """Encode a file; input and output are binary files.""" while True: read = inval.read(MAXBINSIZE) if not read: break while len(read) < MAXBINSIZE: next_read = inval.read(MAXBINSIZE - len(read)) if not next_read: break read += next_read line = binascii.b2a_base64(read) outval.write(line)
def encode(input, output): """Encode a file; input and output are binary files.""" while True: s = input.read(MAXBINSIZE) if not s: break while len(s) < MAXBINSIZE: ns = input.read(MAXBINSIZE-len(s)) if not ns: break s += ns line = binascii.b2a_base64(s) output.write(line)
def b64encode(toencode, altchars=None): """Encode a byte string using Base64. toencode is the byte string to encode. Optional altchars must be a byte string of length 2 which specifies an alternative alphabet for the '+' and '/' characters. This allows an application to e.g. generate url or filesystem safe Base64 strings. The encoded byte string is returned. """ if not isinstance(toencode, BYTES_TYPES): raise TypeError("expected bytes, not %s" % toencode.__class__.__name__) # Strip off the trailing newline encoded = binascii.b2a_base64(toencode)[:-1] if altchars is not None: if not isinstance(altchars, BYTES_TYPES): raise TypeError("expected bytes, not %s" % altchars.__class__.__name__) assert len(altchars) == 2, repr(altchars) return encoded.translate(bytes.maketrans(b"+/", altchars)) return encoded
def _csr_end(self): """Generates and returns a certificate signing request as a base64 string.""" len_issuer_subject = asn1.issuer_or_subject_length( self._country, self._state_province, self._locality, self._org, self._org_unit, self._common, ) len_sub_header = asn1.get_sequence_header_length(len_issuer_subject) len_csr_info = self._version_len + len_issuer_subject len_csr_info += len_sub_header + 91 + 2 len_csr_info_header = asn1.get_sequence_header_length(len_csr_info) # CSR Info Packet csr_info = bytearray() # Append CSR Info --> [0:2] asn1.get_sequence_header(len_csr_info, csr_info) # Append Version --> [3:5] asn1.get_version(csr_info) # Append Subject --> [6:7] asn1.get_sequence_header(len_issuer_subject, csr_info) # Append Issuer or Subject asn1.get_issuer_or_subject( csr_info, self._country, self._state_province, self._locality, self._org, self._org_unit, self._common, ) # Append Public Key asn1.get_public_key(csr_info, self._key) # Terminator csr_info += b"\xa0\x00" # Init. SHA-256 Calculation csr_info_sha_256 = bytearray(64) self._atecc.sha_start() for i in range(0, len_csr_info + len_csr_info_header, 64): chunk_len = (len_csr_info_header + len_csr_info) - i chunk_len = min(chunk_len, 64) if chunk_len == 64: self._atecc.sha_update(csr_info[i:i + 64]) else: csr_info_sha_256 = self._atecc.sha_digest(csr_info[i:]) # Sign the SHA256 Digest signature = bytearray(64) signature = self._atecc.ecdsa_sign(self._slot, csr_info_sha_256) # Calculations for signature and csr length len_signature = asn1.get_signature_length(signature) len_csr = len_csr_info_header + len_csr_info + len_signature asn1.get_sequence_header_length(len_csr) # append signature to csr csr = bytearray() asn1.get_sequence_header(len_csr, csr) # append csr_info csr += csr_info asn1.get_signature(signature, csr) # encode and return csr = b2a_base64(csr) return csr
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."