use of org.bouncycastle.tsp.TimeStampToken in project tika by apache.
the class TSDParser method extractMetas.
private List<TSDMetas> extractMetas(InputStream stream) {
List<TSDMetas> tsdMetasList = new ArrayList<>();
try {
CMSTimeStampedData cmsTimeStampedData = new CMSTimeStampedData(stream);
TimeStampToken[] tokens = cmsTimeStampedData.getTimeStampTokens();
for (int i = 0; i < tokens.length; i++) {
TSDMetas tsdMetas = new TSDMetas(true, tokens[i].getTimeStampInfo().getGenTime(), tokens[i].getTimeStampInfo().getPolicy().getId(), tokens[i].getTimeStampInfo().getSerialNumber(), tokens[i].getTimeStampInfo().getTsa(), tokens[i].getTimeStampInfo().getHashAlgorithm().getAlgorithm().getId());
tsdMetasList.add(tsdMetas);
}
} catch (Exception ex) {
LOG.error("Error in TSDParser.buildMetas {}", ex.getMessage());
tsdMetasList.clear();
}
return tsdMetasList;
}
use of org.bouncycastle.tsp.TimeStampToken in project pdfbox by apache.
the class ShowSignature method showSignature.
private void showSignature(String[] args) throws IOException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, TSPException {
if (args.length != 2) {
usage();
} else {
String password = args[0];
File infile = new File(args[1]);
try (PDDocument document = PDDocument.load(infile, password)) {
for (PDSignature sig : document.getSignatureDictionaries()) {
COSDictionary sigDict = sig.getCOSObject();
COSString contents = (COSString) sigDict.getDictionaryObject(COSName.CONTENTS);
// download the signed content
byte[] buf;
try (FileInputStream fis = new FileInputStream(infile)) {
buf = sig.getSignedContent(fis);
}
System.out.println("Signature found");
int[] byteRange = sig.getByteRange();
if (byteRange.length != 4) {
System.err.println("Signature byteRange must have 4 items");
} else {
long fileLen = infile.length();
long rangeMax = byteRange[2] + (long) byteRange[3];
// multiply content length with 2 (because it is in hex in the PDF) and add 2 for < and >
int contentLen = contents.getString().length() * 2 + 2;
if (fileLen != rangeMax || byteRange[0] != 0 || byteRange[1] + contentLen != byteRange[2]) {
// a false result doesn't necessarily mean that the PDF is a fake
// see this answer why:
// https://stackoverflow.com/a/48185913/535646
System.out.println("Signature does not cover whole document");
} else {
System.out.println("Signature covers whole document");
}
}
if (sig.getName() != null) {
System.out.println("Name: " + sig.getName());
}
if (sig.getSignDate() != null) {
System.out.println("Modified: " + sdf.format(sig.getSignDate().getTime()));
}
String subFilter = sig.getSubFilter();
if (subFilter != null) {
switch(subFilter) {
case "adbe.pkcs7.detached":
case "ETSI.CAdES.detached":
verifyPKCS7(buf, contents, sig);
// TODO check certificate chain, revocation lists, timestamp...
break;
case "adbe.pkcs7.sha1":
{
// example: PDFBOX-1452.pdf
byte[] certData = contents.getBytes();
CertificateFactory factory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
System.out.println("certs=" + certs);
byte[] hash = MessageDigest.getInstance("SHA1").digest(buf);
verifyPKCS7(hash, contents, sig);
// TODO check certificate chain, revocation lists, timestamp...
break;
}
case "adbe.x509.rsa_sha1":
{
// example: PDFBOX-2693.pdf
COSString certString = (COSString) sigDict.getDictionaryObject(COSName.CERT);
if (certString == null) {
System.err.println("The /Cert certificate string is missing in the signature dictionary");
return;
}
byte[] certData = certString.getBytes();
CertificateFactory factory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
System.out.println("certs=" + certs);
// TODO verify signature
break;
}
case "ETSI.RFC3161":
TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(contents.getBytes()));
System.out.println("Time stamp gen time: " + timeStampToken.getTimeStampInfo().getGenTime());
System.out.println("Time stamp tsa name: " + timeStampToken.getTimeStampInfo().getTsa().getName());
CertificateFactory factory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream certStream = new ByteArrayInputStream(contents.getBytes());
Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
System.out.println("certs=" + certs);
// TODO verify signature
break;
default:
System.err.println("Unknown certificate type: " + subFilter);
break;
}
} else {
throw new IOException("Missing subfilter for cert dictionary");
}
}
analyseDSS(document);
} catch (CMSException | OperatorCreationException ex) {
throw new IOException(ex);
}
System.out.println("Analyzed: " + args[1]);
}
}
use of org.bouncycastle.tsp.TimeStampToken in project pdfbox by apache.
the class TSAClient method getTimeStampToken.
/**
* @param messageImprint imprint of message contents
* @return the encoded time stamp token
* @throws IOException if there was an error with the connection or data from the TSA server,
* or if the time stamp response could not be validated
*/
public byte[] getTimeStampToken(byte[] messageImprint) throws IOException {
digest.reset();
byte[] hash = digest.digest(messageImprint);
// 32-bit cryptographic nonce
SecureRandom random = new SecureRandom();
int nonce = random.nextInt();
// generate TSA request
TimeStampRequestGenerator tsaGenerator = new TimeStampRequestGenerator();
tsaGenerator.setCertReq(true);
ASN1ObjectIdentifier oid = getHashObjectIdentifier(digest.getAlgorithm());
TimeStampRequest request = tsaGenerator.generate(oid, hash, BigInteger.valueOf(nonce));
// get TSA response
byte[] tsaResponse = getTSAResponse(request.getEncoded());
TimeStampResponse response;
try {
response = new TimeStampResponse(tsaResponse);
response.validate(request);
} catch (TSPException e) {
throw new IOException(e);
}
TimeStampToken token = response.getTimeStampToken();
if (token == null) {
throw new IOException("Response does not have a time stamp token");
}
return token.getEncoded();
}
use of org.bouncycastle.tsp.TimeStampToken in project xades4j by luisgoncalves.
the class DefaultTimeStampVerificationProvider method verifyToken.
@Override
public Date verifyToken(byte[] timeStampToken, byte[] tsDigestInput) throws TimeStampTokenVerificationException {
TimeStampToken tsToken;
try {
ASN1InputStream asn1is = new ASN1InputStream(timeStampToken);
ContentInfo tsContentInfo = ContentInfo.getInstance(asn1is.readObject());
asn1is.close();
tsToken = new TimeStampToken(tsContentInfo);
} catch (IOException ex) {
throw new TimeStampTokenStructureException("Error parsing encoded token", ex);
} catch (TSPException ex) {
throw new TimeStampTokenStructureException("Invalid token", ex);
}
X509Certificate tsaCert = null;
try {
/* Validate the TSA certificate */
LinkedList<X509Certificate> certs = new LinkedList<X509Certificate>();
for (Object certHolder : tsToken.getCertificates().getMatches(new AllCertificatesSelector())) {
certs.add(this.x509CertificateConverter.getCertificate((X509CertificateHolder) certHolder));
}
ValidationData vData = this.certificateValidationProvider.validate(x509CertSelectorConverter.getCertSelector(tsToken.getSID()), tsToken.getTimeStampInfo().getGenTime(), certs);
tsaCert = vData.getCerts().get(0);
} catch (CertificateException ex) {
throw new TimeStampTokenVerificationException(ex.getMessage(), ex);
} catch (XAdES4jException ex) {
throw new TimeStampTokenTSACertException("cannot validate TSA certificate", ex);
}
try {
tsToken.validate(this.signerInfoVerifierBuilder.build(tsaCert));
} catch (TSPValidationException ex) {
throw new TimeStampTokenSignatureException("Invalid token signature or certificate", ex);
} catch (Exception ex) {
throw new TimeStampTokenVerificationException("Error when verifying the token signature", ex);
}
org.bouncycastle.tsp.TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo();
try {
String digestAlgUri = uriForDigest(tsTokenInfo.getMessageImprintAlgOID());
MessageDigest md = messageDigestProvider.getEngine(digestAlgUri);
if (!Arrays.equals(md.digest(tsDigestInput), tsTokenInfo.getMessageImprintDigest())) {
throw new TimeStampTokenDigestException();
}
} catch (UnsupportedAlgorithmException ex) {
throw new TimeStampTokenVerificationException("The token's digest algorithm is not supported", ex);
}
return tsTokenInfo.getGenTime();
}
use of org.bouncycastle.tsp.TimeStampToken in project signer by demoiselle.
the class CAdESChecker method validateTimestamp.
/**
* validade a timestampo on signature
* @param attributeTimeStamp
* @param varSignature
* @return
*/
private Timestamp validateTimestamp(Attribute attributeTimeStamp, byte[] varSignature) {
try {
TimeStampOperator timeStampOperator = new TimeStampOperator();
byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
Timestamp timeStampSigner = new Timestamp(timeStampToken);
timeStampOperator.validate(varSignature, varTimeStamp, null);
return timeStampSigner;
} catch (CertificateCoreException | IOException | TSPException | CMSException e) {
throw new SignerException(e);
}
}
Aggregations