Python base64.decodebytes() Examples

The following are 30 code examples of base64.decodebytes(). 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 base64 , or try the search function .
Example #1
Source File: read_fb2.py    From Lector with GNU General Public License v3.0 7 votes vote down vote up
def generate_book_cover(self):
        cover = None

        try:
            cover_image_xml = self.xml.find('coverpage')
            for i in cover_image_xml:
                cover_image_name = i.get('l:href')

            cover_image_data = self.xml.find_all('binary')
            for i in cover_image_data:
                if cover_image_name.endswith(i.get('id')):
                    cover = base64.decodebytes(i.text.encode())
        except (AttributeError, TypeError):
            # Catch TypeError in case no images exist in the book
            logger.warning('Cover not found: ' + self.filename)

        return cover 
Example #2
Source File: utils.py    From any-captcha with GNU General Public License v2.0 6 votes vote down vote up
def convert_gif_2_jpg(gif_base64):
        bas = base64.decodebytes(bytes(gif_base64, "utf-8"))
        im = Image.open(BytesIO(bas))
        i = 0
        mypalette = im.getpalette()
        base64_jpgs = []
        try:
            while 1:
                im.putpalette(mypalette)
                new_im = Image.new("RGB", im.size)
                new_im.paste(im)
                buffered = BytesIO()
                new_im.save(buffered, format="JPEG")
                img_data_base64 = base64.b64encode(buffered.getvalue())
                base64_jpgs.append(img_data_base64)
                i += 1
                im.seek(im.tell() + 1)

        except EOFError:
            pass

        return base64_jpgs 
Example #3
Source File: rest.py    From crnn.pytorch with Apache License 2.0 6 votes vote down vote up
def ocr_rest():
    """
    :return:
    """

    img = base64.decodebytes(request.form.get('img').encode())
    img = np.frombuffer(img, dtype=np.uint8)
    h, w = request.form.getlist('shape', type=int)
    img = img.reshape((h, w))
    # 预处理
    img = pre_process_image(img, h, w)
    # 预测
    text = inference(img, h, w)
    text = ''.join(text)
    print("text:{}".format(text))
    return {'text': text} 
Example #4
Source File: utils.py    From transistor with MIT License 6 votes vote down vote up
def png_to_file(self, filename):
    """
    Write the png to a file for viewing.
    :param filename: str(): a name to give the saved file
    :return: a saved filename.png in the img folder for viewing.
    """
    path = Path().cwd()
    data_folder = path / u'img'
    filepath = data_folder / filename

    if self.png:
        png_data = self.png.encode('utf-8')
        with open(str(filepath), 'wb') as fh:
            fh.write(base64.decodebytes(png_data))
            print(f'Saved to {filepath}')
    print(f'self.png is None')
    return None 
Example #5
Source File: fsmanager.py    From jupyter-fs with Apache License 2.0 6 votes vote down vote up
def _save_file(self, path, content, format):
        """Save content of a generic file."""
        if format not in {'text', 'base64'}:
            raise web.HTTPError(
                400,
                "Must specify format of file contents as 'text' or 'base64'",
            )
        try:
            if format == 'text':
                bcontent = content.encode('utf8')
            else:
                b64_bytes = content.encode('ascii')
                bcontent = decodebytes(b64_bytes)
        except Exception as e:
            raise web.HTTPError(
                400, u'Encoding error saving %s: %s' % (path, e)
            )

        if format == 'text':
            self._pyfilesystem_instance.writebytes(path, bcontent)
        else:
            self._pyfilesystem_instance.writebytes(path, bcontent) 
Example #6
Source File: test_base64.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_decodebytes(self):
        eq = self.assertEqual
        eq(base64.decodebytes(b"d3d3LnB5dGhvbi5vcmc=\n"), b"www.python.org")
        eq(base64.decodebytes(b"YQ==\n"), b"a")
        eq(base64.decodebytes(b"YWI=\n"), b"ab")
        eq(base64.decodebytes(b"YWJj\n"), b"abc")
        eq(base64.decodebytes(b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
                               b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
                               b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n"),
           b"abcdefghijklmnopqrstuvwxyz"
           b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
           b"0123456789!@#0^&*();:<>,. []{}")
        eq(base64.decodebytes(b''), b'')
        # Non-bytes
        eq(base64.decodebytes(bytearray(b'YWJj\n')), b'abc')
        eq(base64.decodebytes(memoryview(b'YWJj\n')), b'abc')
        eq(base64.decodebytes(array('B', b'YWJj\n')), b'abc')
        self.check_type_errors(base64.decodebytes) 
Example #7
Source File: test_gettext.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        if not os.path.isdir(LOCALEDIR):
            os.makedirs(LOCALEDIR)
        with open(MOFILE, 'wb') as fp:
            fp.write(base64.decodebytes(GNU_MO_DATA))
        with open(MOFILE_BAD_MAJOR_VERSION, 'wb') as fp:
            fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MAJOR_VERSION))
        with open(MOFILE_BAD_MINOR_VERSION, 'wb') as fp:
            fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MINOR_VERSION))
        with open(UMOFILE, 'wb') as fp:
            fp.write(base64.decodebytes(UMO_DATA))
        with open(MMOFILE, 'wb') as fp:
            fp.write(base64.decodebytes(MMO_DATA))
        self.env = support.EnvironmentVarGuard()
        self.env['LANGUAGE'] = 'xx'
        gettext._translations.clear() 
Example #8
Source File: request.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def open_data(self, url, data=None):
        """Use "data" URL."""
        if not isinstance(url, str):
            raise URLError('data error: proxy support for data protocol currently not implemented')
        # ignore POSTed data
        #
        # syntax of data URLs:
        # dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
        # mediatype := [ type "/" subtype ] *( ";" parameter )
        # data      := *urlchar
        # parameter := attribute "=" value
        try:
            [type, data] = url.split(',', 1)
        except ValueError:
            raise IOError('data error', 'bad data URL')
        if not type:
            type = 'text/plain;charset=US-ASCII'
        semi = type.rfind(';')
        if semi >= 0 and '=' not in type[semi:]:
            encoding = type[semi+1:]
            type = type[:semi]
        else:
            encoding = ''
        msg = []
        msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                            time.gmtime(time.time())))
        msg.append('Content-type: %s' % type)
        if encoding == 'base64':
            # XXX is this encoding/decoding ok?
            data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
        else:
            data = unquote(data)
        msg.append('Content-Length: %d' % len(data))
        msg.append('')
        msg.append(data)
        msg = '\n'.join(msg)
        headers = email.message_from_string(msg)
        f = io.StringIO(msg)
        #f.fileno = None     # needed for addinfourl
        return addinfourl(f, headers, url) 
Example #9
Source File: request.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def open_data(self, url, data=None):
        """Use "data" URL."""
        if not isinstance(url, str):
            raise URLError('data error: proxy support for data protocol currently not implemented')
        # ignore POSTed data
        #
        # syntax of data URLs:
        # dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
        # mediatype := [ type "/" subtype ] *( ";" parameter )
        # data      := *urlchar
        # parameter := attribute "=" value
        try:
            [type, data] = url.split(',', 1)
        except ValueError:
            raise IOError('data error', 'bad data URL')
        if not type:
            type = 'text/plain;charset=US-ASCII'
        semi = type.rfind(';')
        if semi >= 0 and '=' not in type[semi:]:
            encoding = type[semi+1:]
            type = type[:semi]
        else:
            encoding = ''
        msg = []
        msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                            time.gmtime(time.time())))
        msg.append('Content-type: %s' % type)
        if encoding == 'base64':
            # XXX is this encoding/decoding ok?
            data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
        else:
            data = unquote(data)
        msg.append('Content-Length: %d' % len(data))
        msg.append('')
        msg.append(data)
        msg = '\n'.join(msg)
        headers = email.message_from_string(msg)
        f = io.StringIO(msg)
        #f.fileno = None     # needed for addinfourl
        return addinfourl(f, headers, url) 
Example #10
Source File: community.py    From py-ipv8 with GNU Lesser General Public License v3.0 6 votes vote down vote up
def on_request_attestation(self, peer, dist, payload):
        """
        Someone wants us to attest their attribute.
        """
        metadata = json.loads(payload.metadata)
        attribute = metadata.pop('attribute')
        pubkey_b64 = cast_to_bin(metadata.pop('public_key'))
        id_format = metadata.pop('id_format')
        id_algorithm = self.get_id_algorithm(id_format)

        value = await maybe_coroutine(self.attestation_request_callback, peer, attribute, metadata)
        if value is None:
            return

        PK = id_algorithm.load_public_key(decodebytes(pubkey_b64))
        attestation_blob = id_algorithm.attest(PK, value)
        attestation = id_algorithm.get_attestation_class().unserialize(attestation_blob, id_format)

        self.attestation_request_complete_callback(peer, attribute, attestation.get_hash(), id_format)

        self.send_attestation(peer.address, attestation_blob, dist.global_time) 
Example #11
Source File: subtitles.py    From SubCrawl with MIT License 6 votes vote down vote up
def _write_file(self, byte_data: str, subtitle_path: str):
        """
        Encode the byte_data string to bytes (since it's not in byte format by default) and write it to a .gzip
        file. Unzip the content of the .gzip file and write it outside (unzipped).

        :param byte_data: (string) string containing bytecode information
                                        ATTENTION: variable is not byte encoded, which is why it is done in this method
        :param subtitle_path: (string) absolute path where to write the subtitle
        """
        with open(subtitle_path, "wb") as subtitle_file:
            subtitle_file.write(base64.decodebytes(byte_data.encode()))

        # Open and read the compressed file and write it outside
        with gzip.open(subtitle_path, 'rb') as gzip_file:
            content = gzip_file.read()
            # Removes the ".gzip" extension
            with open(subtitle_path[:-4], 'wb') as srt_file:
                srt_file.write(content)

        self.downloaded_files += 1
        # Remove the .gzip file
        os.remove(subtitle_path) 
Example #12
Source File: request.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def open_data(self, url, data=None):
        """Use "data" URL."""
        if not isinstance(url, str):
            raise URLError('data error: proxy support for data protocol currently not implemented')
        # ignore POSTed data
        #
        # syntax of data URLs:
        # dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
        # mediatype := [ type "/" subtype ] *( ";" parameter )
        # data      := *urlchar
        # parameter := attribute "=" value
        try:
            [type, data] = url.split(',', 1)
        except ValueError:
            raise IOError('data error', 'bad data URL')
        if not type:
            type = 'text/plain;charset=US-ASCII'
        semi = type.rfind(';')
        if semi >= 0 and '=' not in type[semi:]:
            encoding = type[semi+1:]
            type = type[:semi]
        else:
            encoding = ''
        msg = []
        msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                            time.gmtime(time.time())))
        msg.append('Content-type: %s' % type)
        if encoding == 'base64':
            # XXX is this encoding/decoding ok?
            data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
        else:
            data = unquote(data)
        msg.append('Content-Length: %d' % len(data))
        msg.append('')
        msg.append(data)
        msg = '\n'.join(msg)
        headers = email.message_from_string(msg)
        f = io.StringIO(msg)
        #f.fileno = None     # needed for addinfourl
        return addinfourl(f, headers, url) 
Example #13
Source File: test_simplification.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_start_with_moveto():
    # Should be entirely clipped away to a single MOVETO
    data = b"""
ZwAAAAku+v9UAQAA+Tj6/z8CAADpQ/r/KAMAANlO+v8QBAAAyVn6//UEAAC6ZPr/2gUAAKpv+v+8
BgAAm3r6/50HAACLhfr/ewgAAHyQ+v9ZCQAAbZv6/zQKAABepvr/DgsAAE+x+v/lCwAAQLz6/7wM
AAAxx/r/kA0AACPS+v9jDgAAFN36/zQPAAAF6Pr/AxAAAPfy+v/QEAAA6f36/5wRAADbCPv/ZhIA
AMwT+/8uEwAAvh77//UTAACwKfv/uRQAAKM0+/98FQAAlT/7/z0WAACHSvv//RYAAHlV+/+7FwAA
bGD7/3cYAABea/v/MRkAAFF2+//pGQAARIH7/6AaAAA3jPv/VRsAACmX+/8JHAAAHKL7/7ocAAAP
rfv/ah0AAAO4+/8YHgAA9sL7/8QeAADpzfv/bx8AANzY+/8YIAAA0OP7/78gAADD7vv/ZCEAALf5
+/8IIgAAqwT8/6kiAACeD/z/SiMAAJIa/P/oIwAAhiX8/4QkAAB6MPz/HyUAAG47/P+4JQAAYkb8
/1AmAABWUfz/5SYAAEpc/P95JwAAPmf8/wsoAAAzcvz/nCgAACd9/P8qKQAAHIj8/7cpAAAQk/z/
QyoAAAWe/P/MKgAA+aj8/1QrAADus/z/2isAAOO+/P9eLAAA2Mn8/+AsAADM1Pz/YS0AAMHf/P/g
LQAAtur8/10uAACr9fz/2C4AAKEA/f9SLwAAlgv9/8ovAACLFv3/QDAAAIAh/f+1MAAAdSz9/ycx
AABrN/3/mDEAAGBC/f8IMgAAVk39/3UyAABLWP3/4TIAAEFj/f9LMwAANm79/7MzAAAsef3/GjQA
ACKE/f9+NAAAF4/9/+E0AAANmv3/QzUAAAOl/f+iNQAA+a/9/wA2AADvuv3/XDYAAOXF/f+2NgAA
29D9/w83AADR2/3/ZjcAAMfm/f+7NwAAvfH9/w44AACz/P3/XzgAAKkH/v+vOAAAnxL+//04AACW
Hf7/SjkAAIwo/v+UOQAAgjP+/905AAB5Pv7/JDoAAG9J/v9pOgAAZVT+/606AABcX/7/7zoAAFJq
/v8vOwAASXX+/207AAA/gP7/qjsAADaL/v/lOwAALZb+/x48AAAjof7/VTwAABqs/v+LPAAAELf+
/788AAAHwv7/8TwAAP7M/v8hPQAA9df+/1A9AADr4v7/fT0AAOLt/v+oPQAA2fj+/9E9AADQA///
+T0AAMYO//8fPgAAvRn//0M+AAC0JP//ZT4AAKsv//+GPgAAojr//6U+AACZRf//wj4AAJBQ///d
PgAAh1v///c+AAB+Zv//Dz8AAHRx//8lPwAAa3z//zk/AABih///TD8AAFmS//9dPwAAUJ3//2w/
AABHqP//ej8AAD6z//+FPwAANb7//48/AAAsyf//lz8AACPU//+ePwAAGt///6M/AAAR6v//pj8A
AAj1//+nPwAA/////w=="""

    verts = np.fromstring(base64.decodebytes(data), dtype='<i4')
    verts = verts.reshape((len(verts) // 2, 2))
    path = Path(verts)
    segs = path.iter_segments(transforms.IdentityTransform(),
                              clip=(0.0, 0.0, 100.0, 100.0))
    segs = list(segs)
    assert len(segs) == 1
    assert segs[0][1] == Path.MOVETO 
Example #14
Source File: request.py    From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 5 votes vote down vote up
def open_data(self, url, data=None):
        """Use "data" URL."""
        if not isinstance(url, str):
            raise URLError('data error: proxy support for data protocol currently not implemented')
        # ignore POSTed data
        #
        # syntax of data URLs:
        # dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
        # mediatype := [ type "/" subtype ] *( ";" parameter )
        # data      := *urlchar
        # parameter := attribute "=" value
        try:
            [type, data] = url.split(',', 1)
        except ValueError:
            raise IOError('data error', 'bad data URL')
        if not type:
            type = 'text/plain;charset=US-ASCII'
        semi = type.rfind(';')
        if semi >= 0 and '=' not in type[semi:]:
            encoding = type[semi+1:]
            type = type[:semi]
        else:
            encoding = ''
        msg = []
        msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                            time.gmtime(time.time())))
        msg.append('Content-type: %s' % type)
        if encoding == 'base64':
            # XXX is this encoding/decoding ok?
            data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
        else:
            data = unquote(data)
        msg.append('Content-Length: %d' % len(data))
        msg.append('')
        msg.append(data)
        msg = '\n'.join(msg)
        headers = email.message_from_string(msg)
        f = io.StringIO(msg)
        #f.fileno = None     # needed for addinfourl
        return addinfourl(f, headers, url) 
Example #15
Source File: constructor.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def construct_python_bytes(self, node):
        try:
            value = self.construct_scalar(node).encode('ascii')
        except UnicodeEncodeError as exc:
            raise ConstructorError(None, None,
                    "failed to convert base64 data into ascii: %s" % exc,
                    node.start_mark)
        try:
            if hasattr(base64, 'decodebytes'):
                return base64.decodebytes(value)
            else:
                return base64.decodestring(value)
        except binascii.Error as exc:
            raise ConstructorError(None, None,
                    "failed to decode base64 data: %s" % exc, node.start_mark) 
Example #16
Source File: base64_codec.py    From Imogen with MIT License 5 votes vote down vote up
def base64_decode(input, errors='strict'):
    assert errors == 'strict'
    return (base64.decodebytes(input), len(input)) 
Example #17
Source File: smtplib.py    From Imogen with MIT License 5 votes vote down vote up
def auth(self, mechanism, authobject, *, initial_response_ok=True):
        """Authentication command - requires response processing.

        'mechanism' specifies which authentication mechanism is to
        be used - the valid values are those listed in the 'auth'
        element of 'esmtp_features'.

        'authobject' must be a callable object taking a single argument:

                data = authobject(challenge)

        It will be called to process the server's challenge response; the
        challenge argument it is passed will be a bytes.  It should return
        an ASCII string that will be base64 encoded and sent to the server.

        Keyword arguments:
            - initial_response_ok: Allow sending the RFC 4954 initial-response
              to the AUTH command, if the authentication methods supports it.
        """
        # RFC 4954 allows auth methods to provide an initial response.  Not all
        # methods support it.  By definition, if they return something other
        # than None when challenge is None, then they do.  See issue #15014.
        mechanism = mechanism.upper()
        initial_response = (authobject() if initial_response_ok else None)
        if initial_response is not None:
            response = encode_base64(initial_response.encode('ascii'), eol='')
            (code, resp) = self.docmd("AUTH", mechanism + " " + response)
        else:
            (code, resp) = self.docmd("AUTH", mechanism)
        # If server responds with a challenge, send the response.
        if code == 334:
            challenge = base64.decodebytes(resp)
            response = encode_base64(
                authobject(challenge).encode('ascii'), eol='')
            (code, resp) = self.docmd(response)
        if code in (235, 503):
            return (code, resp)
        raise SMTPAuthenticationError(code, resp) 
Example #18
Source File: base64_codec.py    From Imogen with MIT License 5 votes vote down vote up
def decode(self, input, final=False):
        assert self.errors == 'strict'
        return base64.decodebytes(input) 
Example #19
Source File: constructor.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def construct_yaml_binary(self, node):
        try:
            value = self.construct_scalar(node).encode('ascii')
        except UnicodeEncodeError as exc:
            raise ConstructorError(None, None,
                    "failed to convert base64 data into ascii: %s" % exc,
                    node.start_mark)
        try:
            if hasattr(base64, 'decodebytes'):
                return base64.decodebytes(value)
            else:
                return base64.decodestring(value)
        except binascii.Error as exc:
            raise ConstructorError(None, None,
                    "failed to decode base64 data: %s" % exc, node.start_mark) 
Example #20
Source File: client.py    From Imogen with MIT License 5 votes vote down vote up
def decode(self, data):
        self.data = base64.decodebytes(data) 
Example #21
Source File: base64_codec.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def decode(self, input, final=False):
        assert self.errors == 'strict'
        return base64.decodebytes(input) 
Example #22
Source File: base64_codec.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def base64_decode(input, errors='strict'):
    assert errors == 'strict'
    return (base64.decodebytes(input), len(input)) 
Example #23
Source File: base64_codec.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def base64_decode(input, errors='strict'):
    assert errors == 'strict'
    return (base64.decodebytes(input), len(input)) 
Example #24
Source File: client.py    From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 5 votes vote down vote up
def getparser(use_datetime=False, use_builtin_types=False):
    """getparser() -> parser, unmarshaller

    Create an instance of the fastest available parser, and attach it
    to an unmarshalling object.  Return both objects.
    """
    if FastParser and FastUnmarshaller:
        if use_builtin_types:
            mkdatetime = _datetime_type
            mkbytes = base64.decodebytes
        elif use_datetime:
            mkdatetime = _datetime_type
            mkbytes = _binary
        else:
            mkdatetime = _datetime
            mkbytes = _binary
        target = FastUnmarshaller(True, False, mkbytes, mkdatetime, Fault)
        parser = FastParser(target)
    else:
        target = Unmarshaller(use_datetime=use_datetime, use_builtin_types=use_builtin_types)
        if FastParser:
            parser = FastParser(target)
        else:
            parser = ExpatParser(target)
    return parser, target

##
# Convert a Python tuple or a Fault instance to an XML-RPC packet.
#
# @def dumps(params, **options)
# @param params A tuple or Fault instance.
# @keyparam methodname If given, create a methodCall request for
#     this method name.
# @keyparam methodresponse If given, create a methodResponse packet.
#     If used with a tuple, the tuple must be a singleton (that is,
#     it must contain exactly one element).
# @keyparam encoding The packet encoding.
# @return A string containing marshalled data. 
Example #25
Source File: client.py    From kgsgo-dataset-preprocessor with Mozilla Public License 2.0 5 votes vote down vote up
def decode(self, data):
        self.data = base64.decodebytes(data) 
Example #26
Source File: AliPay.py    From django-RESTfulAPI with MIT License 5 votes vote down vote up
def _verify(self, raw_content, signature):
        # 开始计算签名
        key = self.alipay_public_key
        signer = PKCS1_v1_5.new(key)
        digest = SHA256.new()
        digest.update(raw_content.encode("utf8"))
        if signer.verify(digest, decodebytes(signature.encode("utf8"))):
            return True
        return False 
Example #27
Source File: test_serialization.py    From py-ipv8 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_public_to_pem(self):
        """
        Check if public keys can be serialized and loaded correctly in PEM format.
        """
        public_pem = self.key.pub().key_to_pem()

        # Convert the PEM to a DER keystring
        prefix = "-----BEGIN PUBLIC KEY-----\n"
        postfix = "-----END PUBLIC KEY-----\n"
        keystring = decodebytes(public_pem[len(prefix):-len(postfix)])

        # Reconstruct a key with this keystring
        key = M2CryptoPK(keystring=keystring)

        self.assertEqual(public_pem, key.key_to_pem()) 
Example #28
Source File: test_serialization.py    From py-ipv8 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_private_to_pem(self):
        """
        Check if keys can be serialized and loaded correctly in PEM format.
        """
        private_pem = self.key.key_to_pem()

        # Convert the PEM to a DER keystring
        prefix = "-----BEGIN EC PRIVATE KEY-----\n"
        postfix = "-----END EC PRIVATE KEY-----\n"
        keystring = decodebytes(private_pem[len(prefix):-len(postfix)])

        # Reconstruct a key with this keystring
        key = M2CryptoSK(keystring=keystring)

        self.assertEqual(private_pem, key.key_to_pem()) 
Example #29
Source File: m2crypto.py    From py-ipv8 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def pem_to_bin(self, pem):
        """
        Convert a key in the PEM format into a key in the binary format.
        @note: Encrypted pem's are NOT supported and will silently fail.
        """
        return decodebytes(b"".join(pem.split(b"\n")[1:-2])) 
Example #30
Source File: users.py    From onec_dtools with MIT License 5 votes vote down vote up
def extract_hashes(text):
    """
    Получает SHA1 хэши паролей пользователей из расшифрованных данных поля DATA

    :param text: расшифрованное поле DATA
    :return: кортеж хэшей: (SHA1(pwd), SHA1(TO_UPPER(pwd))
    """
    result = re.search('\d+,\d+,"(\S+)","(\S+)",\d+,\d+', text)
    if result is None:
        return
    return tuple([''.join('{:02x}'.format(byte) for byte in base64.decodebytes(x.encode())) for x in result.groups()])