import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.StringWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class PrivatteKeyTest { /** * 先將私鑰存儲到數據庫中;而後從數據庫中獲取私鑰,並將私鑰保存到文件中 */ public static void main(String[] args) { // TODO Auto-generated method stub try { PrivatteKeyTest.saveKey("C:/new/private.ppk"); System.out.println("save Key finished!"); PrivatteKeyTest.createKeyFile(); System.out.println("create Key finished!"); } catch (Exception e) { // TODO Auto-generated catch block System.out.println(e.getMessage()); } } private static Connection getConnection() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:13306/mydb"; conn = DriverManager.getConnection(url, "root", "root"); } catch (Exception e) { // TODO Auto-generated catch block System.out.println(e.getMessage()); } return conn; } private static void closeConnection(Connection conn) throws SQLException{ conn.close(); } /* * 將密鑰從文件中存儲到數據庫中 */ private static boolean saveKey(String keyPath) throws Exception { boolean result = true; Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement("update ftp set FTP_PRIVATE_KEY = ? where ftp_id = 1"); String key = getKeyString(keyPath); ps.setString(1, key); result = ps.execute(); closeConnection(conn); return result; } /* * 將密鑰從數據庫中存儲到新建的文件中 */ private static void createKeyFile() throws Exception{ String key = getKeyStringFromDB(); File file = new File("C:/private.ppk"); FileWriter fw = new FileWriter(file); fw.write(key); fw.flush(); fw.close(); } /* * 從數據庫中獲取密鑰字符串 */ private static String getKeyStringFromDB() throws SQLException{ String key = null; Connection conn = getConnection(); Statement stst = conn.createStatement(); ResultSet rs = stst.executeQuery("select FTP_PRIVATE_KEY from ftp where ftp_id = 1"); while(rs.next()){ key = rs.getString("FTP_PRIVATE_KEY2"); } if(rs!=null){ rs.close(); } if(stst!=null){ stst.close(); } closeConnection(conn); return key; } /* * 將密鑰從文件中讀取出來 */ private static String getKeyString(String keyPath) throws Exception { File file = new File(keyPath); FileReader fr = new FileReader(file); StringWriter sw = new StringWriter(); int c = -1; while((c=fr.read()) != -1){ sw.write(c); } return sw.toString(); } }