我正在尝试在bouncycastle版本1.49中使用非弃用的构造函数,但我很难弄清楚如何使用这些创建的对象,因为它与我的任何教程有点不同在网上找到了。
这是我的代码到目前为止;任何人都可以告诉我我应该用PGPContentSigner做什么,以及我应该如何将它连接到OutputStream?我想要实现的是数据的附加签名,而不必将数据加密到任何人(非常像gpg --clearsign -a <textfile>
)。
我查看了ArmoredOutputStream
及其方法,beginClearText(int)
看起来很有希望,但只是调用它,将数据转储到输出流中,调用endClearText
,然后编写签名字节到ArmoredOutputStream
不起作用。它看起来好像需要对流进行低级操作,将控制字节戳到流中以表示签名的开始等等。在我看来应该有某种夹具来挂钩签名者和装甲输出流一起处理那个小包杂耍。
/**
* Generate a signature for the given bytes so that they can be sent off and the recipient can verify
* that the bytes have not been tampered with in transit.
*
* @param dataBytes the data to sign
* @return the data along with the signature
* @throws PGPException if there's a problem generating the signature
*/
public static byte[] clearSignBytes(byte[] dataBytes, PGPSecretKeyRingCollection skrCollection, String keyPass) throws PGPException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); // this is where we put the signed data
try {
// get our secret key so we can init the signature generator
Iterator<PGPSecretKeyRing> it = skrCollection.getKeyRings();
PGPSecretKeyRing skr = it.next();
PGPSecretKey skey = skr.getSecretKey();
PGPPrivateKey prKey = skey.extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(keyPass.toCharArray()));
BcPGPContentSignerBuilder signerBuilder = new BcPGPContentSignerBuilder(skey.getPublicKey().getAlgorithm(), PGPUtil.SHA256);
PGPContentSigner signer = signerBuilder.build(PGPSignature.BINARY_DOCUMENT, prKey);
// Now, we're supposed to write dataBytes somewhere and we're supposed to hand them to the signer somehow
// and ultimately we're supposed to tell the signer to output a signature and we put the signature and
// dataBytes together into baos.
// TODO ??????
} catch (Exception e) {
__l.error("Exception generating signature", e);
throw new PGPException("Exception while signing the data", e);
}
return baos.toByteArray();
}
答案 0 :(得分:2)
原来我没有使用合适的类来完成工作。以下是该方法的相关部分,其中包含实际可行的代码。我希望这能帮助那些有同样困惑的人。在我们得到PGPPrivateKey prKey...
PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(skey.getPublicKey().getAlgorithm(), PGPUtil.SHA256).setProvider("BC"));
PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
sGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, prKey);
Iterator userIDs = skey.getPublicKey().getUserIDs();
if (it.hasNext()) {
spGen.setSignerUserID(false, (String)userIDs.next());
sGen.setHashedSubpackets(spGen.generate());
}
ArmoredOutputStream aos = new ArmoredOutputStream(baos);
aos.beginClearText(PGPUtil.SHA256);
sGen.update(dataBytes);
aos.write(dataBytes);
aos.endClearText();
BCPGOutputStream bOut = new BCPGOutputStream(aos);
sGen.generate().encode(bOut);
aos.flush();
aos.close();