def register_key(key_id, openssh_input_string, keys_folder=None, output_type='openssh'): """ """ if key_id in known_keys(): lg.warn('key %s already exists' % key_id) return None key_object = unserialize_key_to_object(openssh_input_string) if not key_object: lg.warn('invalid openssh string, unserialize_key_to_object() failed') return None lg.out( 4, 'my_keys.register_key %s from %d bytes openssh_input_string' % (key_id, len(openssh_input_string))) known_keys()[key_id] = key_object if not keys_folder: keys_folder = settings.PrivateKeysDir() key_string = key_object.toString(output_type) key_filepath = os.path.join(keys_folder, key_id) bpio.WriteFile(key_filepath, key_string) if _Debug: lg.out(_DebugLevel, ' key %s saved to %s' % (key_id, key_filepath)) return key_object
def erase_key(key_id, keys_folder=None): """ """ if key_id not in known_keys(): lg.warn('key %s is not found' % key_id) return False if not keys_folder: keys_folder = settings.PrivateKeysDir() key_filepath = os.path.join(keys_folder, key_id) try: os.remove(key_filepath) except: lg.exc() return False known_keys().pop(key_id) return True
def save_keys_local(keys_folder=None, output_type='openssh'): """ """ if not keys_folder: keys_folder = settings.PrivateKeysDir() if _Debug: lg.out( _DebugLevel, 'my_keys.save_keys_local will store all known keys in %s' % keys_folder) count = 0 for key_id, key_object in known_keys().items(): key_string = key_object.toString(output_type) key_filepath = os.path.join(keys_folder, key_id) bpio.WriteFile(key_filepath, key_string) count += 1 if _Debug: lg.out(_DebugLevel, ' %d keys saved' % count)
def generate_key(key_id, key_size=4096, keys_folder=None, output_type='openssh'): """ """ if key_id in known_keys(): lg.warn('key "%s" already exists' % key_id) return None lg.out(4, 'my_keys.generate_key "%s" of %d bits' % (key_id, key_size)) rsa_key = RSA.generate(key_size, os.urandom) key_object = keys.Key(rsa_key) known_keys()[key_id] = key_object if not keys_folder: keys_folder = settings.PrivateKeysDir() key_string = key_object.toString(output_type) key_filepath = os.path.join(keys_folder, key_id) bpio.WriteFile(key_filepath, key_string) if _Debug: lg.out(_DebugLevel, ' key %s saved to %s' % (key_id, key_filepath)) return key_object
def load_local_keys(keys_folder=None): """ """ if not keys_folder: keys_folder = settings.PrivateKeysDir() if _Debug: lg.out(_DebugLevel, 'my_keys.load_local_keys will read files from %s' % keys_folder) known_keys().clear() count = 0 for key_id in os.listdir(keys_folder): key_filepath = os.path.join(keys_folder, key_id) try: key_object = keys.Key.fromFile(key_filepath) except: lg.exc() continue if not validate_key(key_object): lg.warn('validation failed for %s key' % key_id) continue known_keys()[key_id] = key_object count += 1 if _Debug: lg.out(_DebugLevel, ' %d keys loaded' % count)