我正在尝试使用此question中的代码签名邮件。
我面临的问题是,我有一些毫无意义的废话而不是原创内容。 略有改动的代码:
public class BCTestSign2 {
static final String KEYSTORE_FILE = "c:\\clientkeystore";
static final String KEYSTORE_INSTANCE = "JKS";
static final String KEYSTORE_PWD = "javacaps";
static final String KEYSTORE_ALIAS = "client";
public static void main(String[] args) throws Exception {
String text = "This is a message";
Security.addProvider(new BouncyCastleProvider());
KeyStore ks = KeyStore.getInstance(KEYSTORE_INSTANCE);
ks.load(new FileInputStream(KEYSTORE_FILE), KEYSTORE_PWD.toCharArray());
Key key = ks.getKey(KEYSTORE_ALIAS, KEYSTORE_PWD.toCharArray());
//Sign
PrivateKey privKey = (PrivateKey) key;
Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
signature.initSign(privKey);
signature.update(text.getBytes());
//Build CMS
X509Certificate cert = (X509Certificate) ks.getCertificate(KEYSTORE_ALIAS);
List certList = new ArrayList();
CMSTypedData msg = new CMSProcessableByteArray(signature.sign());
certList.add(cert);
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));
gen.addCertificates(certs);
CMSSignedData sigData = gen.generate(msg, true);
System.out.print ("Signed content: ");
sigData.getSignedContent().write (System.out);
}
}
输出是:
签名内容:7!Ѓ'(2XжS^р««Ц8в@ uqШ<€&чcеЫR,ьћIк¤еџ“рМр”Гx|ЛЗжzҐЎНD,Y•*ґ№‰•^d1г,qNюТЉG°yюЄЭќ2ЉшОuхcS- Ѕљg[Яμр·№У_С`|еo“ќў‰†і
我使用相同的jar:bcprov-jdk16-1.46,bcmail-jdk16-1.46与v1.6编译器和jdk。 我也为后来的jdks和jar尝试了相同的代码。
有什么想法吗?
upd1: 我有一个签名文件的例子,其中包含显式签名消息。因此,您只需打开文件,然后在标志之间查看原始消息即可。当我得到“Enveloped data”(匹配原始帖子)时,我可以看到我的证书的详细信息,但是我找不到原始消息 - 只能从sigData.getSignedContent()获取哈希值。
答案 0 :(得分:0)
你试过吗
gen.generate(msg, false);
你得到了什么输出?