public Object getEntity(Class t, Type gt, Annotation[] ann, PrivateKey pKey, X509Certificate cert) { MimeBodyPart decrypted = null; try { MimeBodyPart encryptedBodyPart = body; SMIMEEnveloped m = new SMIMEEnveloped(encryptedBodyPart); JceKeyTransRecipientId recId = new JceKeyTransRecipientId(cert); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); JceKeyTransRecipient pKeyRecp = new JceKeyTransEnvelopedRecipient(pKey); decrypted = SMIMEUtil.toMimeBodyPart(recipient.getContent(pKeyRecp)); } catch (Exception e1) { throw new RuntimeException(e1); } return extractEntity(t, gt, ann, decrypted, providers); }
public boolean verify(PublicKey publicKey) throws Exception { SMIMESigned signed = new SMIMESigned(body); SignerInformationStore signers = signed.getSignerInfos(); SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next(); return (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(publicKey))); }
@Override public void writeTo(SignedOutput out, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream os) throws IOException, WebApplicationException { try { SMIMESignedGenerator gen = new SMIMESignedGenerator(); SignerInfoGenerator signer = new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").build("SHA1WITHRSA", out.getPrivateKey(), out.getCertificate()); gen.addSignerInfoGenerator(signer); MimeMultipart mp = gen.generate(EnvelopedWriter.createBodyPart(providers, out)); String contentType = mp.getContentType(); contentType = contentType.replace("\r\n", "").replace("\t", " "); headers.putSingle("Content-Type", contentType); mp.writeTo(os); } catch (Exception e) { throw new WriterException(e); } } }
/** * Creates an <CODE>SMIMESignedGenerator</CODE>. Includes a signer private key and certificate, * and a pool of certs and cerls (if any) to go with the signature. * @return The generated SMIMESignedGenerator. */ public SMIMESignedGenerator createGenerator() throws CertStoreException, SMIMEException, OperatorCreationException, CertificateEncodingException { // create the generator for creating an smime/signed message SMIMESignedGenerator generator = new SMIMESignedGenerator(); // add a signer to the generator - this specifies we are using SHA1 // the encryption algorithm used is taken from the key SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder() .setProvider("BC") .build("SHA1withRSA", privateKey, certificate); generator.addSignerInfoGenerator(signerInfoGenerator); // add our pool of certs and cerls (if any) to go with the signature generator.addCertificates(jcaCertStore); return generator; }
public MimeBodyPart encrypt(MimeBodyPart part, Certificate cert, String algorithm, String contentTxfrEncoding) throws GeneralSecurityException, SMIMEException, MessagingException { X509Certificate x509Cert = castCertificate(cert); SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); gen.setContentTransferEncoding(getEncoding(contentTxfrEncoding)); if (logger.isDebugEnabled()) { logger.debug("Encrypting on MIME part containing the following headers: " + AS2Util.printHeaders(part.getAllHeaders())); } gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(x509Cert).setProvider("BC")); return gen.generate(part, getOutputEncryptor(algorithm)); }
public static MimeMessage encryptMessage(MimeMessage message) throws Exception { Security.addProvider(new BouncyCastleProvider()); // create the generator for creating an smime/encrypted message SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); X509Certificate recipientCert = getRecipientPublicCertificate(message); gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(recipientCert).setProvider("BC")); MimeBodyPart msg = new MimeBodyPart(); msg.setContent(message.getContent(), message.getContentType()); MimeBodyPart mp = gen.generate(msg, new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC).setProvider("BC").build()); message.setContent(mp.getContent(), mp.getContentType()); message.saveChanges(); return message; }
public void decompress(AS2Message msg) throws DispositionException { try { if (logger.isDebugEnabled()) { logger.debug("Decompressing a compressed message"); } SMIMECompressed compressed = new SMIMECompressed(msg.getData()); // decompression step MimeBodyPart MimeBodyPart recoveredPart = SMIMEUtil.toMimeBodyPart(compressed.getContent(new ZlibExpanderProvider())); // Update the message object msg.setData(recoveredPart); } catch (Exception ex) { msg.setLogMsg("Error decompressing received message: " + ex.getCause()); logger.error(msg, ex); throw new DispositionException(new DispositionType("automatic-action", "MDN-sent-automatically", "processed", "Error", "unexpected-processing-error"), AS2ReceiverModule.DISP_DECOMPRESSION_ERROR, ex); } }
/** * Generates a signed MimeMultipart from a MimeMessage. * @param message The message to sign. * @return The signed <CODE>MimeMultipart</CODE>. */ @Override public MimeMultipart generate(MimeMessage message) throws CertStoreException, NoSuchAlgorithmException, NoSuchProviderException, SMIMEException, OperatorCreationException, CertificateEncodingException { // create the generator for creating an smime/signed MimeMultipart SMIMESignedGenerator generator = createGenerator(); // do it return generator.generate(message); }
/** * Get the internal SMIMESigned message * * @return the SMIMESigned message instance * @throws PackageException */ public SMIMESigned getSMIMESignedMessage() throws PackageException { if (smimeSignedMessage == null && message != null) { // smimeSignedMessage is not 'null' if the message is signed and already decrypted final String notASignedMessage = "The Content-Type is '" + CONTENT_TYPE_MULTIPART_SIGNED + "' but could not create SMIMESigned message"; try { if (message.isMimeType(CONTENT_TYPE_MULTIPART_SIGNED)) { smimeSignedMessage = new SMIMESigned((MimeMultipart) message.getContent()); } } catch (MessagingException me) { throw new PackageException("Could not get message details", me); } catch (CMSException e) { throw new PackageException(notASignedMessage, e); } catch (IOException e) { throw new PackageException(notASignedMessage, e); } } return smimeSignedMessage; }
@Nonnull public static MimeBodyPart compressMimeBodyPart (@Nonnull final MimeBodyPart aData, @Nonnull final ECompressionType eCompressionType, @Nonnull final EContentTransferEncoding eCTE) throws SMIMEException { ValueEnforcer.notNull (aData, "Data"); ValueEnforcer.notNull (eCompressionType, "CompressionType"); ValueEnforcer.notNull (eCTE, "ContentTransferEncoding"); final SMIMECompressedGenerator aCompressedGenerator = new SMIMECompressedGenerator (); // Content-Transfer-Encoding to use aCompressedGenerator.setContentTransferEncoding (eCTE.getID ()); // This call might modify the original mime part and add "Content-Type" and // "Content-Transfer-Encoding" header final MimeBodyPart aCompressedBodyPart = aCompressedGenerator.generate (aData, eCompressionType.createOutputCompressor ()); return aCompressedBodyPart; }
private MimeBodyPart encryptMimeBodyPart(MimeBodyPart mimeBodyPart) throws NoSuchAlgorithmException, NoSuchProviderException, SMIMEException { if (encryptMessage) { mimeBodyPart = gen.generate(mimeBodyPart, encryptionOID, BOUNCY_CASTLE_PROVIDER); } return mimeBodyPart; }
public InputStream getContent() throws IOException, OxalisSecurityException, OxalisAs2Exception { try { if (signer == null) throw new OxalisSecurityException("Content is not validated."); return smimeSigned.getContent().getInputStream(); } catch (MessagingException e) { throw new OxalisAs2Exception("Unable to fetch content.", e); } }
public void validate(Service service, CertificateValidator validator, String commonName) throws IOException, OxalisSecurityException, PeppolSecurityException { for (X509CertificateHolder holder : (CollectionStore<X509CertificateHolder>) smimeSigned.getCertificates()) { if (CertificateUtils.containsCommonName(holder.getSubject(), commonName)) { try { X509Certificate certificate = CertificateUtils.parseCertificate(holder.getEncoded()); if (isValid(service, validator, certificate)) { validate(certificate); return; } } catch (CertificateException e) { log.debug("Unable to initiate certificate object."); } } } throw new OxalisSecurityException(commonName == null ? "Unable to find valid certificate for validation of content." : String.format("Unable to find valid certificate with CN '%s' for validation of content.", commonName)); }
SMIMESignedGenerator gen = new SMIMESignedGenerator(); SignerInfoGenerator sigGen = new JcaSimpleSignerInfoGeneratorBuilder() .setProvider(BC) .build("SHA1withRSA", senderKey, senderCert); gen.addSignerInfoGenerator(sigGen); MimeMultipart smime = gen.generate(part); MimeBodyPart tmpBody = new MimeBodyPart(); tmpBody.setContent(smime); tmpBody.setHeader("Content-Type", smime.getContentType()); return tmpBody;
private MimeBodyPart decryptPart(MimeBodyPart part) throws Exception { SMIMEEnveloped smimeEnveloped = new SMIMEEnveloped(part); RecipientInformationStore recipients = smimeEnveloped.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); if (null == recipient) { StringBuilder errorMessage = new StringBuilder(); errorMessage.append("This email wasn't encrypted with \"" + recId.toString() + "\".\n"); errorMessage.append("The encryption recId is: "); for (Object rec : recipients.getRecipients()) { if (rec instanceof RecipientInformation) { RecipientId recipientId = ((RecipientInformation) rec).getRID(); errorMessage.append("\"" + recipientId.toString() + "\"\n"); } } throw new Exception(errorMessage.toString()); } return toMimeBodyPart(recipient.getContent(ks.getKey(decryptionKeyAlias, null), BOUNCY_CASTLE_PROVIDER)); }
/** * Generates a signed MimeMultipart from a MimeBodyPart. * @param content The content to sign. * @return The signed <CODE>MimeMultipart</CODE>. */ @Override public MimeMultipart generate(MimeBodyPart content) throws CertStoreException, NoSuchAlgorithmException, NoSuchProviderException, SMIMEException, OperatorCreationException, CertificateEncodingException { // create the generator for creating an smime/signed MimeMultipart SMIMESignedGenerator generator = createGenerator(); // do it return generator.generate(content); }
private SignedMessage(MimeMessage message) throws IOException, OxalisAs2Exception { try { // Verify content type if (!message.isMimeType("multipart/signed")) throw new OxalisAs2Exception("Received content is not 'multipart/signed'."); micalg = extractMicalg(message); // Extract headers //noinspection unchecked // headers = Collections.list((Enumeration<Header>) message.getAllHeaders()); // Create MimeMultitype mimeMultipart = (MimeMultipart) message.getContent(); // Extracting signature signature = ByteStreams.toByteArray(mimeMultipart.getBodyPart(1).getInputStream()); // Create signed message smimeSigned = new SMIMESigned(mimeMultipart); } catch (CMSException | MessagingException e) { throw new OxalisAs2Exception("Unable to parse received content.", e); } }
public InputStream getContent() throws IOException, OxalisSecurityException, OxalisAs2Exception { try { if (signer == null) throw new OxalisSecurityException("Content is not validated."); return smimeSigned.getContent().getInputStream(); } catch (MessagingException e) { throw new OxalisAs2Exception("Unable to fetch content.", e); } }
public void validate(Service service, CertificateValidator validator, String commonName) throws IOException, OxalisSecurityException, PeppolSecurityException { for (X509CertificateHolder holder : (CollectionStore<X509CertificateHolder>) smimeSigned.getCertificates()) { if (CertificateUtils.containsCommonName(holder.getSubject(), commonName)) { try { X509Certificate certificate = CertificateUtils.parseCertificate(holder.getEncoded()); if (isValid(service, validator, certificate)) { validate(certificate); return; } } catch (CertificateException e) { log.debug("Unable to initiate certificate object."); } } } throw new OxalisSecurityException(commonName == null ? "Unable to find valid certificate for validation of content." : String.format("Unable to find valid certificate with CN '%s' for validation of content.", commonName)); }
private SignedMessage(MimeMessage message) throws IOException, OxalisAs2Exception { try { // Verify content type if (!message.isMimeType("multipart/signed")) throw new OxalisAs2Exception("Received content is not 'multipart/signed'."); micalg = extractMicalg(message); // Extract headers //noinspection unchecked // headers = Collections.list((Enumeration<Header>) message.getAllHeaders()); // Create MimeMultitype mimeMultipart = (MimeMultipart) message.getContent(); // Extracting signature signature = ByteStreams.toByteArray(mimeMultipart.getBodyPart(1).getInputStream()); // Create signed message smimeSigned = new SMIMESigned(mimeMultipart); } catch (CMSException | MessagingException e) { throw new OxalisAs2Exception("Unable to parse received content.", e); } }