Python binascii.b2a_hex() Examples

The following are 30 code examples of binascii.b2a_hex(). 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: auth.py    From bottle-auth with MIT License 6 votes vote down vote up
def _oauth_access_token_url(self, request_token):
        consumer_token = self._oauth_consumer_token()
        url = self._OAUTH_ACCESS_TOKEN_URL
        args = dict(
            oauth_consumer_key=consumer_token["key"],
            oauth_token=request_token["key"],
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=binascii.b2a_hex(uuid.uuid4().bytes),
            oauth_version=getattr(self, "_OAUTH_VERSION", "1.0a"),
        )
        if "verifier" in request_token:
          args["oauth_verifier"]=request_token["verifier"]

        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            signature = _oauth10a_signature(consumer_token, "GET", url, args,
                                            request_token)
        else:
            signature = _oauth_signature(consumer_token, "GET", url, args,
                                         request_token)

        args["oauth_signature"] = signature
        return url + "?" + urllib.urlencode(args) 
Example #2
Source File: common.py    From earthengine with MIT License 6 votes vote down vote up
def runTest(self):
        plaintext = a2b_hex(self.plaintext)
        ciphertext = a2b_hex(self.ciphertext)

        # The cipher should work like a stream cipher

        # Test counter mode encryption, 3 bytes at a time
        ct3 = []
        cipher = self._new()
        for i in range(0, len(plaintext), 3):
            ct3.append(cipher.encrypt(plaintext[i:i+3]))
        ct3 = b2a_hex(b("").join(ct3))
        self.assertEqual(self.ciphertext, ct3)  # encryption (3 bytes at a time)

        # Test counter mode decryption, 3 bytes at a time
        pt3 = []
        cipher = self._new()
        for i in range(0, len(ciphertext), 3):
            pt3.append(cipher.encrypt(ciphertext[i:i+3]))
        # PY3K: This is meant to be text, do not change to bytes (data)
        pt3 = b2a_hex(b("").join(pt3))
        self.assertEqual(self.plaintext, pt3)  # decryption (3 bytes at a time) 
Example #3
Source File: sqlite3_util.py    From bayeslite with Apache License 2.0 6 votes vote down vote up
def sqlite3_savepoint(db):
    """Savepoint context manager.  On return, commit; on exception, rollback.

    Savepoints are like transactions, but they may be nested in
    transactions or in other savepoints.
    """
    # This is not symmetric with sqlite3_transaction because ROLLBACK
    # undoes any effects and makes the transaction cease to be,
    # whereas ROLLBACK TO undoes any effects but leaves the savepoint
    # as is.  So for either success or failure we must release the
    # savepoint explicitly.
    savepoint = binascii.b2a_hex(os.urandom(32))
    db.cursor().execute("SAVEPOINT x%s" % (savepoint,))
    ok = False
    try:
        yield
        ok = True
    finally:
        if not ok:
            db.cursor().execute("ROLLBACK TO x%s" % (savepoint,))
        db.cursor().execute("RELEASE x%s" % (savepoint,)) 
Example #4
Source File: test_FortunaAccumulator.py    From earthengine with MIT License 6 votes vote down vote up
def test_FortunaPool(self):
        """FortunaAccumulator.FortunaPool"""
        pool = FortunaAccumulator.FortunaPool()
        self.assertEqual(0, pool.length)
        self.assertEqual("5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456", pool.hexdigest())

        pool.append(b('abc'))

        self.assertEqual(3, pool.length)
        self.assertEqual("4f8b42c22dd3729b519ba6f68d2da7cc5b2d606d05daed5ad5128cc03e6c6358", pool.hexdigest())

        pool.append(b("dbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"))

        self.assertEqual(56, pool.length)
        self.assertEqual(b('0cffe17f68954dac3a84fb1458bd5ec99209449749b2b308b7cb55812f9563af'), b2a_hex(pool.digest()))

        pool.reset()

        self.assertEqual(0, pool.length)

        pool.append(b('a') * 10**6)

        self.assertEqual(10**6, pool.length)
        self.assertEqual(b('80d1189477563e1b5206b2749f1afe4807e5705e8bd77887a60187a712156688'), b2a_hex(pool.digest())) 
Example #5
Source File: hashing.py    From blueflower with GNU General Public License v3.0 6 votes vote down vote up
def key_derivation(pwd, salt=''):
    """returns (key, verifier, salt) where
        * key is a 128-bit int (as siphash.SipHash requires)
        * verifier is an 8-byte string
        * salt is an 8-byte string
    """
    # if salt not given, pick a random one
    if not salt:
        salt = b2a_hex(os.urandom(SALT_BYTES))

    # key generation
    salt_as_int = int(salt, 16)
    mask = 0xffffffffffffffff
    key_hi = SIPHASH_SLOW(pwd+'0', salt_as_int) & mask
    key_lo = SIPHASH_SLOW(pwd+'1', salt_as_int) & mask
    key = (key_hi << 64) | key_lo

    # verifier generation
    verifier = tohex(SIPHASH_FAST(salt, key))

    return (key, verifier, salt) 
Example #6
Source File: common.py    From earthengine with MIT License 6 votes vote down vote up
def runTest(self):
        plaintext = a2b_hex(self.plaintext)
        ciphertext = a2b_hex(self.ciphertext)

        ct1 = b2a_hex(self._new().encrypt(plaintext))
        pt1 = b2a_hex(self._new(1).decrypt(ciphertext))
        ct2 = b2a_hex(self._new().encrypt(plaintext))
        pt2 = b2a_hex(self._new(1).decrypt(ciphertext))

        if hasattr(self.module, "MODE_OPENPGP") and self.mode == self.module.MODE_OPENPGP:
            # In PGP mode, data returned by the first encrypt()
            # is prefixed with the encrypted IV.
            # Here we check it and then remove it from the ciphertexts.
            eilen = len(self.encrypted_iv)
            self.assertEqual(self.encrypted_iv, ct1[:eilen])
            self.assertEqual(self.encrypted_iv, ct2[:eilen])
            ct1 = ct1[eilen:]
            ct2 = ct2[eilen:]

        self.assertEqual(self.ciphertext, ct1)  # encrypt
        self.assertEqual(self.ciphertext, ct2)  # encrypt (second time)
        self.assertEqual(self.plaintext, pt1)   # decrypt
        self.assertEqual(self.plaintext, pt2)   # decrypt (second time) 
Example #7
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_dispatch_opcode_iquery(self):
        # DNS packet with IQUERY opcode
        payload = "271109000001000000000000076578616d706c6503636f6d0000010001"

        # expected response is an error code REFUSED.  The other fields are
        # id 10001
        # opcode IQUERY
        # rcode REFUSED
        # flags QR RD
        # ;QUESTION
        # example.com. IN A
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"271189050001000000000000076578616d706c6503636f"
                             b"6d0000010001")

        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {'addr': self.addr, 'context': self.context}
        response = next(self.handler(request)).to_wire()

        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #8
Source File: auth.py    From tornado-zh with MIT License 6 votes vote down vote up
def _oauth_access_token_url(self, request_token):
        consumer_token = self._oauth_consumer_token()
        url = self._OAUTH_ACCESS_TOKEN_URL
        args = dict(
            oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
            oauth_token=escape.to_basestring(request_token["key"]),
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
            oauth_version="1.0",
        )
        if "verifier" in request_token:
            args["oauth_verifier"] = request_token["verifier"]

        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            signature = _oauth10a_signature(consumer_token, "GET", url, args,
                                            request_token)
        else:
            signature = _oauth_signature(consumer_token, "GET", url, args,
                                         request_token)

        args["oauth_signature"] = signature
        return url + "?" + urllib_parse.urlencode(args) 
Example #9
Source File: auth.py    From tornado-zh with MIT License 6 votes vote down vote up
def _oauth_request_token_url(self, callback_uri=None, extra_params=None):
        consumer_token = self._oauth_consumer_token()
        url = self._OAUTH_REQUEST_TOKEN_URL
        args = dict(
            oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
            oauth_version="1.0",
        )
        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            if callback_uri == "oob":
                args["oauth_callback"] = "oob"
            elif callback_uri:
                args["oauth_callback"] = urlparse.urljoin(
                    self.request.full_url(), callback_uri)
            if extra_params:
                args.update(extra_params)
            signature = _oauth10a_signature(consumer_token, "GET", url, args)
        else:
            signature = _oauth_signature(consumer_token, "GET", url, args)

        args["oauth_signature"] = signature
        return url + "?" + urllib_parse.urlencode(args) 
Example #10
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_dispatch_opcode_status(self):
        # DNS packet with STATUS opcode
        payload = "271211000001000000000000076578616d706c6503636f6d0000010001"

        # expected response is an error code REFUSED.  The other fields are
        # id 10002
        # opcode STATUS
        # rcode REFUSED
        # flags QR RD
        # ;QUESTION
        # example.com. IN A
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"271291050001000000000000076578616d706c6503636f"
                             b"6d0000010001")

        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {'addr': self.addr, 'context': self.context}
        response = next(self.handler(request)).to_wire()

        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #11
Source File: auth.py    From tornado-zh with MIT License 6 votes vote down vote up
def _oauth_access_token_url(self, request_token):
        consumer_token = self._oauth_consumer_token()
        url = self._OAUTH_ACCESS_TOKEN_URL
        args = dict(
            oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
            oauth_token=escape.to_basestring(request_token["key"]),
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
            oauth_version="1.0",
        )
        if "verifier" in request_token:
            args["oauth_verifier"] = request_token["verifier"]

        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            signature = _oauth10a_signature(consumer_token, "GET", url, args,
                                            request_token)
        else:
            signature = _oauth_signature(consumer_token, "GET", url, args,
                                         request_token)

        args["oauth_signature"] = signature
        return url + "?" + urllib_parse.urlencode(args) 
Example #12
Source File: auth.py    From tornado-zh with MIT License 6 votes vote down vote up
def _oauth_request_token_url(self, callback_uri=None, extra_params=None):
        consumer_token = self._oauth_consumer_token()
        url = self._OAUTH_REQUEST_TOKEN_URL
        args = dict(
            oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
            oauth_version="1.0",
        )
        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            if callback_uri == "oob":
                args["oauth_callback"] = "oob"
            elif callback_uri:
                args["oauth_callback"] = urlparse.urljoin(
                    self.request.full_url(), callback_uri)
            if extra_params:
                args.update(extra_params)
            signature = _oauth10a_signature(consumer_token, "GET", url, args)
        else:
            signature = _oauth_signature(consumer_token, "GET", url, args)

        args["oauth_signature"] = signature
        return url + "?" + urllib_parse.urlencode(args) 
Example #13
Source File: auth.py    From bottle-auth with MIT License 6 votes vote down vote up
def _oauth_request_token_url(self, callback_uri= None, extra_params=None):
        consumer_token = self._oauth_consumer_token()
        url = self._OAUTH_REQUEST_TOKEN_URL
        args = dict(
            oauth_consumer_key=consumer_token["key"],
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=binascii.b2a_hex(uuid.uuid4().bytes),
            oauth_version=getattr(self, "_OAUTH_VERSION", "1.0a"),
        )
        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            if callback_uri:
                args["oauth_callback"] = urlparse.urljoin(
                    self.request.full_url(), callback_uri)
            if extra_params: args.update(extra_params)
            signature = _oauth10a_signature(consumer_token, "GET", url, args)
        else:
            signature = _oauth_signature(consumer_token, "GET", url, args)

        args["oauth_signature"] = signature
        return url + "?" + urllib.urlencode(args) 
Example #14
Source File: auth.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def _oauth_access_token_url(self, request_token: Dict[str, Any]) -> str:
        consumer_token = self._oauth_consumer_token()
        url = self._OAUTH_ACCESS_TOKEN_URL  # type: ignore
        args = dict(
            oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
            oauth_token=escape.to_basestring(request_token["key"]),
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
            oauth_version="1.0",
        )
        if "verifier" in request_token:
            args["oauth_verifier"] = request_token["verifier"]

        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            signature = _oauth10a_signature(
                consumer_token, "GET", url, args, request_token
            )
        else:
            signature = _oauth_signature(
                consumer_token, "GET", url, args, request_token
            )

        args["oauth_signature"] = signature
        return url + "?" + urllib.parse.urlencode(args) 
Example #15
Source File: _robot_tester.py    From sslyze with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_client_key_exchange_record(
        cls,
        robot_payload_enum: RobotPmsPaddingPayloadEnum,
        tls_version: tls_parser.tls_version.TlsVersionEnum,
        modulus: int,
        exponent: int,
    ) -> TlsRsaClientKeyExchangeRecord:
        """A client key exchange record with a hardcoded pre_master_secret, and a valid or invalid padding.
        """
        pms_padding = cls._compute_pms_padding(modulus)
        tls_version_hex = binascii.b2a_hex(TlsRecordTlsVersionBytes[tls_version.name].value).decode("ascii")

        pms_with_padding_payload = cls._CKE_PAYLOADS_HEX[robot_payload_enum]
        final_pms = pms_with_padding_payload.format(
            pms_padding=pms_padding, tls_version=tls_version_hex, pms=cls._PMS_HEX
        )
        cke_robot_record = TlsRsaClientKeyExchangeRecord.from_parameters(
            tls_version, exponent, modulus, int(final_pms, 16)
        )
        return cke_robot_record 
Example #16
Source File: test_DES.py    From earthengine with MIT License 6 votes vote down vote up
def runTest(self):
        from Crypto.Cipher import DES
        from binascii import b2a_hex

        X = []
        X[0:] = [b('\x94\x74\xB8\xE8\xC7\x3B\xCA\x7D')]
        
        for i in range(16):
            c = DES.new(X[i],DES.MODE_ECB)
            if not (i&1): # (num&1) returns 1 for odd numbers 
                X[i+1:] = [c.encrypt(X[i])] # even
            else:
                X[i+1:] = [c.decrypt(X[i])] # odd

        self.assertEqual(b2a_hex(X[16]),
            b2a_hex(b('\x1B\x1A\x2D\xDB\x4C\x64\x24\x38'))) 
Example #17
Source File: test_handler.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_dispatch_opcode_query_non_existent_zone(self):
        # DNS packet with QUERY opcode
        # query is for example.com. IN A
        payload = ("271501200001000000000001076578616d706c6503636f6d0000010001"
                   "0000291000000000000000")

        # expected_response is an error code REFUSED.  The other fields are
        # id 10005
        # opcode QUERY
        # rcode REFUSED
        # flags QR RD
        # edns 0
        # payload 8192
        # ;QUESTION
        # example.com. IN A
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"271581050001000000000001076578616d706c6503636f"
                             b"6d00000100010000292000000000000000")
        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {'addr': self.addr, 'context': self.context}
        response = next(self.handler(request)).to_wire()

        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #18
Source File: hex_codec.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def encode(self, input, final=False):
        assert self.errors == 'strict'
        return binascii.b2a_hex(input) 
Example #19
Source File: test_handler.py    From designate with Apache License 2.0 5 votes vote down vote up
def test_dispatch_opcode_notify_same_serial(self, func):
        # DNS packet with NOTIFY opcode
        payload = "c38021000001000000000000076578616d706c6503636f6d0000060001"

        master = "10.0.0.1"
        zone = self._get_secondary_zone({"serial": 123})

        # expected response is an error code NOERROR.  The other fields are
        # id 50048
        # opcode NOTIFY
        # rcode NOERROR
        # flags QR AA RD
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"c380a5000001000000000000076578616d706c6503636f"
                             b"6d0000060001")

        # The SOA serial should be different from the one in thezone and
        # will trigger a AXFR
        func.return_value = self._get_soa_answer(zone.serial)

        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {
            'addr': (master, 53),
            'context': self.context
        }

        with mock.patch.object(self.handler.storage, 'find_zone',
                               return_value=zone):
            response = next(self.handler(request)).to_wire()

        assert not self.mock_tg.add_thread.called
        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #20
Source File: test_descr.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_buffer_inheritance(self):
        # Testing that buffer interface is inherited ...

        import binascii
        # SF bug [#470040] ParseTuple t# vs subclasses.

        class MyStr(str):
            pass
        base = 'abc'
        m = MyStr(base)
        # b2a_hex uses the buffer interface to get its argument's value, via
        # PyArg_ParseTuple 't#' code.
        self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))

        # It's not clear that unicode will continue to support the character
        # buffer interface, and this test will fail if that's taken away.
        class MyUni(unicode):
            pass
        base = u'abc'
        m = MyUni(base)
        self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))

        class MyInt(int):
            pass
        m = MyInt(42)
        try:
            binascii.b2a_hex(m)
            self.fail('subclass of int should not have a buffer interface')
        except TypeError:
            pass 
Example #21
Source File: minimize_task.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def get_temporary_file_name(original_file):
  """Generate a temporary file name in the same directory as |original_file|."""
  directory, basename = os.path.split(original_file)
  basename = basename[-MAX_TEMPORARY_FILE_BASENAME_LENGTH:]

  random_hex = binascii.b2a_hex(os.urandom(16)).decode('utf-8')
  new_file_path = os.path.join(directory, '%s%s' % (random_hex, basename))

  return new_file_path 
Example #22
Source File: test_handler.py    From designate with Apache License 2.0 5 votes vote down vote up
def test_dispatch_opcode_notify_different_serial(self, func):
        # DNS packet with NOTIFY opcode
        payload = "c38021000001000000000000076578616d706c6503636f6d0000060001"

        master = "10.0.0.1"
        zone = self._get_secondary_zone({"serial": 123})

        # expected response is an error code NOERROR.  The other fields are
        # id 50048
        # opcode NOTIFY
        # rcode NOERROR
        # flags QR AA RD
        # ;QUESTION
        # example.com. IN A
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"c380a5000001000000000000076578616d706c6503636f"
                             b"6d0000060001")

        # The SOA serial should be different from the one in thezone and
        # will trigger a AXFR
        func.return_value = self._get_soa_answer(123123)

        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {
            'addr': (master, 53),
            'context': self.context
        }

        with mock.patch.object(self.handler.storage, 'find_zone',
                               return_value=zone):
            response = next(self.handler(request)).to_wire()

        self.mock_tg.add_thread.assert_called_with(
            self.handler.zone_sync, self.context, zone,
            [zone.masters[0]])
        self.assertEqual(expected_response, binascii.b2a_hex(response)) 
Example #23
Source File: auth.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def _oauth_request_token_url(
        self, callback_uri: str = None, extra_params: Dict[str, Any] = None
    ) -> str:
        handler = cast(RequestHandler, self)
        consumer_token = self._oauth_consumer_token()
        url = self._OAUTH_REQUEST_TOKEN_URL  # type: ignore
        args = dict(
            oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
            oauth_version="1.0",
        )
        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            if callback_uri == "oob":
                args["oauth_callback"] = "oob"
            elif callback_uri:
                args["oauth_callback"] = urllib.parse.urljoin(
                    handler.request.full_url(), callback_uri
                )
            if extra_params:
                args.update(extra_params)
            signature = _oauth10a_signature(consumer_token, "GET", url, args)
        else:
            signature = _oauth_signature(consumer_token, "GET", url, args)

        args["oauth_signature"] = signature
        return url + "?" + urllib.parse.urlencode(args) 
Example #24
Source File: hex_codec.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def hex_encode(input,errors='strict'):

    """ Encodes the object input and returns a tuple (output
        object, length consumed).

        errors defines the error handling to apply. It defaults to
        'strict' handling which is the only currently supported
        error handling for this codec.

    """
    assert errors == 'strict'
    output = binascii.b2a_hex(input)
    return (output, len(input)) 
Example #25
Source File: custom.py    From azure-cli-extensions with MIT License 5 votes vote down vote up
def _create_client_secret():
    # Add a special character to satsify AAD SP secret requirements
    special_char = '$'
    client_secret = binascii.b2a_hex(os.urandom(10)).decode('utf-8') + special_char
    return client_secret 
Example #26
Source File: custom.py    From azure-cli-extensions with MIT License 5 votes vote down vote up
def _ensure_aks_service_principal(cli_ctx,
                                  service_principal=None,
                                  client_secret=None,
                                  subscription_id=None,
                                  dns_name_prefix=None,
                                  location=None,
                                  name=None):
    file_name_aks = 'aksServicePrincipal.json'
    # TODO: This really needs to be unit tested.
    rbac_client = get_graph_rbac_management_client(cli_ctx)
    if not service_principal:
        # --service-principal not specified, try to load it from local disk
        principal_obj = load_acs_service_principal(subscription_id, file_name=file_name_aks)
        if principal_obj:
            service_principal = principal_obj.get('service_principal')
            client_secret = principal_obj.get('client_secret')
        else:
            # Nothing to load, make one.
            if not client_secret:
                client_secret = _create_client_secret()
            salt = binascii.b2a_hex(os.urandom(3)).decode('utf-8')
            url = 'http://{}.{}.{}.cloudapp.azure.com'.format(salt, dns_name_prefix, location)

            service_principal = _build_service_principal(rbac_client, cli_ctx, name, url, client_secret)
            if not service_principal:
                raise CLIError('Could not create a service principal with the right permissions. '
                               'Are you an Owner on this project?')
            logger.info('Created a service principal: %s', service_principal)
            # We don't need to add role assignment for this created SPN
    else:
        # --service-principal specfied, validate --client-secret was too
        if not client_secret:
            raise CLIError('--client-secret is required if --service-principal is specified')
    store_acs_service_principal(subscription_id, client_secret, service_principal, file_name=file_name_aks)
    return load_acs_service_principal(subscription_id, file_name=file_name_aks) 
Example #27
Source File: auth.py    From bottle-auth with MIT License 5 votes vote down vote up
def _oauth_request_parameters(self, url, access_token, parameters={},
                                  method="GET"):
        """Returns the OAuth parameters as a dict for the given request.

        parameters should include all POST arguments and query string arguments
        that will be sent with the request.
        """
        consumer_token = self._oauth_consumer_token()
        base_args = dict(
            oauth_consumer_key=consumer_token["key"],
            oauth_token=access_token["key"],
            oauth_signature_method="HMAC-SHA1",
            oauth_timestamp=str(int(time.time())),
            oauth_nonce=binascii.b2a_hex(uuid.uuid4().bytes),
            oauth_version=getattr(self, "_OAUTH_VERSION", "1.0a"),
        )
        args = {}
        args.update(base_args)
        args.update(parameters)
        if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
            signature = _oauth10a_signature(consumer_token, method, url, args,
                                         access_token)
        else:
            signature = _oauth_signature(consumer_token, method, url, args,
                                         access_token)
        base_args["oauth_signature"] = signature
        return base_args 
Example #28
Source File: ssh_host_key.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def key_details(self):
		key_type = self.key.get_name().lower()
		details = "Host: {0} ({1})\n".format(self.hostname, key_type)
		if key_type.startswith('ssh-'):
			key_type = key_type[4:]
		key_type = key_type.split('-', 1)[0].upper()
		details += "{0} key fingerprint is SHA256:{1}\n".format(key_type, base64.b64encode(hashlib.new('sha256', self.key.asbytes()).digest()).decode('utf-8'))
		details += "{0} key fingerprint is MD5:{1}\n".format(key_type, binascii.b2a_hex(hashlib.new('md5', self.key.asbytes()).digest()).decode('utf-8'))
		return details 
Example #29
Source File: security_keys.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _encoding_data(value, encoding=None):
	if isinstance(encoding, str):
		encoding = encoding.lower()
	if encoding == 'base64':
		value = binascii.b2a_base64(value).decode('utf-8').strip()
	elif encoding == 'hex':
		value = binascii.b2a_hex(value).decode('utf-8').strip()
	elif encoding is not None:
		raise ValueError('unknown encoding: ' + encoding)
	return value 
Example #30
Source File: hex_codec.py    From meddle with MIT License 5 votes vote down vote up
def encode(self, input, final=False):
        assert self.errors == 'strict'
        return binascii.b2a_hex(input)