我希望在Java中使用证书对文件内容进行签名。
通过终端和openssl,我可以这样做:
通过终端和openssl,我可以这样做:
openssl smime -sign -in nosign.mobileconfig -out signed.mobileconfig -signer server.crt -inkey server.key -certfile cacert.crt -outform der -nodetach
server.crt和.key是要签名的文件,我认为cacert.crt嵌入了输出内容中。
最终,我有一个被签名和信任的文件。
在Java中,我无法使用openssl(不想启动openssl命令),所以我必须使用库进行签名。
为此,我使用Bouncy Castle(版本1.53)。
这是我的代码:
byte[] profile = ...; // I can have it also in String
// the certificate in -certfile
FileInputStream inputStream = new FileInputStream("src/main/resources/cacert.crt");
byte[] caCertificate = ByteStreams.toByteArray(inputStream);
// the certificate to sign : server.crt, embedded in p12
X509Certificate serverCertificate = (X509Certificate) this.keyStore.getCertificate("1");
// Private key is the server.key
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(this.privateKey);
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, serverCertificate));
// the embedded certificate : cacert.crt, but I don't know if it is good to do that this way
X509CertificateHolder holder = new X509CertificateHolder(caCertificate);
generator.addCertificate(holder);
CMSProcessableByteArray bytes = new CMSProcessableByteArray(profile);
CMSSignedData signedData = generator.generate(bytes, true);
System.out.println("signedData : \n" + signedData.getEncoded());
你能帮我得到正确的签名数据吗?谢谢!
编辑: 我在这里遇到了一个错误。
X509CertificateHolder holder = new X509CertificateHolder(caCertificate);
java.io.IOException: 遇到未知标记13
X509CertificateHolder holder = new X509CertificateHolder(caCertificate);
java.io.IOException: 遇到未知标签13 我检查了cacert并且它是格式良好的。 - zarghol