I have a PDF file and I use this code to sign this file:
certificate = (X509Certificate) loadKeyStore(certificateFile, password).getCertificate(alias);
privateKey = (PrivateKey) loadKeyStore(certificateFile, password).getKey(alias, alias.toCharArray());
Security.addProvider(new BouncyCastleProvider());
BufferedInputStream inFile = new BufferedInputStream(new FileInputStream(origem));
byte[] dates = new byte[inFile.available()];
entrada.read(dates);
entrada.close();
CMSSignedDataGenerator genetateSign = new CMSSignedDataGenerator();
geradorAss.addSigner(privateKey, certificate, CMSSignedDataGenerator.DIGEST_SHA1);
List certList = new ArrayList();
certList.add(certificate);
CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList));
geradorAss.addCertificatesAndCRLs(certs);
// Efetivamente assinar os dados de entrada
CMSProcessable content = new CMSProcessableByteArray(dates);
String providerName;
if (ks.getType().equalsIgnoreCase("JKS")) {
providerName = BouncyCastleProvider.PROVIDER_NAME;
} else {
providerName = ks.getProvider().getName();
}
CMSSignedData signedDate = genetateSign.generate(content, providerName);
signedDate = new CMSSignedData(content, signedDate.getEncoded());
File f = Converter.converter("signedFile.pdf", signedDate.getEncoded());
But, the file f no open on reader. When I get the file f and run this code:
CMSSignedData data = new CMSSignedData(new FileInputStream(f));
Occur this error:
org.bouncycastle.cms.CMSException: Malformed content.
Someone can help me?
Summarizing:
I need to generate the final file after signing. For example, I have a test.pdf file, I want to sign and generate test_signed.pdf file. And this test_signed.pdf file must have the signature and should still be readable in your reader.
I'm waiting...
PDF has an embedded signature inside the document, while CMS is signature itself. To extract and verify signature from PDF use iText library. Here is an example.
Related
I implemented a signature feature in JAVA using PDFBox.
The signing part of my code is :
ExternalSigningSupport externalSigning = document.saveIncrementalForExternalSigning(output);
byte[] cmsSignature = new byte[0];
try {
Certificate[] certificationChain = SignatureUtils.getCertificateChain(alias);
X509Certificate certificate = (X509Certificate) certificationChain[0];
PrivateKey privateKey = SignatureUtils.getSignaturePrivateKey(alias, password);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
.build(sha1Signer, certificate));
gen.addCertificates(new JcaCertStore(Arrays.asList(certificationChain)));
CMSProcessableInputStream msg = new CMSProcessableInputStream(externalSigning.getContent());
CMSSignedData signedData = gen.generate(msg, false);
if (tsaUrl != null && !tsaUrl.isEmpty()) {
ValidationTimeStamp validation;
validation = new ValidationTimeStamp(tsaUrl);
signedData = validation.addSignedTimeStamp(signedData);
}
cmsSignature = signedData.getEncoded();
if (logger.isDebugEnabled()) {
logger.debug("signature length = " + cmsSignature.length);
logger.debug("certificate = " + certificate.toString());
}
} catch (GeneralSecurityException | CMSException | OperatorCreationException | IOException e) {
throw new SignatureException(e.getMessage());
}
externalSigning.setSignature(cmsSignature);
Everything works fine if I use my testing auto-signed certificate I generated with the keytool command.
The problem is, when I try this code with an existing certificate which is truly certified, I get the exeption :
Caused by: java.io.IOException: Can't write signature, not enough space
at org.apache.pdfbox.pdfwriter.COSWriter.writeExternalSignature(COSWriter.java:797)
at org.apache.pdfbox.pdmodel.interactive.digitalsignature.SigningSupport.setSignature(SigningSupport.java:48)
I have no idea why this doesn't work...
Any help would be appreciated ! =)
In a comment you mention that you get
signature length = 10721
in the log files and that you
didn't set any preferred size
By default PDFBox reserves 0x2500 bytes for the signature. That's 9472 bytes decimally. Thus, just like the exception says, there's not enough space.
You can set the size PDFBox reserves for the signature by using a SignatureOptions object during document.addSignature:
SignatureOptions signatureOptions = new SignatureOptions();
signatureOptions.setPreferredSignatureSize(20000);
document.addSignature(signature, signatureOptions);
I'm trying to sign a pdf document on the Java webapp running on the server, I have used hwcrypto.js and was able to successfully get the signature as well as the certificate. Now I'm trying to generate a pkcs7 encoded CMS signed data using below code:
String generatePkcs7EncodedSignature(String certString, String signature) {
try {
BASE64Decoder decoder = new BASE64Decoder()
byte[] signatureByte = decoder.decodeBuffer(signature)
List<Certificate> certList = getPublicCertificates(certString)
Store certs = new JcaCertStore(certList)
CMSProcessableByteArray msg = new CMSProcessableByteArray(signatureByte)
CMSSignedDataGenerator gen = new CMSSignedDataGenerator()
gen.addCertificates(certs)
CMSSignedData data = gen.generate(msg, true)
return Base64.getEncoder().encodeToString(data.getEncoded())
}
catch (Exception ex) {
println(ex.stackTrace)
}
return null
}
getPublicCertificates method is as follows:
X509Certificate getPublicCertificate(String certificateString)
throws IOException, CertificateException {
InputStream is = new ByteArrayInputStream(certificateString.getBytes(StandardCharsets.UTF_8))
CertificateFactory cf = CertificateFactory.getInstance("X.509")
Certificate cert = (X509Certificate) cf.generateCertificate(is)
return cert
}
But I'm getting "No Certificate to validate signature" error when I open the pdf in Adobe Reader
Please, could someone point me in the right direction to digitally sign an MS-Office document (docx, xlsx, pptx) in Apache POI, or any other open source library?
I have already reviewed the classes under org.apache.poi.openxml4j.opc.signature but I cannot understand how I could add a signature to a document.
Check this sample code .. this sample code uses a file keystore PFX (PKCS12) .. Signs the Document and verify it.
// loading the keystore - pkcs12 is used here, but of course jks & co are also valid
// the keystore needs to contain a private key and it's certificate having a
// 'digitalSignature' key usage
char password[] = "test".toCharArray();
File file = new File("test.pfx");
KeyStore keystore = KeyStore.getInstance("PKCS12");
FileInputStream fis = new FileInputStream(file);
keystore.load(fis, password);
fis.close();
// extracting private key and certificate
String alias = "xyz"; // alias of the keystore entry
Key key = keystore.getKey(alias, password);
X509Certificate x509 = (X509Certificate)keystore.getCertificate(alias);
// filling the SignatureConfig entries (minimum fields, more options are available ...)
SignatureConfig signatureConfig = new SignatureConfig();
signatureConfig.setKey(keyPair.getPrivate());
signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));
OPCPackage pkg = OPCPackage.open(..., PackageAccess.READ_WRITE);
signatureConfig.setOpcPackage(pkg);
// adding the signature document to the package
SignatureInfo si = new SignatureInfo();
si.setSignatureConfig(signatureConfig);
si.confirmSignature();
// optionally verify the generated signature
boolean b = si.verifySignature();
assert (b);
// write the changes back to disc
pkg.close();
Here's the sample source : https://poi.apache.org/apidocs/org/apache/poi/poifs/crypt/dsig/SignatureInfo.html
I hope this could help!
I have a pkcs7 file, and I want to load it and extract its contents.
I tried these two methods:
byte[] bytes = Files.readAllBytes(Paths.get("myfile.p7b"));
FileInputStream fi = new FileInputStream(file);
//Creating PKCS7 object
PKCS7 pkcs7Signature = new PKCS7(bytes);
or this
FileInputStream fis = new FileInputStream(new File("myfile.p7b"));
PKCS7 pkcs7Signature = new PKCS7(fis);
but I got IOException: Sequence tag error
So how can I load this .p7b file ?
Finally I did it with BouncyCastle library.
PKCS#7 is a complex format, also called CMS. Sun JCE has no direct support to PKCS#7.
This is the code that I used to extract my content:
// Loading the file first
File f = new File("myFile.p7b");
byte[] buffer = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f));
in.readFully(buffer);
in.close();
//Corresponding class of signed_data is CMSSignedData
CMSSignedData signature = new CMSSignedData(buffer);
Store cs = signature.getCertificates();
SignerInformationStore signers = signature.getSignerInfos();
Collection c = signers.getSigners();
Iterator it = c.iterator();
//the following array will contain the content of xml document
byte[] data = null;
while (it.hasNext()) {
SignerInformation signer = (SignerInformation) it.next();
Collection certCollection = cs.getMatches(signer.getSID());
Iterator certIt = certCollection.iterator();
X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
CMSProcessable sc = signature.getSignedContent();
data = (byte[]) sc.getContent();
}
If you want to verify the signature of this PKCS7 file against X509 certificate, you must add the following code to the while loop:
// ************************************************************* //
// ********************* Verify signature ********************** //
//get CA public key
// Create a X509 certificat
CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
// Open the certificate file
FileInputStream fileinputstream = new FileInputStream("myCA.cert");
//get CA public key
PublicKey pk = certificatefactory.generateCertificate(fileinputstream).getPublicKey();
X509Certificate myCA = new JcaX509CertificateConverter().setProvider("BC").getCertificate(cert);
myCA.verify(pk);
System.out.println("Verfication done successfully ");
I am new to Cryptography and so please excuse me if you think this is a basic question
I have a .p7b file which I need to read and extract the individual public certificates i.e the .cer files and store it in the key store. I need not worry about persisting in the key store as there is already a service which takes in the .cer file as byte[] and saves that.
What i want to know is , how do i read the .p7b and extract the individual .cer file? I know that can be done via the openSSL commands, but i need to do the same in java. I need to also read the Issued By name as that will be used as a unique key to persist the certificate.
Thanks in advance
You can get the certificates from a PKCS#7 object with BouncyCastle. Here is a quick code sample:
public Collection<X59Certificate> getCertificates(String path) throws Exception
{
Security.addProvider(new BouncyCastleProvider());
CMSSignedData sd = new CMSSignedData(new FileInputStream(path));
X509Store store = sd.getCertificates("Collection", "BC");
Collection<X509Certificate> certificates = store.getMatches(X509CertStoreSelector.getInstance(new X509CertSelector()));
return certificates;
}
Note that a PKCS#7 may contain more than one certificate. Most of the time it includes intermediate certification authority certificates required to build the certificate chain between the end-user certificate and the root CA.
I was successfully able to read the individual .X509 certificates from the p7b files. Here are the steps
First step includes, getting a byte[] from the java.io.File. The steps include to remove the -----BEGIN PKCS7----- and -----END PKCS7----- from the file, and decode the remaining base64 encoded String.
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder cerfile = new StringBuilder();
String line = null;
while(( line = reader.readLine())!=null){
if(!line.contains("PKCS7")){
cerfile.append(line);
}
}
byte[] fileBytes = Base64.decode(cerfile.toString().getBytes());
The next step is to use the BouncyCastle api to parse the file
CMSSignedData dataParser = new CMSSignedData(trustBundleByte);
ContentInfo contentInfo = dataParser.getContentInfo();
SignedData signedData = SignedData.getInstance(contentInfo.getContent());
CMSSignedData encapInfoBundle = new CMSSignedData(new CMSProcessableByteArray(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded()),contentInfo);
SignedData encapMetaData = SignedData.getInstance(encapInfoBundle.getContentInfo().getContent());
CMSProcessableByteArray cin = new CMSProcessableByteArray(((ASN1OctetString)encapMetaData.getEncapContentInfo().getContent()).getOctets());
CertificateFactory ucf = CertificateFactory.getInstance("X.509");
CMSSignedData unsignedParser = new CMSSignedData(cin.getInputStream());
ContentInfo unsginedEncapInfo = unsignedParser.getContentInfo();
SignedData metaData = SignedData.getInstance(unsginedEncapInfo.getContent());
Enumeration certificates = metaData.getCertificates().getObjects();
// Build certificate path
while (certificates.hasMoreElements()) {
DERObject certObj = (DERObject) certificates.nextElement();
InputStream bin = new ByteArrayInputStream(certObj.getDEREncoded());
X509Certificate cert = (X509Certificate) ucf.generateCertificate(bin);
X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
RDN cn = x500name.getRDNs(BCStyle.CN)[0];
}
The above steps are working fine, but i am sure there are other solutions with less lines of code to achieve this. I am using bcjdk16 jars.