gpt4 book ai didi

grails - 我如何在 grails 中使用 *.p12 证书来建立 https 连接?

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:54 25 4
gpt4 key购买 nike

我正在尝试通过 https 连接到我的后端。我有 2 个证书 *.p12 和 *.cer。我是用命令导入的(见代码)我使用命令导入 key :

keytool -v -importkeystore -srckeystore bonus-testagent.p12 -srcstoretype PKCS12 -destkeystore truststore.jks -deststoretype JKS

我的代码是(grails 服务):

private SSLSocketFactory getSSLFactory() throws Exception {
KeyStore keyStore = KeyStore.getInstance("JKS");
String keystoreFile = 'D:\\grails_wide\\certificates\\truststore.jks'
File binaryFile = new File(keystoreFile);
InputStream is = binaryFile.newInputStream()
if (is == null) {
return null;
}
String password = "****";
keyStore.load(is, password.toCharArray());
is.close();


TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);

SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
return ctx.getSocketFactory();
}

def accountInfo(String cardNumber, Cookie[] cookies) {
String urlStr = "https://app-domain.com";
URL url = new URL(urlStr);

HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(getSSLFactory());
conn.setRequestMethod("GET");
conn.setRequestProperty("Cookie", WebUtils.buildCookiesHeader(cookies))
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer stringBuffer = new StringBuffer();
while ((line = rd.readLine()) != null) {
stringBuffer.append(line);
}
rd.close();
def response = stringBuffer.toString();

但是有错误:

ERROR errors.GrailsExceptionResolver  - SunCertPathBuilderException occurred when processing request: [POST] /club/account
unable to find valid certification path to requested target. Stacktrace follows:
Message: unable to find valid certification path to requested target

在字符串中:

InputStream is = conn.getInputStream();

最佳答案

首先,您通常不需要将 PKCS#12 (.p12) 文件转换为 JKS 存储,您可以直接使用 PKCS12 keystore 类型。

其次,.p12 文件通常不用作信任库,而是用作 keystore 。 (例如,请参阅 this question 以了解 keystore 和信任库之间的区别。).p12 文件将包含不属于信任库的私钥 Material 。

您在这里所做的是用您的 .p12 文件替换默认的信任库,因此它只能在连接时根据您的 .p12 文件中的证书进行验证远程(而不是根据 CA 证书进行验证)。因此,它失败并显示“无法找到到所请求目标的有效证书路径”。

据推测,您正在尝试连接客户端证书。在这种情况下,您需要将该 .p12 文件用作 keystore。为此:

  1. (可选)如果您想直接加载 .p12,请改用 KeyStore.getInstance("PKCS12")。 (您不需要那个 keytool 转换。)
  2. 将其与 KeyManagerFactory 一起使用,而不是 TrustManagerFactory。初始密码将是 key 本身的密码,与 PKCS#12 中的存储 key 相同。
  3. 使用 ctx.init(kmf.getKeyManagers(), null, null)。第二个 null 参数将使用 JRE 的默认信任库(假设您的服务器以这种方式受信任)。

关于grails - 我如何在 grails 中使用 *.p12 证书来建立 https 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22072463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com