問題描述
用java中的充氣城堡簽署文件 (sign file with bouncy castle in java)
我想用 java 中的證書籤署文件內容。
使用終端和 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 嵌入在 out 內容中。
最後,我有一個文件簽名和信任。
在 Java 中,我不能使用openssl(不想啟動 openssl 命令)所以,我必須使用 lib 對其進行簽名。
為此,我使用 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
參考解法
方法 1:
The CA certificate file is obviously in PEM (ASCII) format. The constructor for X509CertificateHolder needs the BER/DER (binary) encoding of the certificate.
You can convert it by adding this:
PEMParser pemParser = new PEMParser(new FileReader("src/main/resources/cacert.crt"));
X509CertificateHolder caCertificate = (X509CertificateHolder) pemParser.readObject();
You should add the signing certificate to the CMS structure as well:
generator.addCertificate(new X509CertificateHolder(serverCertificate.getEncoded()));