pdb

Simple password manager
Log | Files | Refs | README

update-2-db-to-flatfiles.lua (1436B)


      1 local lfs = require( "lfs" )
      2 local symmetric = require( "symmetric" )
      3 local json = require( "cjson" )
      4 
      5 local dir = os.getenv( "HOME" ) .. "/.pdb/"
      6 local paths = {
      7 	old_db = dir .. "db2",
      8 	key = dir .. "key2",
      9 	new_db = dir .. "passwords/",
     10 }
     11 
     12 lfs.mkdir( paths.new_db )
     13 
     14 local function load_key()
     15 	local file, err = io.open( paths.key, "r" )
     16 	if not file then
     17 		io.stderr:write( "Unable to open key file: " .. err .. "\n" )
     18 		io.stderr:write( "You might need to create it with `pdb init`.\n" )
     19 		return os.exit( 1 )
     20 	end
     21 
     22 	local key = assert( file:read( "*all" ) ) -- TODO
     23 	file:close()
     24 
     25 	return key
     26 end
     27 
     28 local function load_db( key )
     29 	local file, err = io.open( paths.old_db, "r" )
     30 	if not file then
     31 		io.stderr:write( "Unable to open DB: " .. err .. "\n" )
     32 		io.stderr:write( "You might need to create it with `pdb init`.\n" )
     33 		return os.exit( 1 )
     34 	end
     35 
     36 	local ciphertext = assert( file:read( "*all" ) ) -- TODO
     37 	local plaintext = symmetric.decrypt( ciphertext, key )
     38 	if not plaintext then
     39 		io.stderr:write( "DB does not decrypt with the given key.\n" )
     40 		return os.exit( 1 )
     41 	end
     42 
     43 	local db = json.decode( plaintext )
     44 	if not db then
     45 		io.stderr:write( "DB does not appear to be in JSON format.\n" )
     46 		return os.exit( 1 )
     47 	end
     48 	
     49 	return db
     50 end
     51 
     52 local key = load_key()
     53 local db = load_db( key )
     54 
     55 for k, v in pairs( db ) do
     56 	local file = io.open( paths.new_db .. k, "w" )
     57 	file:write( symmetric.encrypt( v, key ) )
     58 	file:close()
     59 end