oracle使用ssl+jdbc连接(1)

服务器端配置Wallet和生成证书(单向)

创建一个新的自动登录wallet

 mkdir -p /data0/app/oracle/wallet
 orapki wallet create -wallet "/data0/app/oracle/wallet" -pwd WalletPasswd123 -auto_login_local

创建一个自签名证书并将其加载到

orapki wallet add -wallet "/data0/app/oracle/wallet" -pwd WalletPasswd123 -dn "CN=`hostname`" -keysize 1024 -self_signed -validity 3650

检查wallet的内容,需要注意的是自签名证书既是用户也是可信证书

orapki wallet display -wallet "/data0/app/oracle/wallet" -pwd WalletPasswd123

导出证书,以便稍后将其加载到客户的wallet中

orapki wallet export -wallet "/data0/app/oracle/wallet" -pwd WalletPasswd123 -dn "CN=`hostname`" -cert /tmp/`hostname`-certificate.pem

检查证书是否已按预期导出

 cat /tmp/`hostname`-certificate.pem

将pem证书下载至客户端

keytool -import -trustcacerts -v -alias Mysql -file "server-certificate.pem" -keystore "oracle.jks"

jdbc代码

import org.omg.CORBA.PRIVATE_MEMBER;

import java.sql.*;
import java.util.Properties;

public class OracleSslConnectionTest {
    private  static final String DB_SERVER_NAME="192.168.126.154";
    private  static final Integer SSL_PORT=2484;
    private  static final String SERVICE_NAME="orcl11g.us.oracle.com";
    private  static final String DB_USER="test";
    private  static final String DB_PASSWORD="test";
    private  static final String KEY_STORE_FILE_PATH="C:\\Users\\13468\\Desktop\\fsdownload\\oracle.jks";
    private  static final String KEY_STORE_PASS="WalletPasswd123";

    public static void main(String[] args) throws SQLException{
        final Properties properties = new Properties();
        final String connectionString=String.format(
            "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCPS)(HOST=%s)(PORT=%d))(CONNECT_DATA=(SERVICE_NAME=%s)))",
                DB_SERVER_NAME,
                SSL_PORT,
                SERVICE_NAME
        );
        System.out.println(connectionString);
        properties.put("user",DB_USER);
        properties.put("password",DB_PASSWORD);
        properties.put("oracle.jdbc.J2EE13Complaint","true");
        properties.put("javax.net.ssl.trustStore",KEY_STORE_FILE_PATH);
        properties.put("javax.net.ssl.trustStoreType","JKS");
        properties.put("javax.net.ssl.trustStorePassword",KEY_STORE_PASS);

        final Connection connection= DriverManager.getConnection(connectionString,properties);
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery("select * from TEST");
        //4. 遍历查询结果
        while (rs.next()) {
            String ID = rs.getString("ID");
            String NAME = rs.getString("NAME");
            System.out.println(ID + "-" + NAME);
        }
    }
}

posted on 2022-03-07 14:31  BlogZhang  阅读(789)  评论(0编辑  收藏  举报

导航