V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
linuxsteam
V2EX  ›  问与答

Java 怎么使用自签证书访问双向认证的网站?

  •  
  •   linuxsteam · 2022-11-09 20:22:38 +08:00 · 845 次点击
    这是一个创建于 525 天前的主题,其中的信息可能已经有所发展或是发生改变。

    需求

    目前想要在 Java 程序中调用客户的网站。我搜索了一些资料,排除了代码中内嵌证书的操作(因为客户提供的 SDK 不支持自定义证书)。 所以选择 向 Jdk 信任证书导入自签证书。但是没有操作成功

    前置测试操作

    首先我拿到客户自签的一个客户端 PKCS12 证书链文件 client.p12

    • 使用 openssl 转换成公钥 client.crt 和私钥 client.key

    • 自行用 curl 测试公钥密钥是否可用 curl --cert client.crt --key client.key -X GET -H "Content-Type: application/json" "https://xxx.com" 是可以正常握手的。

    使用 Java 开始干活

    导入证书到 keystore

    keytool -import -alias client -keystore "C:\Program Files\Zulu\zulu-17\lib\security\cacerts" -storepass changeit -file .\client.crt -trustcacerts

    代码测试
    • 尝试使用 Jdk 导入的自签证书
    String result = HttpUtil.createGet("https://xxx.com")
                    .timeout(5 * 60 * 1000)
                    .execute()
                    .sync()
                    .body();
    

    报错 Exception in thread "main" cn.hutool.core.io.IORuntimeException: SSLHandshakeException: Received fatal alert: bad_certificate

    • 选用代码调“死”证书也不行

    生成 jks

    keytool -importkeystore -srckeystore client.p12 -srcstoretype PKCS12 -deststoretype JKS -destkeystore client.jks

    System.setProperty("javax.net.ssl.trustStore","D:\\test\\client.jks");
    System.setProperty("javax.net.ssl.trustStorePassword", "password");
    String result = HttpUtil.createGet("https://xxx.com")
                    .timeout(5 * 60 * 1000)
                    .execute()
                    .sync()
                    .body();
    

    疑问

    求助 我是哪里操作错了吗?请赐教,小弟已经铜鼓很久了。网络知识太菜了 加了 jvm 参数(-Djavax.net.debug=ssl:handshake ) 看了握手日志也没看明白

    linuxsteam
        1
    linuxsteam  
    OP
       2022-11-09 20:44:10 +08:00
    顶一顶
    linuxsteam
        2
    linuxsteam  
    OP
       2022-11-10 06:54:36 +08:00 via iPhone
    😫
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5307 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 09:07 · PVG 17:07 · LAX 02:07 · JFK 05:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.