Exemplo n.º 1
0
def register_key_factories():
    # Public Key: ECC
    factory = GeneralPublicFactory()
    PublicKey.register(algorithm=AsymmetricKey.ECC, factory=factory)
    # Public Key: RSA
    PublicKey.register(algorithm=AsymmetricKey.RSA, factory=factory)
    PublicKey.register(algorithm='SHA256withRSA', factory=factory)
    PublicKey.register(algorithm='RSA/ECB/PKCS1Padding', factory=factory)

    # Private Key: ECC
    factory = GeneralPrivateFactory(algorithm=AsymmetricKey.ECC)
    PrivateKey.register(algorithm=AsymmetricKey.ECC, factory=factory)

    # Private Key: RSA
    factory = GeneralPrivateFactory(algorithm=AsymmetricKey.RSA)
    PrivateKey.register(algorithm=AsymmetricKey.RSA, factory=factory)
    PrivateKey.register(algorithm='SHA256withRSA', factory=factory)
    PrivateKey.register(algorithm='RSA/ECB/PKCS1Padding', factory=factory)

    # Symmetric Key: AES
    factory = GeneralSymmetricFactory(algorithm=SymmetricKey.AES)
    SymmetricKey.register(algorithm=SymmetricKey.AES, factory=factory)
    SymmetricKey.register(algorithm='AES/CBC/PKCS7Padding', factory=factory)

    # Symmetric Key: Plain
    factory = GeneralSymmetricFactory(algorithm=PlainKey.PLAIN)
    SymmetricKey.register(algorithm=PlainKey.PLAIN, factory=factory)
Exemplo n.º 2
0
def load_station(identifier: str) -> Station:
    """ Load station info from 'etc' directory

        :param identifier - station ID
        :return station with info from 'dims/etc/{address}/*'
    """
    identifier = g_facebook.identifier(identifier)
    # check meta
    meta = g_facebook.meta(identifier=identifier)
    if meta is None:
        # load from 'etc' directory
        meta = Meta(
            load_station_info(identifier=identifier, filename='meta.js'))
        if meta is None:
            raise LookupError('failed to get meta for station: %s' %
                              identifier)
        elif not g_facebook.save_meta(meta=meta, identifier=identifier):
            raise ValueError('meta error: %s' % meta)
    # check private key
    private_key = g_facebook.private_key_for_signature(identifier=identifier)
    if private_key is None:
        # load from 'etc' directory
        private_key = PrivateKey(
            load_station_info(identifier=identifier, filename='secret.js'))
        if private_key is None:
            pass
        elif not g_facebook.save_private_key(key=private_key,
                                             identifier=identifier):
            raise AssertionError('failed to save private key for ID: %s, %s' %
                                 (identifier, private_key))
    # check profile
    profile = load_station_info(identifier=identifier, filename='profile.js')
    if profile is None:
        raise LookupError('failed to get profile for station: %s' % identifier)
    Log.info('station profile: %s' % profile)
    name = profile.get('name')
    host = profile.get('host')
    port = profile.get('port')
    # create station
    if private_key is None:
        # remote station
        station = Station(identifier=identifier, host=host, port=port)
    else:
        # create profile
        profile = Profile.new(identifier=identifier)
        profile.set_property('name', name)
        profile.set_property('host', host)
        profile.set_property('port', port)
        profile.sign(private_key=private_key)
        if not g_facebook.save_profile(profile=profile):
            raise AssertionError('failed to save profile: %s' % profile)
        # local station
        station = Server(identifier=identifier, host=host, port=port)
    g_facebook.cache_user(user=station)
    Log.info('station loaded: %s' % station)
    return station
Exemplo n.º 3
0
def load_station(identifier: Union[ID, str], facebook: CommonFacebook) -> Station:
    """ Load station info from 'etc' directory

        :param identifier - station ID
        :param facebook - social network data source
        :return station with info from 'dims/etc/{address}/*'
    """
    identifier = ID.parse(identifier=identifier)
    # check meta
    meta = facebook.meta(identifier=identifier)
    if meta is None:
        # load from 'etc' directory
        meta = Meta.parse(meta=load_station_info(identifier=identifier, filename='meta.js'))
        if meta is None:
            raise LookupError('failed to get meta for station: %s' % identifier)
        elif not facebook.save_meta(meta=meta, identifier=identifier):
            raise ValueError('meta error: %s' % meta)
    # check private key
    private_key = facebook.private_key_for_signature(identifier=identifier)
    if private_key is None:
        # load from 'etc' directory
        private_key = PrivateKey.parse(key=load_station_info(identifier=identifier, filename='secret.js'))
        if private_key is None:
            pass
        elif not facebook.save_private_key(key=private_key, identifier=identifier):
            raise AssertionError('failed to save private key for ID: %s, %s' % (identifier, private_key))
    # check profile
    profile = load_station_info(identifier=identifier, filename='profile.js')
    if profile is None:
        raise LookupError('failed to get profile for station: %s' % identifier)
    Log.info('station profile: %s' % profile)
    name = profile.get('name')
    host = profile.get('host')
    port = profile.get('port')
    # create station
    if private_key is None:
        # remote station
        station = Station(identifier=identifier, host=host, port=port)
    else:
        # create profile
        profile = Document.create(doc_type=Document.PROFILE, identifier=identifier)
        profile.set_property('name', name)
        profile.set_property('host', host)
        profile.set_property('port', port)
        profile.sign(private_key=private_key)
        if not facebook.save_document(document=profile):
            raise AssertionError('failed to save profile: %s' % profile)
        # local station
        station = Station(identifier=identifier, host=host, port=port)
    facebook.cache_user(user=station)
    Log.info('station loaded: %s' % station)
    return station
Exemplo n.º 4
0
 def __identity_key(self, identifier: ID) -> Optional[PrivateKey]:
     # 1. try from memory cache
     key = self.__meta_private_keys.get(identifier)
     if key is None:
         # 2. try from local storage
         path = self.__identity_key_path(identifier=identifier)
         self.info('Loading identity key from: %s' % path)
         dictionary = self.read_json(path=path)
         key = PrivateKey.parse(key=dictionary)
         if key is None:
             # 2.1. place an empty key for cache
             key = self.__empty
         # 3. store into memory cache
         self.__meta_private_keys[identifier] = key
     if key is not self.__empty:
         return key
Exemplo n.º 5
0
 def __message_keys(self, identifier: ID) -> List[PrivateKey]:
     # 1. try from memory cache
     keys = self.__visa_private_keys.get(identifier)
     if keys is None:
         keys = []
         # 2. try from local storage
         path = self.__message_keys_path(identifier=identifier)
         self.info('Loading message keys from: %s' % path)
         array = self.read_json(path=path)
         if array is not None:
             for item in array:
                 k = PrivateKey.parse(key=item)
                 if k is not None:
                     keys.append(k)
         # 3. store into memory cache
         self.__visa_private_keys[identifier] = keys
     return keys
Exemplo n.º 6
0
def load_user(identifier: str) -> User:
    identifier = g_facebook.identifier(identifier)
    # check meta
    meta = g_facebook.meta(identifier=identifier)
    if meta is None:
        # load from 'etc' directory
        meta = Meta(load_robot_info(identifier=identifier, filename='meta.js'))
        if meta is None:
            raise LookupError('failed to get meta for robot: %s' % identifier)
        elif not g_facebook.save_meta(meta=meta, identifier=identifier):
            raise ValueError('meta error: %s' % meta)
    # check private key
    private_key = g_facebook.private_key_for_signature(identifier=identifier)
    if private_key is None:
        # load from 'etc' directory
        private_key = PrivateKey(
            load_robot_info(identifier=identifier, filename='secret.js'))
        if private_key is None:
            pass
        elif not g_facebook.save_private_key(key=private_key,
                                             identifier=identifier):
            raise AssertionError('failed to save private key for ID: %s, %s' %
                                 (identifier, private_key))
    if private_key is None:
        raise AssertionError('private key not found for ID: %s' % identifier)
    # check profile
    profile = load_robot_info(identifier=identifier, filename='profile.js')
    if profile is None:
        raise LookupError('failed to get profile for robot: %s' % identifier)
    Log.info('robot profile: %s' % profile)
    name = profile.get('name')
    avatar = profile.get('avatar')
    # create profile
    profile = Profile.new(identifier=identifier)
    profile.set_property('name', name)
    profile.set_property('avatar', avatar)
    profile.sign(private_key=private_key)
    if not g_facebook.save_profile(profile):
        raise AssertionError('failed to save profile: %s' % profile)
    # create local user
    return g_facebook.user(identifier=identifier)
Exemplo n.º 7
0
def load_user(identifier: str, facebook: CommonFacebook) -> User:
    identifier = ID.parse(identifier=identifier)
    # check meta
    try:
        meta = facebook.meta(identifier=identifier)
    except AssertionError:
        meta = None
    if meta is None:
        # load from 'etc' directory
        meta = Meta.parse(meta=load_robot_info(identifier=identifier, filename='meta.js'))
        if meta is None:
            raise LookupError('failed to get meta for robot: %s' % identifier)
        elif not facebook.save_meta(meta=meta, identifier=identifier):
            raise ValueError('meta error: %s' % meta)
    # check private key
    private_key = facebook.private_key_for_signature(identifier=identifier)
    if private_key is None:
        # load from 'etc' directory
        private_key = PrivateKey.parse(key=load_robot_info(identifier=identifier, filename='secret.js'))
        if private_key is None:
            raise AssertionError('private key not found for ID: %s' % identifier)
        elif not facebook.save_private_key(key=private_key, identifier=identifier):
            raise AssertionError('failed to save private key for ID: %s, %s' % (identifier, private_key))
    # check profile
    profile = load_robot_info(identifier=identifier, filename='profile.js')
    if profile is None:
        raise LookupError('failed to get profile for robot: %s' % identifier)
    Log.info('robot profile: %s' % profile)
    name = profile.get('name')
    avatar = profile.get('avatar')
    # create profile
    profile = Document.create(doc_type=Document.VISA, identifier=identifier)
    profile.set_property('name', name)
    profile.set_property('avatar', avatar)
    profile.sign(private_key=private_key)
    if not facebook.save_document(document=profile):
        raise AssertionError('failed to save profile: %s' % profile)
    # create local user
    return facebook.user(identifier=identifier)
Exemplo n.º 8
0
 def __load_private_key(self, identifier: ID) -> PrivateKey:
     path = self.__path(identifier=identifier)
     self.info('Loading private key from: %s' % path)
     dictionary = self.read_json(path=path)
     return PrivateKey(dictionary)
Exemplo n.º 9
0
 def __load_private_key(filename: str) -> Optional[PrivateKey]:
     return PrivateKey.parse(key=load_resource_file(filename=filename))
Exemplo n.º 10
0
    def test_register(self):
        print('\n---------------- %s' % self)

        #
        #  prepare register parameters
        #
        cmd = 3
        if cmd == 1:
            # generate SP
            seed = 'gsp'
            pattern = re.compile(r'^400\d+$')
            network = NetworkID.Provider
            print('*** registering SP (%s) with number match: %s' %
                  (seed, pattern))
        elif cmd == 2:
            # generate Station
            seed = 'gsp-s002'
            pattern = re.compile(r'^110\d+$')
            network = NetworkID.Station
            print('*** registering station (%s) with number match: %s' %
                  (seed, pattern))
        elif cmd == 3:
            # generate robot
            seed = 'assistant'
            pattern = re.compile(r'^000\d+$')
            network = NetworkID.Robot
            print('*** registering robot (%s) with number match: %s' %
                  (seed, pattern))
        else:
            # generate User
            seed = 'moky'
            pattern = re.compile(r'^\d+9527$')
            network = NetworkID.Main
            print('*** registering account (%s) with number match: %s' %
                  (seed, pattern))

        # seed
        data = seed.encode('utf-8')

        for index in range(0, 10000):

            # generate private key
            sk = PrivateKey({'algorithm': 'RSA'})
            ct = sk.sign(data)
            # generate address
            address = BTCAddress.new(data=ct, network=network)
            number = address.number

            if index % 10 == 0:
                print('[% 5d] %s : %s@%s' %
                      (index, number_string(number), seed, address))

            if not pattern.match('%010d' % number):
                continue

            print('**** GOT IT!')
            meta = {
                'version': Meta.DefaultVersion,
                'seed': seed,
                'key': sk.public_key,
                'fingerprint': base64_encode(ct),
            }
            meta = Meta(meta)
            id1 = meta.generate_identifier(network=network)
            print('[% 5d] %s : %s' % (index, number_string(number), id1))

            choice = ''
            while choice not in ['y', 'n']:
                choice = input('Save it (y/n)? ')

            if choice == 'y':
                print('---- Mission Accomplished! ----')
                print('**** ID:', id1, 'number:', number_string(id1.number))
                print('**** meta:\n', meta)
                print('**** private key:\n', sk)

                g_facebook.save_meta(identifier=id1, meta=meta)
                g_facebook.save_private_key(identifier=id1, private_key=sk)
                break
Exemplo n.º 11
0
    def test_register(self):
        print('\n---------------- %s' % self)

        #
        #  prepare register parameters
        #
        cmd = 3
        if cmd == 1:
            # generate SP
            seed = 'gsp'
            network = NetworkType.PROVIDER
            print('*** registering SP (%s)' % seed)
        elif cmd == 2:
            # generate Station
            seed = 'gsp-s002'
            network = NetworkType.STATION
            print('*** registering station (%s)' % seed)
        elif cmd == 3:
            # generate robot
            seed = 'chatroom-admin'
            network = NetworkType.ROBOT
            print('*** registering robot (%s)' % seed)
        else:
            # generate User
            seed = 'moky'
            network = NetworkType.MAIN
            print('*** registering account (%s)' % seed)

        # seed
        data = utf8_encode(string=seed)

        for index in range(0, 10000):

            # generate private key
            sk = PrivateKey.parse(key={'algorithm': 'RSA'})
            ct = sk.sign(data)
            # generate address
            address = BTCAddress.generate(fingerprint=ct, network=network)

            print('[% 5d] %s@%s' % (index, seed, address))

            meta = {
                'version': MetaType.DEFAULT.value,
                'seed': seed,
                'key': sk.public_key.dictionary,
                'fingerprint': base64_encode(ct),
            }
            meta = Meta.parse(meta=meta)
            id1 = meta.generate_identifier(network=network)
            print('[% 5d] %s' % (index, id1))

            choice = ''
            while choice not in ['y', 'n']:
                choice = input('Save it (y/n)? ')

            if choice == 'y':
                print('---- Mission Accomplished! ----')
                print('**** ID:', id1)
                print('**** meta:\n', meta)
                print('**** private key:\n', sk)

                g_facebook.save_meta(identifier=id1, meta=meta)
                g_facebook.save_private_key(identifier=id1, key=sk)
                break