我需要简单地为字符串值生成数字签名。我试图修改this示例,但没有成功尝试使其适用于字符串值。我最终使用了这段代码:
public static byte[] signData(byte[] data) throws Exception {
Provider bouncyCastle = new org.bouncycastle.jce.provider.BouncyCastleProvider();
PGPSecretKeyRingCollection secretKeyRings = new PGPSecretKeyRingCollection(new FileInputStream(new File("/path_to_binary.gpg")));
PGPSecretKeyRing secretKeyRing = (PGPSecretKeyRing) secretKeyRings.getKeyRings().next();
PGPSecretKey secretKey = (PGPSecretKey) secretKeyRing.getSecretKeys().next();
PGPPrivateKey pgpPrivateKey = secretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider(bouncyCastle).build("password".toCharArray()));
PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1).setProvider(bouncyCastle));
PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
sGen.init(PGPSignature.STAND_ALONE, pgpPrivateKey);
Iterator userIDs = secretKey.getPublicKey().getUserIDs();
if (userIDs.hasNext()) {
spGen.setSignerUserID(false, (String)userIDs.next());
sGen.setHashedSubpackets(spGen.generate());
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
sGen.update(data);
baos.write(data);
sGen.generateOnePassVersion(false).encode(baos);
baos.flush();
baos.close();
return baos.toByteArray();
}
得到了这个结果(字符串表示):
[B@50867e0f
显然不是数字签名。我做错了什么?