aliases = keystore.aliases();
String alias;
Certificate cert = null;
while (cert == null && aliases.hasMoreElements())
{
alias = aliases.nextElement();
setPrivateKey((PrivateKey) keystore.getKey(alias, pin));
Certificate[] certChain = keystore.getCertificateChain(alias);
if (certChain != null)
{
setCertificateChain(certChain);
cert = certChain[0];
if (cert instanceof X509Certificate)
{
// avoid expired certificate
((X509Certificate) cert).checkValidity();
SigUtils.checkCertificateUsage((X509Certificate) cert);
}
}
}
if (cert == null)
{
throw new IOException("Could not find certificate");
}
}
public final void setPrivateKey(PrivateKey privateKey)
{
this.privateKey = privateKey;
}
public final void setCertificateChain(final Certificate[] certificateChain)
{
this.certificateChain = certificateChain;
}
public Certificate[] getCertificateChain()
{
return certificateChain;
}
public void setTsaUrl(String tsaUrl)
{
this.tsaUrl = tsaUrl;
}
/**
* SignatureInterface sample implementation.
*
* This method will be called from inside of the pdfbox and create the PKCS #7 signature.
* The given InputStream contains the bytes that are given by the byte range.
*
* This method is for internal use only.
*
* Use your favorite cryptographic library to implement PKCS #7 signature creation.
* If you want to create the hash and the signature separately (e.g. to transfer only the hash
* to an external application), read
this
* answer
or
this answer
.
*
* @throws IOException
*/
@Override
public byte[] sign(InputStream content) throws IOException
{
// cannot be done private (interface)
try
{
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
X509Certificate cert = (X509Certificate) certificateChain[0];
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(sha1Signer, cert));
gen.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
CMSSignedData signedData = gen.generate(msg, false);
if (tsaUrl != null && !tsaUrl.isEmpty())
{
ValidationTimeStamp validation = new ValidationTimeStamp(tsaUrl);
signedData = validation.addSignedTimeStamp(signedData);
}
return signedData.getEncoded();
}
catch (GeneralSecurityException | CMSException | OperatorCreationException | URISyntaxException e)
{
throw new IOException(e);
}
}
/**
* Set if external signing scenario should be used.
* If {@code false}, SignatureInterface would be used for signing.
*
* Default: {@code false}
*
* @param externalSigning {@code true} if external signing should be performed
*/
public void setExternalSigning(boolean externalSigning)
{
this.externalSigning = externalSigning;
}
public boolean isExternalSigning()
{
return externalSigning;
}
}