我正在使用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
将此Gson version 2.2.4
转换为jsonString,但是由于无参数构造函数的问题,我无法将此jsonString还原回原始的bouncycastle对象,并且出现错误(相同solution1错误)。谷歌搜索指导我开发出两种方法来检索此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
这些解决方案有什么问题?
是否存在第三种解决方案,可以将jsonString
正确地还原为Bouncycastle的原始OCSPResp
对象?