我正在使用 bouncycastle 版本15on
从 OcspServer 获取 ocspResponse,如下所示:
public OCSPResp getOcspResponse(OCSPReq request, String urlStr){
HttpURLConnection con = null;
OutputStream out = null;
DataOutputStream dataOut = null;
try {
byte[] array = request.getEncoded();
URL url = new URL(urlStr);
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "application/ocsp-request");
con.setRequestProperty("Accept", "application/ocsp-response");
con.setDoOutput(true);
out = con.getOutputStream();
dataOut = new DataOutputStream(new BufferedOutputStream(out));
dataOut.write(array);
dataOut.flush();
if (con.getResponseCode() / 100 != 2)
throw new Exception(...);
InputStream in = (InputStream) con.getContent();
if (in == null)
throw new Exception(...);
byte[] byteArrayInputStream = IOUtils.toByteArray(in);
return new OCSPResp(byteArrayInputStream);
} catch (IOException e) {
...
}finally {
...
}
}
然后我使用 将其转换OCSPResp
为 jsonString Gson version 2.2.4
,但是由于无参数构造函数问题,我无法将此 jsonString 恢复为原始 bouncycastle 对象,并且出现错误(相同的解决方案 1 错误)。谷歌搜索指导我开发两种方法来检索此 OCSPResp,如下所示,但没有人适合我:
解决方案1:向 Gson 注册一个 InstanceCreator
public class OCSPRespInstanceCreator implements InstanceCreator<OCSPResp> {
byte[] byteArrayInputStream = {48, -126, 6, ... , 27, 6, 67};
@Override
public OCSPResp createInstance(Type type) {
try {
OCSPResp ocspResp = new OCSPResp(byteArrayInputStream);
return ocspResp;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
应用解决方案1:
public static void main(String[] args) {
try {
String ocspJson = "{\"resp\":{\"responseStatus\":{\"value\":{\"bytes\":[0]}},\"responseBytes\":{\"responseType\":{\"identifier\":\"1.3.6.1.5.5.7.48.1.1\",\"body\":[43,6,1,5,5,7,48,1,1]},\"response\":{\"string\":[48,-126,6,51,48,...81,27,6,67]}}}}";
Gson gson = new GsonBuilder().registerTypeAdapter(OCSPResp.class, new OCSPRespInstanceCreator()).create();
OCSPResp ocspResp3 = gson.fromJson(ocspJson, OCSPResp.class);
} catch (Exception e) {
e.printStackTrace();
}
}
解决方案1的结果:
java.lang.RuntimeException:无法为类 org.bouncycastle.asn1.ASN1OctetString 调用无参数构造函数。向 Gson 注册此类型的 InstanceCreator 可能会解决此问题。
解决方案2:使用flexjson 3.2版
public static void main(String[] args) {
try {
String ocspJson = "{\"resp\":{\"responseStatus\":{\"value\":{\"bytes\":[0]}},\"responseBytes\":{\"responseType\":{\"identifier\":\"1.3.6.1.5.5.7.48.1.1\",\"body\":[43,6,1,5,5,7,48,1,1]},\"response\":{\"string\":[48,-126,6,51,48,-127,...,-46,108,81,27,6,67]}}}}";
OCSPResp ocspResp = new JSONDeserializer<OCSPResp>().deserialize(ocspJson);
} catch (Exception e) {
e.printStackTrace();
}
}
解决方案2的结果:
java.lang.ClassCastException:java.util.HashMap 无法转换为 org.bouncycastle.cert.ocsp.OCSPResp
这些解决方案的问题是什么?是否有第三种解决方案可以正确恢复为 bouncycastlejsonString
的原始OCSPResp
对象?