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();
}
}