在這裏有很多人對我提出的問題提出了不同的解決方案,但他們中的任何一個都不適合我。我目前正在測試一個時間戳服務器和(除其他外,我正在向服務器發送一條消息),我需要閱讀該消息存在於答案中。所以我創建一個請求,並準備它:從MessageDigest獲取輸入文本
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
無論如何,我一直在盲目地嘗試所有我發現的建議,那會回到「Trolololoo」,但沒有成功。一些(但不限於)的事情我已經嘗試:
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看起來並不像一個十六進制字符串(原諒我,我在大學學過地質學)..這些東西對我來說都是非常新的,所以很難與編譯器或其他某些東西爭論。
只要確定:_ messageImprint必須與 TimeStampReq中的相似字段具有相同的值,前提是該散列值的大小與hashAlgorithm._ [Ref]中標識的散列算法的預期大小相匹配 (https ://www.ietf.org/rfc/rfc3161.txt)(第8頁)意味着只比較哈希值? –
我建議你下定決心這個問題是真的。它已經有一個不正確的標題。如果你問如何實現RFC 3161,你應該這麼說。 – EJP
我不需要實現,但我必須在不久的將來測試實現,因爲所有這些CA和PKI等東西對我來說都是非常新的,我只是稍微玩弄一下。無論如何,如果無法將消息摘要轉換回來,那麼這將回答這個具體問題。 –