下面是我用来执行简单 HTTPS 请求的代码的简化版本:
// Assume the variables host, file and postData have valid String values
final URL url = new URL("https", host, file);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-length", String.valueOf(postData.length()));
final DataOutputStream output = new DataOutputStream(connection.getOutputStream());
output.writeBytes(postData);
output.close();
final InputStream input = new DataInputStream(connection.getInputStream());
for (int c = input.read(); c != -1; c = input.read()) {
System.out.print((char) c);
}
System.out.println();
input.close();
过去,这对于连接到我们的服务器非常有效(如果我使用 http 作为协议,仍然有效),直到最近完成了一些安全升级。
现在它给我这个问题中提到的“无法生成 DH 密钥对”和“质数大小必须是 64 的倍数,并且只能范围从 512 到 1024(含)”错误:
Java:为什么 SSL 握手会出现“无法生成 DH 密钥对”异常? https://stackoverflow.com/questions/6851461/java-why-does-ssl-handshake-give-could-not-generate-dh-keypair-exception
事实证明这是 Java 中的一个已知错误,建议使用 BouncyCastle 的 JCE 实现。
我的问题是......我如何使用 BouncyCastle 来做这样的事情?或者还有更多的选择吗?
免责声明:我对密码学和使 HTTPS 查询成为可能的底层技术知之甚少,也没有兴趣。相反,我更愿意专注于我的应用程序逻辑,并让各种库处理低级问题。
我查看了 BouncyCastle 网站和文档,并通过 Google 搜索来了解有关 JCE 等的更多信息,但总而言之,它相当令人难以承受,而且我无法找到任何简单的代码示例来执行类似上述代码的操作。