use of org.bouncycastle.tsp.TimeStampTokenInfo in project itext2 by albfernandez.
the class PdfPKCS7 method verifyTimestampImprint.
/**
* Checks if the timestamp refers to this document.
* @throws java.security.NoSuchAlgorithmException on error
* @return true if it checks false otherwise
* @since 2.1.6
*/
public boolean verifyTimestampImprint() throws NoSuchAlgorithmException {
if (timeStampToken == null)
return false;
MessageImprint imprint = timeStampToken.getTimeStampInfo().toASN1Structure().getMessageImprint();
TimeStampTokenInfo info = timeStampToken.getTimeStampInfo();
String algOID = info.getMessageImprintAlgOID().getId();
byte[] md = MessageDigest.getInstance(getStandardJavaName(getDigest(algOID))).digest(digest);
byte[] imphashed = imprint.getHashedMessage();
boolean res = Arrays.equals(md, imphashed);
return res;
}
use of org.bouncycastle.tsp.TimeStampTokenInfo in project pdfbox by apache.
the class AddValidationInformation method doValidation.
/**
* Fetches certificate information from the last signature of the document and appends a DSS
* with the validation information to the document.
*
* @param filename in file to extract signature
* @param output where to write the changed document
* @throws IOException
*/
private void doValidation(String filename, OutputStream output) throws IOException {
certInformationHelper = new CertInformationCollector();
CertSignatureInformation certInfo = null;
try {
PDSignature signature = SigUtils.getLastRelevantSignature(document);
if (signature != null) {
certInfo = certInformationHelper.getLastCertInfo(signature, filename);
signDate = signature.getSignDate();
if ("ETSI.RFC3161".equals(signature.getSubFilter())) {
byte[] contents = signature.getContents();
TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(contents));
TimeStampTokenInfo timeStampInfo = timeStampToken.getTimeStampInfo();
signDate = Calendar.getInstance();
signDate.setTime(timeStampInfo.getGenTime());
}
}
} catch (TSPException | CMSException | CertificateProccessingException e) {
throw new IOException("An Error occurred processing the Signature", e);
}
if (certInfo == null) {
throw new IOException("No Certificate information or signature found in the given document");
}
PDDocumentCatalog docCatalog = document.getDocumentCatalog();
COSDictionary catalog = docCatalog.getCOSObject();
catalog.setNeedToBeUpdated(true);
COSDictionary dss = getOrCreateDictionaryEntry(COSDictionary.class, catalog, "DSS");
addExtensions(docCatalog);
vriBase = getOrCreateDictionaryEntry(COSDictionary.class, dss, "VRI");
ocsps = getOrCreateDictionaryEntry(COSArray.class, dss, "OCSPs");
crls = getOrCreateDictionaryEntry(COSArray.class, dss, "CRLs");
certs = getOrCreateDictionaryEntry(COSArray.class, dss, "Certs");
addRevocationData(certInfo);
addAllCertsToCertArray();
// write incremental
document.saveIncremental(output);
}
use of org.bouncycastle.tsp.TimeStampTokenInfo in project OpenPDF by LibrePDF.
the class TSAClientBouncyCastle method getTimeStampToken.
/**
* Get timestamp token - Bouncy Castle request encoding / decoding layer
* @param imprint a byte array containing the imprint
* @return the timestamp token
* @throws Exception on error
*/
protected byte[] getTimeStampToken(byte[] imprint) throws Exception {
byte[] respBytes = null;
try {
// Setup the time stamp request
TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
tsqGenerator.setCertReq(true);
if (isNotEmpty(policy)) {
tsqGenerator.setReqPolicy(new ASN1ObjectIdentifier(policy));
}
BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
ASN1ObjectIdentifier digestOid = X509ObjectIdentifiers.id_SHA1;
if (isNotEmpty(digestName)) {
digestOid = new ASN1ObjectIdentifier(PdfPKCS7.getDigestOid(digestName));
}
TimeStampRequest request = tsqGenerator.generate(digestOid, imprint, nonce);
byte[] requestBytes = request.getEncoded();
// Call the communications layer
respBytes = getTSAResponse(requestBytes);
// Handle the TSA response
TimeStampResponse response = new TimeStampResponse(respBytes);
// validate communication level attributes (RFC 3161 PKIStatus)
response.validate(request);
PKIFailureInfo failure = response.getFailInfo();
int value = (failure == null) ? 0 : failure.intValue();
if (value != 0) {
// PKIFailureInfo to string
throw new Exception(MessageLocalization.getComposedMessage("invalid.tsa.1.response.code.2", tsaURL, String.valueOf(value)));
}
// @todo: validate the time stap certificate chain (if we want
// assure we do not sign using an invalid timestamp).
// extract just the time stamp token (removes communication status
// info)
TimeStampToken tsToken = response.getTimeStampToken();
if (tsToken == null) {
throw new Exception(MessageLocalization.getComposedMessage("tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.getStatusString()));
}
// to view
TimeStampTokenInfo info = tsToken.getTimeStampInfo();
// details
byte[] encoded = tsToken.getEncoded();
long stop = System.currentTimeMillis();
// Update our token size estimate for the next call (padded to be
// safe)
this.tokSzEstimate = encoded.length + 32;
return encoded;
} catch (Exception e) {
throw e;
} catch (Throwable t) {
throw new Exception(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL), t);
}
}
use of org.bouncycastle.tsp.TimeStampTokenInfo in project signer by demoiselle.
the class TimeStampOperator method validate.
/**
* Validate a time stamp
*
* @param content if it is assigned, the parameter hash must to be null
* @param timeStamp timestamp to be validated
* @param hash if it is assigned, the parameter content must to be null
* @throws CertificateCoreException validate exception
*/
@SuppressWarnings("unchecked")
public void validate(byte[] content, byte[] timeStamp, byte[] hash) throws CertificateCoreException {
try {
TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(timeStamp));
CMSSignedData s = timeStampToken.toCMSSignedData();
int verified = 0;
Store<?> certStore = s.getCertificates();
SignerInformationStore signers = s.getSignerInfos();
Collection<SignerInformation> c = signers.getSigners();
Iterator<SignerInformation> it = c.iterator();
while (it.hasNext()) {
SignerInformation signer = it.next();
Collection<?> certCollection = certStore.getMatches(signer.getSID());
Iterator<?> certIt = certCollection.iterator();
X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert);
if (signer.verify(siv)) {
verified++;
}
cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue();
timeStampToken.validate(siv);
}
logger.debug(timeStampMessagesBundle.getString("info.signature.verified", verified));
// Valida o hash incluso no carimbo de tempo com hash do arquivo carimbado
byte[] calculatedHash = null;
if (content != null) {
Digest digest = DigestFactory.getInstance().factoryDefault();
TimeStampTokenInfo info = timeStampToken.getTimeStampInfo();
ASN1ObjectIdentifier algOID = info.getMessageImprintAlgOID();
digest.setAlgorithm(algOID.toString());
calculatedHash = digest.digest(content);
} else {
calculatedHash = hash;
}
if (Arrays.equals(calculatedHash, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
logger.debug(timeStampMessagesBundle.getString("info.timestamp.hash.ok"));
} else {
logger.error(timeStampMessagesBundle.getString("info.timestamp.hash.nok"));
throw new CertificateCoreException(timeStampMessagesBundle.getString("info.timestamp.hash.nok"));
}
} catch (TSPException | IOException | CMSException | OperatorCreationException | CertificateException ex) {
logger.error(ex.getMessage());
throw new CertificateCoreException(ex.getMessage());
}
}
use of org.bouncycastle.tsp.TimeStampTokenInfo in project pdfbox by apache.
the class ShowSignature method verifyETSIdotRFC3161.
/**
* Verify ETSI.RFC3161 TimeStampToken
*
* @param signedContentAsStream the byte sequence that has been signed
* @param contents the /Contents field as a COSString
* @throws CMSException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws TSPException
* @throws OperatorCreationException
* @throws CertificateVerificationException
* @throws CertificateException
*/
private void verifyETSIdotRFC3161(InputStream signedContentAsStream, byte[] contents) throws CMSException, NoSuchAlgorithmException, IOException, TSPException, OperatorCreationException, CertificateVerificationException, CertificateException {
TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(contents));
TimeStampTokenInfo timeStampInfo = timeStampToken.getTimeStampInfo();
System.out.println("Time stamp gen time: " + timeStampInfo.getGenTime());
if (timeStampInfo.getTsa() != null) {
System.out.println("Time stamp tsa name: " + timeStampInfo.getTsa().getName());
}
CertificateFactory factory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream certStream = new ByteArrayInputStream(contents);
Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
System.out.println("certs=" + certs);
String hashAlgorithm = timeStampInfo.getMessageImprintAlgOID().getId();
// compare the hash of the signed content with the hash in the timestamp
MessageDigest md = MessageDigest.getInstance(hashAlgorithm);
try (DigestInputStream dis = new DigestInputStream(signedContentAsStream, md)) {
while (dis.read() != -1) {
// do nothing
}
}
if (Arrays.equals(md.digest(), timeStampInfo.getMessageImprintDigest())) {
System.out.println("ETSI.RFC3161 timestamp signature verified");
} else {
System.err.println("ETSI.RFC3161 timestamp signature verification failed");
}
X509Certificate certFromTimeStamp = (X509Certificate) certs.iterator().next();
SigUtils.checkTimeStampCertificateUsage(certFromTimeStamp);
SigUtils.validateTimestampToken(timeStampToken);
SigUtils.verifyCertificateChain(timeStampToken.getCertificates(), certFromTimeStamp, timeStampInfo.getGenTime());
}
Aggregations