List of usage examples for org.bouncycastle.cms CMSException getUnderlyingException
public Exception getUnderlyingException()
From source file:de.rub.dez6a3.jpdfsigner.TimeStampToken.java
License:Open Source License
public TimeStampToken(CMSSignedData signedData) throws TSPException, IOException { this.tsToken = signedData; if (!this.tsToken.getSignedContentTypeOID().equals(PKCSObjectIdentifiers.id_ct_TSTInfo.getId())) { throw new TSPValidationException("ContentInfo object not for a time stamp."); }/* ww w . ja v a2s . c o m*/ Collection signers = tsToken.getSignerInfos().getSigners(); if (signers.size() != 1) { throw new IllegalArgumentException("Time-stamp token signed by " + signers.size() + " signers, but it must contain just the TSA signature."); } tsaSignerInfo = (SignerInformation) signers.iterator().next(); try { CMSProcessable content = tsToken.getSignedContent(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); content.write(bOut); ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bOut.toByteArray())); this.tstInfo = new TimeStampTokenInfo(TSTInfo.getInstance(aIn.readObject())); Attribute attr = tsaSignerInfo.getSignedAttributes() .get(PKCSObjectIdentifiers.id_aa_signingCertificate); if (attr == null) { throw new TSPValidationException("no signing certificate attribute found, time stamp invalid."); } SigningCertificate signCert = SigningCertificate.getInstance(attr.getAttrValues().getObjectAt(0)); this.certID = ESSCertID.getInstance(signCert.getCerts()[0]); } catch (CMSException e) { throw new TSPException(e.getMessage(), e.getUnderlyingException()); } }
From source file:de.rub.dez6a3.jpdfsigner.TimeStampToken.java
License:Open Source License
/** * Validate the time stamp token./*from w w w. ja v a2 s.c o m*/ * <p> * To be valid the token must be signed by the passed in certificate and * the certificate must be the one refered to by the SigningCertificate * attribute included in the hashed attributes of the token. The * certifcate must also have the ExtendedKeyUsageExtension with only * KeyPurposeId.id_kp_timeStamping and have been valid at the time the * timestamp was created. * </p> * <p> * A successful call to validate means all the above are true. * </p> */ public void validate(X509Certificate cert, String provider) throws TSPException, TSPValidationException, CertificateExpiredException, CertificateNotYetValidException, NoSuchProviderException { try { if (!MessageDigest.isEqual(certID.getCertHash(), MessageDigest.getInstance("SHA-1").digest(cert.getEncoded()))) { throw new TSPValidationException("certificate hash does not match certID hash."); } if (certID.getIssuerSerial() != null) { if (!certID.getIssuerSerial().getSerial().getValue().equals(cert.getSerialNumber())) { throw new TSPValidationException( "certificate serial number does not match certID for signature."); } GeneralName[] names = certID.getIssuerSerial().getIssuer().getNames(); X509Principal principal = PrincipalUtil.getIssuerX509Principal(cert); boolean found = false; for (int i = 0; i != names.length; i++) { if (names[i].getTagNo() == 4 && new X509Principal(X509Name.getInstance(names[i].getName())).equals(principal)) { found = true; break; } } if (!found) { throw new TSPValidationException("certificate name does not match certID for signature. "); } } TSPUtil.validateCertificate(cert); cert.checkValidity(tstInfo.getGenTime()); if (!tsaSignerInfo.verify(cert, provider)) { throw new TSPValidationException("signature not created by certificate."); } } catch (CMSException e) { if (e.getUnderlyingException() != null) { throw new TSPException(e.getMessage(), e.getUnderlyingException()); } else { throw new TSPException("CMS exception: " + e, e); } } catch (NoSuchAlgorithmException e) { throw new TSPException("cannot find algorithm: " + e, e); } catch (CertificateEncodingException e) { throw new TSPException("problem processing certificate: " + e, e); } }
From source file:org.dihedron.crypto.operations.encrypt.EncryptZipFile.java
License:Open Source License
public void encrypt(InputStream plaintext, OutputStream encrypted, String provider, String url, String name, String filter) {// w w w .j a v a 2 s . c o m logger.info("starting encryption"); X509Certificate certificate = null; boolean okCertificato = true; try { logger.info("starting encryption process..."); Properties configuration = new Properties(); configuration.setProperty("provider", provider); configuration.setProperty("ldap.url", url); CertificateLoader loader = CertificateLoaderFactory.makeCertificateLoader(configuration); Properties parameters = new Properties(); parameters.put("name", name); parameters.put("filter", filter); certificate = (X509Certificate) loader.loadCertificate(parameters); logger.info("certificate algorithm: " + certificate.getPublicKey().getAlgorithm()); String[] issuerInfo = certificate.getIssuerDN().getName().split("(=|, )", -1); String[] subjectInfo = certificate.getSubjectDN().getName().split("(=|, )", -1); logger.debug("common name (CN) : " + subjectInfo[3]); logger.debug("address : " + subjectInfo[1] + "\n"); for (int i = 0; i < issuerInfo.length; i += 2) { if (issuerInfo[i].equals("C")) logger.debug("CountryName : " + issuerInfo[i + 1]); if (issuerInfo[i].equals("O")) logger.debug("OrganizationName : " + issuerInfo[i + 1]); if (issuerInfo[i].equals("CN")) logger.debug("CommonName : " + issuerInfo[i + 1]); } logger.info("valid from: " + certificate.getNotBefore() + " until: " + certificate.getNotAfter()); } catch (Exception e) { logger.error("couldn't instantiate X.509 certificate. ", e); okCertificato = false; } if (!okCertificato) { logger.info("no certificate, ending process"); return; } try { logger.info("encrypting data"); CMSEnvelopedDataStreamGenerator edGen = new CMSEnvelopedDataStreamGenerator(); edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(certificate).setProvider("BC")); OutputStream out = edGen.open(encrypted, new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider("BC").build()); Streams.copy(plaintext, out); out.close(); } catch (CMSException ex) { logger.error("CMSException: ", ex.getUnderlyingException()); } catch (IOException e) { logger.error("couldn't generate enveloped signature"); } catch (CertificateEncodingException e) { logger.error("certificate encoding error", e); // } catch (OperatorCreationException e) { // logger.error("operator creation error", e); } logger.info("encryption ending"); }
From source file:org.dihedron.crypto.operations.encrypt.pkcs7.PKCS7EncryptingStream.java
License:Open Source License
/** * Constructor.//from w w w . ja v a 2 s . c o m * * @param output * the output stream, to which encrypted data will be written. * @param certificate * the certificate to be used for encryption. */ public PKCS7EncryptingStream(OutputStream output, Certificate certificate) { super(output, certificate); logger.info("encrypting data through certificate supporting algorithm: '{}'", certificate.getPublicKey().getAlgorithm()); if (certificate instanceof X509Certificate) { String[] issuerInfo = ((X509Certificate) certificate).getIssuerDN().getName().split("(=|, )", -1); String[] subjectInfo = ((X509Certificate) certificate).getSubjectDN().getName().split("(=|, )", -1); logger.debug("common name (CN) : '{}'", subjectInfo[3]); logger.debug("address : '{}'", subjectInfo[1]); for (int i = 0; i < issuerInfo.length; i += 2) { if (issuerInfo[i].equals("C")) { logger.debug("CountryName : '{}'", issuerInfo[i + 1]); } if (issuerInfo[i].equals("O")) { logger.debug("OrganizationName : '{}'", issuerInfo[i + 1]); } if (issuerInfo[i].equals("CN")) { logger.debug("CommonName : '{}'", issuerInfo[i + 1]); } } logger.debug("certificate is valid from {} until {}", ((X509Certificate) certificate).getNotBefore(), ((X509Certificate) certificate).getNotAfter()); } try { logger.info("preparing encrypting stream..."); CMSEnvelopedDataStreamGenerator generator = new CMSEnvelopedDataStreamGenerator(); generator.addRecipientInfoGenerator( new JceKeyTransRecipientInfoGenerator((X509Certificate) certificate).setProvider("BC")); stream = generator.open(output, new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider("BC").build()); logger.info("encrypting stream ready!"); } catch (CMSException ex) { logger.error("CMSException: ", ex.getUnderlyingException()); } catch (IOException e) { logger.error("couldn't generate enveloped signature"); } catch (CertificateEncodingException e) { logger.error("certificate encoding error", e); } }
From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.HardTokenEncryptCAService.java
License:Open Source License
@Override public ExtendedCAServiceResponse extendedService(final CryptoToken cryptoToken, final ExtendedCAServiceRequest request) throws ExtendedCAServiceRequestException, IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException { log.trace(">extendedService"); if (this.getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) { String msg = intres.getLocalizedMessage("caservice.notactive", "HardTokenEncrypt"); log.error(msg);/*from w ww. jav a 2 s . co m*/ throw new ExtendedCAServiceNotActiveException(msg); } if (!(request instanceof HardTokenEncryptCAServiceRequest)) { throw new IllegalExtendedCAServiceRequestException( "Not a HardTokenEncryptCAServiceRequest: " + request.getClass().getName()); } final HardTokenEncryptCAServiceRequest serviceReq = (HardTokenEncryptCAServiceRequest) request; ExtendedCAServiceResponse returnval = null; if (serviceReq.getCommand() == HardTokenEncryptCAServiceRequest.COMMAND_ENCRYPTDATA) { try { returnval = new HardTokenEncryptCAServiceResponse( HardTokenEncryptCAServiceResponse.TYPE_ENCRYPTRESPONSE, getCa().encryptData(cryptoToken, serviceReq.getData(), CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT)); } catch (CMSException e) { log.error("encrypt:", e.getUnderlyingException()); throw new IllegalExtendedCAServiceRequestException(e); } catch (Exception e) { throw new IllegalExtendedCAServiceRequestException(e); } } else { if (serviceReq.getCommand() == HardTokenEncryptCAServiceRequest.COMMAND_DECRYPTDATA) { try { returnval = new HardTokenEncryptCAServiceResponse( HardTokenEncryptCAServiceResponse.TYPE_DECRYPTRESPONSE, getCa().decryptData(cryptoToken, serviceReq.getData(), CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT)); } catch (CMSException e) { log.error("decrypt:", e.getUnderlyingException()); throw new IllegalExtendedCAServiceRequestException(e); } catch (Exception e) { throw new IllegalExtendedCAServiceRequestException(e); } } else { throw new IllegalExtendedCAServiceRequestException("Illegal command: " + serviceReq.getCommand()); } } return returnval; }