Python codecs.encode() Examples

The following are 30 code examples of codecs.encode(). 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 codecs , or try the search function .
Example #1
Source File: types.py    From IOTA_demo with MIT License 6 votes vote down vote up
def random(cls, length):
    # type: (int) -> TryteString
    """
    Generates a random sequence of trytes.

    :param length:
      Number of trytes to generate.
    """
    alphabet  = list(itervalues(AsciiTrytesCodec.alphabet))
    generator = SystemRandom()

    # :py:meth:`SystemRandom.choices` wasn't added until Python 3.6;
    # for compatibility, we will continue to use ``choice`` in a loop.
    # https://docs.python.org/3/library/random.html#random.choices
    return cls(
      ''.join(chr(generator.choice(alphabet)) for _ in range(length))
        .encode('ascii')
    ) 
Example #2
Source File: blitz.ip2tor.py    From raspiblitz with MIT License 6 votes vote down vote up
def lndPayInvoice(lnInvoiceString):
    try:
        # call LND GRPC API
        macaroon = codecs.encode(open(LND_ADMIN_MACAROON_PATH, 'rb').read(), 'hex')
        os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'
        cert = open(LND_TLS_PATH, 'rb').read()
        ssl_creds = grpc.ssl_channel_credentials(cert)
        channel = grpc.secure_channel("{0}:10009".format(LND_IP), ssl_creds)
        stub = rpcstub.LightningStub(channel)
        request = lnrpc.SendRequest(
            payment_request=lnInvoiceString,
        )
        response = stub.SendPaymentSync(request, metadata=[('macaroon', macaroon)])

        # validate results
        if len(response.payment_error) > 0:
            print("error='PAYMENT FAILED'")
            print("error_detail='{}'".format(response.payment_error))
            return  

    except Exception as e:
       print("error='FAILED LND INVOICE PAYMENT'")
       return

    return response 
Example #3
Source File: blitz.ip2tor.py    From raspiblitz with MIT License 6 votes vote down vote up
def lndDecodeInvoice(lnInvoiceString):
    try:
        # call LND GRPC API
        macaroon = codecs.encode(open(LND_ADMIN_MACAROON_PATH, 'rb').read(), 'hex')
        os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'
        cert = open(LND_TLS_PATH, 'rb').read()
        ssl_creds = grpc.ssl_channel_credentials(cert)
        channel = grpc.secure_channel("{0}:10009".format(LND_IP), ssl_creds)
        stub = rpcstub.LightningStub(channel)
        request = lnrpc.PayReqString(
            pay_req=lnInvoiceString,
        )
        response = stub.DecodePayReq(request, metadata=[('macaroon', macaroon)])

        # validate results
        if response.num_msat <= 0:
            print("error='ZERO INVOICES NOT ALLOWED'")
            return  

    except Exception as e:
        print("error='FAILED LND INVOICE DECODING'")
        return

    return response 
Example #4
Source File: inputs.py    From inputs with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __get_vibration_code(self, left_motor, right_motor, duration):
        """This is some crazy voodoo, if you can simplify it, please do."""
        inner_event = struct.pack(
            '2h6x2h2x2H28x',
            0x50,
            -1,
            duration,
            0,
            int(left_motor * 65535),
            int(right_motor * 65535))
        buf_conts = ioctl(self._write_device, 1076905344, inner_event)
        return int(codecs.encode(buf_conts[1:3], 'hex'), 16) 
Example #5
Source File: gipc.py    From gipc with MIT License 6 votes vote down vote up
def __init__(self):
        global _all_handles
        # Generate label of text/unicode type from three random bytes.
        self._id = codecs.encode(os.urandom(3), "hex_codec").decode("ascii")
        self._legit_pid = os.getpid()
        self._make_nonblocking()

        # Define lock for synchronizing access to this handle within the current
        # process. Note that a `gevent.lock.Semaphore` instance lives on the
        # heap of the current process and cannot be used to synchronize access
        # across multiple processes. That is, this lock is only meaningful in
        # the current process. This is especially important to consider when the
        # platform supports fork()ing.
        self._lock = gevent.lock.Semaphore(value=1)
        self._closed = False
        _all_handles.append(self) 
Example #6
Source File: security.py    From recruit with Apache License 2.0 6 votes vote down vote up
def pbkdf2_hex(
    data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS, keylen=None, hashfunc=None
):
    """Like :func:`pbkdf2_bin`, but returns a hex-encoded string.

    .. versionadded:: 0.9

    :param data: the data to derive.
    :param salt: the salt for the derivation.
    :param iterations: the number of iterations.
    :param keylen: the length of the resulting key.  If not provided,
                   the digest size will be used.
    :param hashfunc: the hash function to use.  This can either be the
                     string name of a known hash function, or a function
                     from the hashlib module.  Defaults to sha256.
    """
    rv = pbkdf2_bin(data, salt, iterations, keylen, hashfunc)
    return to_native(codecs.encode(rv, "hex_codec")) 
Example #7
Source File: dokuwiki.py    From yamdwe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make_dokuwiki_pagename(mediawiki_name):
    """
    Convert a canonical mediawiki pagename to a dokuwiki pagename

    Any namespacing that is in the form of a / is replaced with a :
    """
    result = mediawiki_name.replace(" ","_")
    # We have pages that have ':' in them - replace with underscores
    result = result.replace(':', '_')
    result = names.clean_id(camel_to_underscore(result)).replace("/",":")
    # Some of our mediawiki page names begin with a '/', which results in os.path.join assuming the page is an absolute path.
    if result[0] == ':':
      result = result.lstrip(':')
    # Fix any pages that began with a space, because that breaks dokuwiki
    result = result.replace(":_", ":")
    result = codecs.encode(result, sys.getfilesystemencoding(), "replace")
    return result 
Example #8
Source File: security.py    From jbox with MIT License 6 votes vote down vote up
def pbkdf2_hex(data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS,
               keylen=None, hashfunc=None):
    """Like :func:`pbkdf2_bin`, but returns a hex-encoded string.

    .. versionadded:: 0.9

    :param data: the data to derive.
    :param salt: the salt for the derivation.
    :param iterations: the number of iterations.
    :param keylen: the length of the resulting key.  If not provided,
                   the digest size will be used.
    :param hashfunc: the hash function to use.  This can either be the
                     string name of a known hash function, or a function
                     from the hashlib module.  Defaults to sha1.
    """
    rv = pbkdf2_bin(data, salt, iterations, keylen, hashfunc)
    return to_native(codecs.encode(rv, 'hex_codec')) 
Example #9
Source File: credstash.py    From credstash with Apache License 2.0 6 votes vote down vote up
def seal_aes_ctr_legacy(key_service, secret, digest_method=DEFAULT_DIGEST):
    """
    Encrypts `secret` using the key service.
    You can decrypt with the companion method `open_aes_ctr_legacy`.
    """
    # generate a a 64 byte key.
    # Half will be for data encryption, the other half for HMAC
    key, encoded_key = key_service.generate_key_data(64)
    ciphertext, hmac = _seal_aes_ctr(
        secret, key, LEGACY_NONCE, digest_method,
    )
    return {
        'key': b64encode(encoded_key).decode('utf-8'),
        'contents': b64encode(ciphertext).decode('utf-8'),
        'hmac': codecs.encode(hmac, "hex_codec"),
        'digest': digest_method,
    } 
Example #10
Source File: benchmark.py    From python-tabulate with MIT License 6 votes vote down vote up
def benchmark(n):
    global methods
    if '--onlyself' in sys.argv[1:]:
        methods = [ m for m in methods if m[0].startswith("tabulate") ]
    else:
        methods = methods

    results = [(desc, timeit(code, setup_code, number=n)/n * 1e6)
               for desc, code in methods]
    mintime = min(map(lambda x: x[1], results))
    results = [(desc, t, t/mintime) for desc, t in
               sorted(results, key=lambda x: x[1])]
    table = tabulate.tabulate(results,
                              [u"Table formatter", u"time, μs", u"rel. time"],
                              u"rst", floatfmt=".1f")
    print codecs.encode(table, "utf-8") 
Example #11
Source File: security.py    From lambda-packs with MIT License 6 votes vote down vote up
def pbkdf2_hex(data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS,
               keylen=None, hashfunc=None):
    """Like :func:`pbkdf2_bin`, but returns a hex-encoded string.

    .. versionadded:: 0.9

    :param data: the data to derive.
    :param salt: the salt for the derivation.
    :param iterations: the number of iterations.
    :param keylen: the length of the resulting key.  If not provided,
                   the digest size will be used.
    :param hashfunc: the hash function to use.  This can either be the
                     string name of a known hash function, or a function
                     from the hashlib module.  Defaults to sha256.
    """
    rv = pbkdf2_bin(data, salt, iterations, keylen, hashfunc)
    return to_native(codecs.encode(rv, 'hex_codec')) 
Example #12
Source File: obfuscate_strings.py    From macro_pack with Apache License 2.0 6 votes vote down vote up
def _maskStrings(self,macroLines, newFunctionName):
        """ Mask string in VBA by encoding them """
        # Find strings and replace them by hex encoded version
        for n,line in enumerate(macroLines):
            #Check if string is not preprocessor instruction, const or contain escape quoting
            if line.lstrip() != "" and line.lstrip()[0] != '#' and  "Const" not in line and  "\"\"" not in line and "PtrSafe Function" not in line and "Declare Function" not in line and "PtrSafe Sub" not in line and "Declare Sub" not in line and "Environ" not in line:
                # Find strings in line
                findList = re.findall( r'"(.+?)"', line, re.I) 
                if findList:
                    for detectedString in findList: 
                        # Hex encode string
                        encodedBytes = codecs.encode(bytes(detectedString, "utf-8"), 'hex_codec')
                        newStr = newFunctionName + "(\"" + encodedBytes.decode("utf-8")  + "\")"
                        wordToReplace =  "\"" + detectedString + "\""
                        line = line.replace(wordToReplace, newStr)
                # Replace line if result is not too big
                if len(line) < 1024:
                    macroLines[n] = line
        
        return macroLines 
Example #13
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_bug1098990_b(self):
        s1 = u"aaaaaaaaaaaaaaaaaaaaaaaa\r\n"
        s2 = u"bbbbbbbbbbbbbbbbbbbbbbbb\r\n"
        s3 = u"stillokay:bbbbxx\r\n"
        s4 = u"broken!!!!badbad\r\n"
        s5 = u"againokay.\r\n"

        s = (s1+s2+s3+s4+s5).encode(self.encoding)
        stream = StringIO.StringIO(s)
        reader = codecs.getreader(self.encoding)(stream)
        self.assertEqual(reader.readline(), s1)
        self.assertEqual(reader.readline(), s2)
        self.assertEqual(reader.readline(), s3)
        self.assertEqual(reader.readline(), s4)
        self.assertEqual(reader.readline(), s5)
        self.assertEqual(reader.readline(), u"") 
Example #14
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_ascii(self):
        # Set D (directly encoded characters)
        set_d = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                 'abcdefghijklmnopqrstuvwxyz'
                 '0123456789'
                 '\'(),-./:?')
        self.assertEqual(set_d.encode(self.encoding), set_d)
        self.assertEqual(set_d.decode(self.encoding), set_d)
        # Set O (optional direct characters)
        set_o = ' !"#$%&*;<=>@[]^_`{|}'
        self.assertEqual(set_o.encode(self.encoding), set_o)
        self.assertEqual(set_o.decode(self.encoding), set_o)
        # +
        self.assertEqual(u'a+b'.encode(self.encoding), 'a+-b')
        self.assertEqual('a+-b'.decode(self.encoding), u'a+b')
        # White spaces
        ws = ' \t\n\r'
        self.assertEqual(ws.encode(self.encoding), ws)
        self.assertEqual(ws.decode(self.encoding), ws)
        # Other ASCII characters
        other_ascii = ''.join(sorted(set(chr(i) for i in range(0x80)) -
                                     set(set_d + set_o + '+' + ws)))
        self.assertEqual(other_ascii.encode(self.encoding),
                         '+AAAAAQACAAMABAAFAAYABwAIAAsADAAOAA8AEAARABIAEwAU'
                         'ABUAFgAXABgAGQAaABsAHAAdAB4AHwBcAH4Afw-') 
Example #15
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_all(self):
        api = (
            "encode", "decode",
            "register", "CodecInfo", "Codec", "IncrementalEncoder",
            "IncrementalDecoder", "StreamReader", "StreamWriter", "lookup",
            "getencoder", "getdecoder", "getincrementalencoder",
            "getincrementaldecoder", "getreader", "getwriter",
            "register_error", "lookup_error",
            "strict_errors", "replace_errors", "ignore_errors",
            "xmlcharrefreplace_errors", "backslashreplace_errors",
            "open", "EncodedFile",
            "iterencode", "iterdecode",
            "BOM", "BOM_BE", "BOM_LE",
            "BOM_UTF8", "BOM_UTF16", "BOM_UTF16_BE", "BOM_UTF16_LE",
            "BOM_UTF32", "BOM_UTF32_BE", "BOM_UTF32_LE",
            "BOM32_BE", "BOM32_LE", "BOM64_BE", "BOM64_LE",  # Undocumented
            "StreamReaderWriter", "StreamRecoder",
        )
        self.assertEqual(sorted(api), sorted(codecs.__all__))
        for api in codecs.__all__:
            getattr(codecs, api) 
Example #16
Source File: base_client.py    From lnd_grpc with MIT License 6 votes vote down vote up
def macaroon(self):
        """
        try to open the macaroon and return it as a byte string
        """
        try:
            with open(self.macaroon_path, "rb") as f:
                macaroon_bytes = f.read()
                macaroon = codecs.encode(macaroon_bytes, "hex")
                return macaroon
        except FileNotFoundError:
            sys.stderr.write(
                f"Could not find macaroon in {self.macaroon_path}. This might happen"
                f"in versions of lnd < v0.5-beta or those not using default"
                f"installation path. Set client object's macaroon_path attribute"
                f"manually."
            ) 
Example #17
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_bug691291(self):
        # Files are always opened in binary mode, even if no binary mode was
        # specified.  This means that no automatic conversion of '\n' is done
        # on reading and writing.
        s1 = u'Hello\r\nworld\r\n'

        s = s1.encode(self.encoding)
        self.addCleanup(test_support.unlink, test_support.TESTFN)
        with open(test_support.TESTFN, 'wb') as fp:
            fp.write(s)
        with codecs.open(test_support.TESTFN, 'U', encoding=self.encoding) as reader:
            self.assertEqual(reader.read(), s1) 
Example #18
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_only_one_bom(self):
        _,_,reader,writer = codecs.lookup(self.encoding)
        # encode some stream
        s = StringIO.StringIO()
        f = writer(s)
        f.write(u"spam")
        f.write(u"spam")
        d = s.getvalue()
        # check whether there is exactly one BOM in it
        self.assertTrue(d == self.spamle or d == self.spambe)
        # try to read it back
        s = StringIO.StringIO(d)
        f = reader(s)
        self.assertEqual(f.read(), u"spamspam") 
Example #19
Source File: bytes.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x):
        try:
            return codecs.encode(x, self.codec, "strict")
        except UnicodeEncodeError:
            raise PFARuntimeException("invalid string", self.errcodeBase + 0, self.name, pos) 
Example #20
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_simple(self):
        self.assertEqual(u"\U00010203".encode(self.encoding), "\x03\x02\x01\x00") 
Example #21
Source File: string.py    From py-solc with MIT License 5 votes vote down vote up
def force_bytes(value, encoding='iso-8859-1'):
    if is_bytes(value):
        return bytes(value)
    elif is_text(value):
        return codecs.encode(value, encoding)
    else:
        raise TypeError("Unsupported type: {0}".format(type(value))) 
Example #22
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_bug1098990_a(self):
        s1 = u"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\r\n"
        s2 = u"offending line: ladfj askldfj klasdj fskla dfzaskdj fasklfj laskd fjasklfzzzzaa%whereisthis!!!\r\n"
        s3 = u"next line.\r\n"

        s = (s1+s2+s3).encode(self.encoding)
        stream = StringIO.StringIO(s)
        reader = codecs.getreader(self.encoding)(stream)
        self.assertEqual(reader.readline(), s1)
        self.assertEqual(reader.readline(), s2)
        self.assertEqual(reader.readline(), s3)
        self.assertEqual(reader.readline(), u"") 
Example #23
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_simple(self):
        self.assertEqual(u"\U00010203".encode(self.encoding), "\x00\x01\x02\x03") 
Example #24
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_bom(self):
        d = codecs.getincrementaldecoder("utf-8-sig")()
        s = u"spam"
        self.assertEqual(d.decode(s.encode("utf-8-sig")), s) 
Example #25
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_encode(self):
        for uni, puny in punycode_testcases:
            # Need to convert both strings to lower case, since
            # some of the extended encodings use upper case, but our
            # code produces only lower case. Converting just puny to
            # lower is also insufficient, since some of the input characters
            # are upper case.
            self.assertEqual(uni.encode("punycode").lower(), puny.lower()) 
Example #26
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_decode_callback(self):
        if sys.maxunicode > 0xffff:
            codecs.register_error("UnicodeInternalTest", codecs.ignore_errors)
            decoder = codecs.getdecoder("unicode_internal")
            ab = u"ab".encode("unicode_internal")
            ignored = decoder("%s\x22\x22\x22\x22%s" % (ab[:4], ab[4:]),
                "UnicodeInternalTest")
            self.assertEqual((u"ab", 12), ignored) 
Example #27
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_builtin_encode(self):
        self.assertEqual(u"python.org".encode("idna"), "python.org")
        self.assertEqual("python.org.".encode("idna"), "python.org.")
        self.assertEqual(u"pyth\xf6n.org".encode("idna"), "xn--pythn-mua.org")
        self.assertEqual(u"pyth\xf6n.org.".encode("idna"), "xn--pythn-mua.org.") 
Example #28
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_incremental_encode(self):
        self.assertEqual(
            "".join(codecs.iterencode(u"python.org", "idna")),
            "python.org"
        )
        self.assertEqual(
            "".join(codecs.iterencode(u"python.org.", "idna")),
            "python.org."
        )
        self.assertEqual(
            "".join(codecs.iterencode(u"pyth\xf6n.org.", "idna")),
            "xn--pythn-mua.org."
        )
        self.assertEqual(
            "".join(codecs.iterencode(u"pyth\xf6n.org.", "idna")),
            "xn--pythn-mua.org."
        )

        encoder = codecs.getincrementalencoder("idna")()
        self.assertEqual(encoder.encode(u"\xe4x"), "")
        self.assertEqual(encoder.encode(u"ample.org"), "xn--xample-9ta.")
        self.assertEqual(encoder.encode(u"", True), "org")

        encoder.reset()
        self.assertEqual(encoder.encode(u"\xe4x"), "")
        self.assertEqual(encoder.encode(u"ample.org."), "xn--xample-9ta.org.")
        self.assertEqual(encoder.encode(u"", True), "") 
Example #29
Source File: test_codecs.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_read(self):
        sin = codecs.encode("\x80", "base64_codec")
        reader = codecs.getreader("base64_codec")(StringIO.StringIO(sin))
        sout = reader.read()
        self.assertEqual(sout, "\x80")
        self.assertIsInstance(sout, str) 
Example #30
Source File: bytes.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x):
        if paramTypes[0] == "bytes" or paramTypes[0] == {"type": "bytes"}:
            try:
                codecs.decode(x, self.codec, "strict")
            except UnicodeDecodeError:
                return False
            else:
                return True
        else:
            try:
                codecs.encode(x, self.codec, "strict")
            except UnicodeEncodeError:
                return False
            else:
                return True