私钥的保存与获取

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

}

 

 

 

 

转载于:https://my.oschina.net/u/3644171/blog/1527355

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值