gpt4 book ai didi

java - RSA加密post请求JAVA

转载 作者:行者123 更新时间:2023-12-01 23:52:54 25 4
gpt4 key购买 nike

我必须与平台进行集成。该平台为我提供了一个公钥来加密数据以调用他们的 API。在发送请求时,我需要考虑以下事项:

  1. 该请求是 HTTPS/POST 请求。
  2. 请求必须类似于:
{ 
Base64Encode(
RSA_Encrypt(
{ "a" : "111111", "b" : "12234", "c" : "2342342", "d" : "612413726581" }
)
)
}

我输入的参数如下:

Map<String, String> parameters = new HashMap<String, String>();
parameters.put("a", "112227");
parameters.put("b", "5411");
parameters.put("c", "12345678");
parameters.put("d", "123456");

加密如下:

StringBuilder sb = new StringBuilder();
sb.append("{");
for (String parameterName : parameters.keySet()) {
sb.append("\""+parameterName+"\"").append(':').append("\""+parameters.get(parameterName)+"\"").append(',');
}

String s=sb.toString();
s=s.replaceAll(",\\Z", "");
s=s+"}";

byte[] cleartext = s.getBytes("UTF-8");
String path="Path to certificate file\\rsa_apikey.cer";

FileInputStream fin = new FileInputStream(filename);
CertificateFactory f;
PublicKey pk;
try {
f = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
pk = certificate.getPublicKey();

} catch (CertificateException e) {

e.printStackTrace();
}
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pk);
byte[] ciphertext=cipher.doFinal(cleartext);
String securePayload = Base64.getEncoder().encodeToString(ciphertext);

之后,我将发送 POST 请求。请求仍然显示 400 bad request 错误。我不知道我做得是否正确。

问题1)请建议最好的方法是什么?

问题 2)我每次得到的 Base64 字符串“securePayload”都不同。这可能是请求错误的原因吗?

最佳答案

我的填充是错误的,因此我收到了错误。我更新到 PKCS1,现在工作正常。谢谢。

PublicKey publicKey=readPublicKey(path);

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.PUBLIC_KEY, publicKey);
byte[] ciphertext=cipher.doFinal(cleartext);

关于java - RSA加密post请求JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58214670/

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