SO上有很多人提出了解决我遇到的问题的不同方法,但似乎没有一个对我有用。我目前正在测试时间戳服务器,并且(除其他外,我正在向服务器发送一条消息)并且我需要阅读该消息是否存在于答案中。所以我正在创建一个请求并准备它:
MessageDigest digest = MessageDigest.getInstance("SHA1");
String s = "Trolololoooo";
DigestInputStream stream = new DigestInputStream(new ByteArrayInputStream(s.getBytes("UTF-8")), digest)
byte[] digest2 = stream.getMessageDigest().digest();
// timestamp stuff is all org.bouncycastle.tsp.*
TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
timeStampRequestGenerator.setReqPolicy(String.valueOf(new ASN1ObjectIdentifier("1.3.6.1.4.1.13762.3")));
TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest2, BigInteger.valueOf(666));
byte request[] = timeStampRequest.getEncoded();
...跳过发送部分,好的得到答案
InputStream in = con.getInputStream();
TimeStampResp resp = TimeStampResp.getInstance(new ASN1InputStream(in).readObject());
TimeStampResponse response = new TimeStampResponse(resp);
response.validate(timeStampRequest);
现在,从响应中,我可以成功读取字节流,例如:
byte[] messageImprintDigest1 = response.getTimeStampToken().getTimeStampInfo().getMessageImprintDigest();
for( byte b : messageImprintDigest1) System.out.print(b);
将输出:-3857-93-189410775135085-65-17-1079624-112-81-4079
无论如何,我一直在盲目地尝试我发现的所有建议,这些建议会转化为“Trolololoooo”,但没有成功。我尝试过的一些(不限于)事情:
String s1 = DigestUtils.sha1Hex(messageImprintDigest1);
String s2 = new String(Hex.decodeHex(s1.toCharArray()), "UTF-8");
// how could that help me..? but nothing to lose here.
String s3 = Hex.encodeHexString(messageImprintDigest1);
String convert = convert(s1);
// String convert1 = convert(s2);
// String convert2 = convert(s3);
int len = s1.length();
byte[] cStr = new byte[len/2];
for(int i = 0; i < len; i+=2) {
cStr[i/2] = (byte)Integer.parseInt(s1.substring(i, i+2), 16);
}
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.IGNORE);
ByteBuffer wrap = ByteBuffer.wrap(cStr);
CharBuffer decode = decoder.decode(wrap);
CharBuffer cb = decoder.decode( ByteBuffer.wrap( cStr ));
String s4 = cb.toString();
...
public static String convert(String hex){
ByteBuffer buff = ByteBuffer.allocate(hex.length()/2);
for (int i = 0; i < hex.length(); i+=2) {
buff.put((byte)Integer.parseInt(hex.substring(i, i+2), 16));
}
buff.rewind();
Charset cs = Charset.forName("UTF-8");
CharBuffer cb = cs.decode(buff);
return cb.toString();
}
无论如何,这可能是我缺少的一些明显的东西,比如 messageImprintDigest1 看起来根本不像一个十六进制字符串(请原谅我,我在大学学习地质学)。这些东西对我来说都很新,所以它是很难与编译器或其他一些东西争论。