Beispiel #1
0
        def new_server_nonce(algorithm, tokens, affordances):
            try:
                state_digest = tokens['state_digest']
            except KeyError:
                request_timestamp = \
                    algorithm.current_request_timestamp(tokens=tokens)
                try:
                    etag = algorithm.current_request_etag(tokens=tokens)
                except _bedframe_exc.AvoidingAuth:
                    etag = _b64encode(algorithm.current_request_loc)

                try:
                    private_key = tokens['private_key']
                except KeyError:
                    private_key = \
                        algorithm.private_key(tokens=tokens,
                                              affordances=affordances)

                state_digest = \
                    _md5('{}:{}:{}'.format(request_timestamp, etag,
                                           private_key))\
                     .hexdigest()

            nonce = _b64encode('{}{}'.format(request_timestamp, state_digest))
            algorithm.server_nonce_info[nonce] = \
                algorithm.ServerNonceInfo(value=nonce,
                                          loc=algorithm.current_request_loc,
                                          etag=etag,
                                          timestamp=request_timestamp,
                                          use_count=0)
            return nonce
Beispiel #2
0
 def private_key(algorithm, tokens, affordances):
     key_create_time = float('-inf')
     while True:
         if _time() - key_create_time > algorithm.private_key_lifespan:
             key = _b64encode(str(_random()))
             key_create_time = _time()
         yield key
Beispiel #3
0
    def __init__(self,
                 user=None,
                 password=None,
                 SID=None,
                 close_on_exit=True,
                 lite=False,
                 proxy=None,
                 timeout=600,
                 throttle=(2, 1)):
        """Create the SOAP clients. user and password for premium access."""

        self._SID = SID
        self._lite = lite
        self._close_on_exit = close_on_exit
        proxy = {'http': proxy} if proxy else None
        options = {'proxy': proxy, 'timeout': timeout}
        search_wsdl = self.searchlite_url if lite else self.search_url
        self._auth = _suds.client.Client(self.auth_url, **options)
        self._search = _suds.client.Client(search_wsdl, **options)
        self._throttle_wait = _limit(*throttle)(lambda: True)

        if user and password:
            auth = '%s:%s' % (user, password)
            auth = _b64encode(auth.encode('utf-8')).decode('utf-8')
            headers = {'Authorization': ('Basic %s' % auth).strip()}
            self._auth.set_options(headers=headers)
Beispiel #4
0
def b64encode(text: str) -> str:
    """计算 Base64 值

    :param text: 待计算的文本
    :return: base64 字符串

    >>> b64encode("从零开始的异世界")
    '5LuO6Zu25byA5aeL55qE5byC5LiW55WM'
    """
    return _b64encode(text.encode("utf-8")).decode("utf-8")
Beispiel #5
0
    def save_to_file(self, metadatafile, private):
        """Saves the metadata to file.

        Args:
            metadatafile (path): The path for the metadatafile.
            private (bool): Save also the private key.
        """
        state = self._keyreg.get_state(private)
        rsakey = self._keyreg.get_rsakey(private)

        metadata = {
            "key": _b64encode(self._key).decode("ascii"),
            "iv": _b64encode(self._iv).decode("ascii"),
            "rsakey": rsakey.exportKey().decode("ascii"),
            "order": self._order,
            "state": state,
        }

        with open(metadatafile, "w") as fp:
            _json.dump(metadata, fp)
Beispiel #6
0
def b64encode(obj: Union[str, bytes], encoding="utf-8") -> str:
    """Base64 encode characters of a string

    Args:
        obj: string or bytes to encode

    Returns:
        str: encoded string
    """
    _obj = obj
    if not isinstance(obj, bytes):
        _obj = str(obj).encode(encoding)
    return _b64encode(_obj).decode(encoding)
Beispiel #7
0
    def create_minimal(cls, uris, configloc, schemas, config_password,
                       pidfile=None):

        if _os.path.isdir(configloc) and _os.access(configloc, _os.W_OK):
            pass
        elif not _os.path.exists(configloc):
            try:
                _os.mkdir(configloc, 0700)
            except OSError as exc:
                raise RuntimeError('cannot create config dir {!r}: {}'
                                    .format(configloc, str(exc)))
        else:
            raise ValueError('invalid config dir {!r}; expecting a writable'
                              ' directory path'
                              .format(configloc))

        if cls._PASSWORD_WITH_SCHEME_RE.match(config_password):
            config_password_configvalue = config_password
        else:
            config_password_salt = _os.urandom(4)
            config_password_configvalue = \
                '{SSHA}' + _b64encode(_sha1(config_password
                                            + config_password_salt)
                                       .digest()
                                      + config_password_salt)

        if not pidfile:
            if _os.path.isdir(cls._PIDFILE_STD_DIR) \
                   and _os.access(cls._PIDFILE_STD_DIR, _os.W_OK):
                pidfile_dir = cls._PIDFILE_STD_DIR
            else:
                pidfile_dir = None
            pidfile_tmp = _NamedTemporaryFile(dir=pidfile_dir, prefix='slapd-',
                                              suffix='.pid')
            with pidfile_tmp:
                pass
            pidfile = pidfile_tmp.name

        configfile = _NamedTemporaryFile(delete=False)
        with configfile:
            for schema in schemas:
                configfile.write('include {}\n'.format(schema))
            configfile.write('pidfile {}\n'.format(pidfile))
            configfile.write('database config\n')
            configfile.write('rootpw {}\n'.format(config_password_configvalue))

        service = cls.create_from_configfile(uris=uris,
                                             configfile=configfile.name,
                                             configdir=configloc)
        _os.remove(configfile.name)
        return service
Beispiel #8
0
    def __init__(self, user=None, password=None, SID=None, close_on_exit=True,
                 lite=False):
        """Create the SOAP clients. user and password for premium access."""

        self._SID = SID
        self._close_on_exit = close_on_exit
        search_wsdl = self.searchlite_url if lite else self.search_url
        self._auth = _suds.client.Client(self.auth_url)
        self._search = _suds.client.Client(search_wsdl)

        if user and password:
            auth = '%s:%s' % (user, password)
            auth = _b64encode(auth.encode('utf-8')).decode('utf-8')
            headers = {'Authorization': ('Basic %s' % auth).strip()}
            self._auth.set_options(headers=headers)
Beispiel #9
0
 def _append_response_auth_challenge(self, realm, input, affordances):
     auth_subfields = ['{}="{}"'.format(directivename, input[tokenname])
                       for tokenname, directivename
                       in (('realm', 'realm'),
                           ('space_uris', 'domain'),
                           ('server_nonce', 'nonce'),
                           ('stale', 'stale'),
                           ('digest_algorithm', 'algorithm'),
                           ('qop', 'qop'),
                           )
                       if tokenname in input]
     if '__' in input:
         auth_subfields.append('opaque="{}"'
                                .format(_b64encode(input['__'])))
     challenge_header_value = 'Digest ' + ', '.join(auth_subfields)
     self._append_response_auth_challenge_header(challenge_header_value)
Beispiel #10
0
def encrypt(plain_text: str, key: str, base64=True) -> str:
    """Encrypt strings using Vigenere Cipher

    Args:
        plain_text (str): Plain text that needs to be encrypted
        key (str): Key for vigenere cipher
        base64 (bool): If true, will return the encoded base64 string of the cipher.
        Defaults to True.
        
        Use `random_key()` to generate a key

    Returns:
        str: Cipher Text encoded to base64
    """
    cipher = str(_transform(plain_text, key, mode="encrpyt"))
    if base64:
        return _b64encode(cipher.encode()).decode()
    return cipher
    def __init__(self,
                 user=None,
                 password=None,
                 SID=None,
                 close_on_exit=True,
                 lite=False):

        #"""Create the SOAP clients. user and password for premium access."""
        self._SID = SID
        self._close_on_exit = close_on_exit
        search_wsdl = self.searchlite_url if lite else self.search_url
        self._auth = client.Client(self.auth_url)
        self._search = client.Client(search_wsdl)

        if user and password:
            auth = '%s:%s' % (user, password)
            auth = _b64encode(auth.encode('utf-8')).decode('utf-8')
            headers = {'Authorization': ('Basic %s' % auth).strip()}
            self._auth.set_options(headers=headers)
Beispiel #12
0
    def _start_new_instance(self):
        """
        Starts a new instance.

        Returns:
            dict: Instance
            str: Instance ID
        """
        # Gets maximum Internet bandwidth
        response = self._request('DescribeBandwidthLimitation',
                                 InstanceType=self._instance_type)
        max_bandwidth = response['Bandwidths']['Bandwidth'][0]['Max']

        # Creates instance
        kwargs = dict(
            ImageId=self._image_id, InstanceType=self._instance_type,
            SecurityGroupId=self._security_group_id,
            InstanceName=self._get_host_name(),
            Description=_utl.gen_msg('accelize_generated'),
            InternetMaxBandwidthOut=max_bandwidth,
            KeyPairName=self._key_pair, RamRoleName=self._role,
            UserData=_b64encode(self._user_data).decode(),
            parameters={'Tag.1.Key': 'Apyfal', 'Tag.1.Value': self._get_tag()})
        _utl.recursive_update(kwargs, self._acs_create_instance_kwargs)

        response = self._request('CreateInstance', **kwargs)
        instance_id = response['InstanceId']

        # Allocates public IP address
        self._instance_request(
            'AllocatePublicIpAddress', status_desc='allocating IP address',
            InstanceId=instance_id)

        # Starts instance
        self._instance_request(
            'StartInstance', status_desc='starting', InstanceId=instance_id)

        # Return basic instance description as instance and instance ID
        return {'InstanceId': instance_id}, instance_id
Beispiel #13
0
 def b64encode(val, **kwargs):
     try:
         return _b64encode(val, **kwargs)
     except TypeError:
         return _b64encode(val.encode('UTF-8'), **kwargs).decode('UTF-8')
Beispiel #14
0
def _embed_figure(figfile, figfmt):
    figbytes = figfile.getvalue()
    if figfmt == 'svg':
        return figbytes.decode()
    data_uri = _b64encode(figbytes).decode()
    return '<img src="data:image/{};base64,{}" />'.format(figfmt, data_uri)
Beispiel #15
0
    if sys.hexversion >= 0x03000000:
        if encoding is not None:
            return string.encode(encoding)
        else:
            return string
    else:
        if encoding is not None:
            return unicode(string, encoding)
        else:
            return unicode(string)


# base64 compat
if sys.hexversion >= 0x03000000:
    from base64 import b64encode as _b64encode, b64decode as _b64decode
    b64encode = lambda s: _b64encode(s.encode('UTF-8')).decode('UTF-8')
    b64decode = lambda s: _b64decode(s.encode('UTF-8')).decode('UTF-8')
else:
    from base64 import b64encode, b64decode

try:
    input = raw_input
except NameError:
    input = input

try:
    reduce = reduce
except NameError:
    from functools import reduce

try:
Beispiel #16
0
    """ print to file compatibility """
    if sys.hexversion >= 0x03000000:
        if encoding is not None:
            return string.encode(encoding)
        else:
            return string
    else:
        if encoding is not None:
            return unicode(string, encoding)
        else:
            return unicode(string)

# base64 compat
if sys.hexversion >= 0x03000000:
    from base64 import b64encode as _b64encode, b64decode as _b64decode
    b64encode = lambda s: _b64encode(s.encode('UTF-8')).decode('UTF-8')
    b64decode = lambda s: _b64decode(s.encode('UTF-8')).decode('UTF-8')
else:
    from base64 import b64encode, b64decode

try:
    input = raw_input
except NameError:
    input = input

try:
    reduce = reduce
except NameError:
    from functools import reduce

try:
Beispiel #17
0
def b64encode(msg: str) -> str:
    """
    Base 64 encoding for Unicode strings.
    """
    return _b64encode(msg.encode()).decode()
Beispiel #18
0
def b64encode(msg: str) -> str:
    return _b64encode(msg.encode()).decode()
Beispiel #19
0
def b64encode(msg: str) -> str:
    """Encode a unicode string in base-64."""
    return _b64encode(msg.encode()).decode()
Beispiel #20
0
 def b64encode(s):
     return _b64encode(s).decode('ascii')
Beispiel #21
0
 def b64encode(s):
     return _b64encode(s).decode("ascii")
Beispiel #22
0
 def b64encode(s):
     return _b64encode(s).decode("ascii")
Beispiel #23
0
 def b64encode(val, **kwargs):  # pylint: disable=C0111
     try:
         return _b64encode(val, **kwargs)
     except TypeError:
         return _b64encode(val.encode('UTF-8'), **kwargs).decode('UTF-8')
Beispiel #24
0
 def b64encode(val, **kwargs):
     try:
         return _b64encode(val, **kwargs)
     except TypeError:
         return _b64encode(val.encode('UTF-8'), **kwargs).decode('UTF-8')
Beispiel #25
0
def b64encode(s):
    return _b64encode(s.encode('ascii'))
 def b64encode(s):
     return _b64encode(s).decode('ascii')
Beispiel #27
0
def b64encode(text: str) -> str:
    """计算base64"""
    return _b64encode(text.encode("utf-8")).decode("utf-8")
Beispiel #28
0
        else:
            return string
    else:
        if encoding is not None:
            return unicode(string, encoding)
        else:
            return unicode(string)

try:
    unicode = unicode
except:
    unicode = str

# base64 compat
from base64 import b64encode as _b64encode, b64decode as _b64decode
b64encode = lambda s: _b64encode(s.encode('ascii')).decode('ascii')
b64decode = lambda s: _b64decode(s.encode('ascii')).decode('ascii')

try:
    input = raw_input
except:
    input = input

try:
    reduce = reduce
except NameError:
    from functools import reduce

try:
    from collections import MutableMapping
except ImportError:
Beispiel #29
0
    def create_basic(cls, uris, configloc, schemas, modules, config_password,
                     dbtype, dbdir, suffix, root_dn, root_password,
                     authz_map=None, access=(), index=(), pidfile=None):

        suffix_rdns = suffix.split(',')
        if len(suffix_rdns) > 1:
            suffix_org_dn = ','.join(suffix_rdns[-2:])
            suffix_orgunits_rdns = suffix_rdns[:-2]

            suffix_org_dn_match = cls._SUFFIX_ORG_DN_RE.match(suffix_org_dn)
            if not suffix_org_dn_match:
                raise ValueError('invalid suffix DN {!r}; expected one in'
                                  ' which the last two components match {!r}'
                                  .format(suffix, cls._SUFFIX_ORG_DN_RE))
            suffix_org = suffix_org_dn_match.group('org')

        if cls._PASSWORD_WITH_SCHEME_RE.match(root_password):
            root_password_configvalue = root_password
        else:
            root_password_salt = _os.urandom(4)
            root_password_configvalue = \
                '{SSHA}' + _b64encode(_sha1(root_password + root_password_salt)
                                       .digest()
                                      + root_password_salt)

        authz_map = authz_map or {}
        try:
            authz_map_items = authz_map.items()
        except AttributeError:
            authz_map_items = authz_map

        service = cls.create_minimal(uris=uris,
                                     configloc=configloc,
                                     schemas=schemas,
                                     config_password=config_password,
                                     pidfile=pidfile)
        svc_pid = service.start(fork=True)
        if svc_pid == 0:
            _sys.exit()

        try:
            config_client = service.client()
            config_client.simple_bind_s('cn=config', config_password)

            # configure SASL authentication
            config_client\
             .modify_s('cn=config',
                       ((_ldap.MOD_REPLACE, 'olcPasswordHash', '{CLEARTEXT}'),
                        (_ldap.MOD_REPLACE, 'olcAuthzRegexp',
                         tuple('{} {}'.format(match, replacement)
                               for match, replacement in authz_map_items)),
                        ))

            # configure primary backend database
            config_client\
             .add_s('cn=Module{0},cn=config',
                    (('objectClass', 'olcModuleList'),
                     ('olcModuleLoad', modules)))
            config_client\
             .add_s('olcDatabase={},cn=config'.format(dbtype),
                    (('objectClass',
                      'olc{}Config'.format(dbtype.capitalize())),
                     ('olcDatabase', dbtype),
                     ('olcDbDirectory', dbdir),
                     ('olcSuffix', suffix),
                     ('olcRootDN', root_dn),
                     ('olcRootPW', root_password_configvalue),
                     ))
            config_client\
             .modify_s('olcDatabase={1}hdb,cn=config',
                       ((_ldap.MOD_ADD, 'olcDbIndex', index),
                        (_ldap.MOD_REPLACE, 'olcAccess', access)))

            config_client.unbind_s()

            # initialize suffix
            suffix_rdns = suffix.split(',')
            if len(suffix_rdns) > 1:

                root_client = service.client()
                root_client.simple_bind_s(root_dn, root_password)

                root_client\
                 .add_s(suffix_org_dn,
                        (('objectClass', ('dcObject', 'organization')),
                         ('dc', suffix_org), ('o', suffix_org)))

                orgunit_dn = suffix_org_dn
                for orgunit_rdn in suffix_orgunits_rdns:
                    orgunit_dn = ','.join(orgunit_rdn, orgunit_dn)

                    _, orgunit = orgunit_dn.split('=')
                    root_client\
                     .add_s(suffix_org_dn,
                            (('objectClass', 'dcObject'),
                             ('objectClass', 'organizationalUnit'),
                             ('dc', orgunit), ('ou', orgunit)))

                root_client.unbind_s()

        finally:
            if service.status == _services.ServiceStatus('running'):
                service.stop()

        return service
Beispiel #30
0
 def b64encode(val, **kwargs):  # pylint: disable=C0111
     try:
         return _b64encode(val, **kwargs)
     except TypeError:
         return _b64encode(val.encode('UTF-8'), **kwargs).decode('UTF-8')
Beispiel #31
0
def b64urlencode(msg: bytes) -> str:
    """Encode bytes in url-safe base-64 alphabet."""
    encoded = _b64encode(msg).decode()
    stripped = encoded.split("=")[0]
    return stripped.replace("+", "-").replace("/", "_")
Beispiel #32
0
 def b64encode(data, chars="+/"):
     if isunicode(chars):
         return _b64encode(data, chars.encode('utf-8')).decode('utf-8')
     else:
         return _b64encode(data, chars)
Beispiel #33
0
        if encoding is not None:
            return string.encode(encoding)
        else:
            return string
    else:
        if encoding is not None:
            return unicode(string, encoding)
        else:
            return unicode(string)


# base64 compat
if sys.hexversion >= 0x03000000:
    from base64 import b64encode as _b64encode, b64decode as _b64decode

    b64encode = lambda s: _b64encode(s.encode("UTF-8")).decode("UTF-8")
    b64decode = lambda s: _b64decode(s.encode("UTF-8")).decode("UTF-8")
else:
    from base64 import b64encode, b64decode

try:
    input = raw_input
except NameError:
    input = input

try:
    reduce = reduce
except NameError:
    from functools import reduce

try:
Beispiel #34
0
 def b64encode(data, chars="+/"):
     if isunicode(chars):
         return _b64encode(data, chars.encode('utf-8')).decode('utf-8')
     else:
         return _b64encode(data, chars)
Beispiel #35
0
def b64encode(s):
    return _b64encode(s.encode('ascii'))