Example usage for org.bouncycastle.util.encoders Base64 encode

List of usage examples for org.bouncycastle.util.encoders Base64 encode

Introduction

In this page you can find the example usage for org.bouncycastle.util.encoders Base64 encode.

Prototype

public static byte[] encode(byte[] data) 

Source Link

Document

encode the input data producing a base 64 encoded byte array.

Usage

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

License:Open Source License

Document signDocument(Document document, SignatureParameters parameters, byte[] signatureValue) {

    try {//from   w ww.j ava2 s.c  o m

        /* Read the document */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = null;
        if (parameters.getSignaturePackaging() == SignaturePackaging.ENVELOPED) {
            doc = db.parse(document.openStream());
        } else {
            doc = db.newDocument();
            doc.appendChild(doc.createElement("empty"));
        }

        /* Interceptor */
        SpecialPrivateKey dummyPrivateKey = new SpecialPrivateKey();

        /* Context */
        DOMSignContext signContext = new DOMSignContext(dummyPrivateKey, doc.getDocumentElement());
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

        String signatureValueId = "value-" + computeDeterministicId(parameters);

        DOMXMLSignature domSig = createSignature(parameters, doc, document, signContext, signatureValueId);

        String xpathString = "//ds:SignatureValue[@Id='" + signatureValueId + "']";
        Element signatureValueEl = XMLUtils.getElement(doc, xpathString);

        if (parameters.getSignatureAlgorithm() == SignatureAlgorithm.ECDSA) {
            signatureValueEl.setTextContent(
                    new String(Base64.encode(SignatureECDSA.convertASN1toXMLDSIG(signatureValue))));
        } else if (parameters.getSignatureAlgorithm() == SignatureAlgorithm.DSA) {
            signatureValueEl.setTextContent(new String(Base64.encode(convertASN1toXMLDSIG(signatureValue))));
        } else {
            signatureValueEl.setTextContent(new String(Base64.encode(signatureValue)));
        }

        UnsignedPropertiesType unsigned = createUnsignedXAdESProperties(parameters, domSig, null,
                signatureValueEl);
        if (unsigned != null) {
            JAXBContext xadesJaxbContext = JAXBContext.newInstance(getXades13ObjectFactory().getClass());
            Marshaller m = xadesJaxbContext.createMarshaller();
            JAXBElement<UnsignedPropertiesType> el = getXades13ObjectFactory()
                    .createUnsignedProperties(unsigned);
            m.marshal(el, getXAdESQualifyingProperties(parameters, doc));
        }

        /* Output document */
        ByteArrayOutputStream outputDoc = new ByteArrayOutputStream();
        Result output = new StreamResult(outputDoc);
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        Source source = new DOMSource(doc);
        xformer.transform(source, output);
        outputDoc.close();

        return new InMemoryDocument(outputDoc.toByteArray());

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (XMLSignatureException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.impact_project.wsclient.SOAPresults.java

License:Apache License

/**
 * Loads the user values/files and sends them to the web service. Files are
 * encoded to Base64. Stores the resulting message in the session and the
 * resulting files on the server.// w w  w.j  av  a2s. c  o  m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    OutputStream outStream = null;
    BufferedInputStream bis = null;
    user = request.getParameter("user");
    pass = request.getParameter("pass");

    try {

        HttpSession session = request.getSession(true);

        String folder = session.getServletContext().getRealPath("/");
        if (!folder.endsWith("/")) {
            folder = folder + "/";
        }

        Properties props = new Properties();
        InputStream stream = new URL("file:" + folder + "config.properties").openStream();

        props.load(stream);
        stream.close();

        boolean loadDefault = Boolean.parseBoolean(props.getProperty("loadDefaultWebService"));
        boolean supportFileUpload = Boolean.parseBoolean(props.getProperty("supportFileUpload"));
        boolean oneResultFile = Boolean.parseBoolean(props.getProperty("oneResultFile"));
        String defaultFilePrefix = props.getProperty("defaultFilePrefix");

        SoapService serviceObject = (SoapService) session.getAttribute("serviceObject");
        SoapOperation operation = null;
        if (supportFileUpload) {

            // stores all the strings and encoded files from the html form
            Map<String, String> htmlFormItems = new HashMap<String, String>();

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List /* FileItem */ items = upload.parseRequest(request);

            // Process the uploaded items
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                // a normal string field
                if (item.isFormField()) {
                    htmlFormItems.put(item.getFieldName(), item.getString());

                    // uploaded file
                } else {

                    // encode the uploaded file to base64
                    String currentAttachment = new String(Base64.encode(item.get()));

                    htmlFormItems.put(item.getFieldName(), currentAttachment);
                }
            }

            // get the chosen WSDL operation
            String operationName = htmlFormItems.get("operationName");

            operation = serviceObject.getOperation(operationName);
            for (SoapInput input : operation.getInputs()) {
                input.setValue(htmlFormItems.get(input.getName()));
            }

        } else {
            // get the chosen WSDL operation
            String operationName = request.getParameter("operationName");

            operation = serviceObject.getOperation(operationName);
            for (SoapInput input : operation.getInputs()) {
                String[] soapInputValues = request.getParameterValues(input.getName());
                input.clearValues();
                for (String value : soapInputValues) {
                    input.addValue(value);
                }
            }

        }

        List<SoapOutput> outs = operation.execute(user, pass);
        String soapResponse = operation.getResponse();

        String htmlResponse = useXslt(soapResponse, "/SoapToHtml.xsl");

        session.setAttribute("htmlResponse", htmlResponse);
        session.setAttribute("soapResponse", soapResponse);

        // for giving the file names back to the JSP
        List<String> fileNames = new ArrayList<String>();

        // process possible attachments in the response
        List<SoapAttachment> attachments = operation.getReceivedAttachments();
        int i = 0;
        for (SoapAttachment attachment : attachments) {

            // path to the server directory
            String serverPath = getServletContext().getRealPath("/");
            if (!serverPath.endsWith("/")) {
                serverPath = folder + "/";
            }

            // construct the file name for the attachment
            String fileEnding = "";
            String contentType = attachment.getContentType();
            System.out.println("content type: " + contentType);
            if (contentType.equals("image/gif")) {
                fileEnding = ".gif";
            } else if (contentType.equals("image/jpeg")) {
                fileEnding = ".jpg";
            } else if (contentType.equals("image/tiff")) {
                fileEnding = ".tif";
            } else if (contentType.equals("application/vnd.ms-excel")) {
                fileEnding = ".xlsx";
            }

            String fileName = loadDefault ? defaultFilePrefix : "attachedFile";

            String counter = oneResultFile ? "" : i + "";

            String attachedFileName = fileName + counter + fileEnding;

            // store the attachment into the file
            File file = new File(serverPath + attachedFileName);
            outStream = new FileOutputStream(file);

            InputStream inStream = attachment.getInputStream();

            bis = new BufferedInputStream(inStream);

            int bufSize = 1024 * 8;

            byte[] bytes = new byte[bufSize];

            int count = bis.read(bytes);
            while (count != -1 && count <= bufSize) {
                outStream.write(bytes, 0, count);
                count = bis.read(bytes);
            }
            if (count != -1) {
                outStream.write(bytes, 0, count);
            }
            outStream.close();
            bis.close();

            fileNames.add(attachedFileName);
            i++;
        }

        // pass the file names to JSP
        request.setAttribute("fileNames", fileNames);

        request.setAttribute("round3", "round3");
        // get back to JSP
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/interface.jsp");
        rd.forward(request, response);

    } catch (Exception e) {
        logger.error("Exception", e);
        e.printStackTrace();
    } finally {
        if (outStream != null) {
            outStream.close();
        }
        if (bis != null) {
            bis.close();
        }
    }

}

From source file:eu.inn.biometric.signature.crypto.BCCryptoProvider.java

License:Open Source License

@Override
public byte[] b64Encode(byte[] data) {
    return Base64.encode(data);
}

From source file:eu.inn.biosign.BioSign.java

License:Open Source License

private Boolean save() {

    return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
        public Boolean run() {
            try {
                JSObjectWrapper.call("log", new Object[] { "save sign : " + tablet.isEmpty() });

                if (tablet.isEmpty())
                    return false;
                if (!tablet.isEmpty()) {

                    if (Signature.isBio)
                        Signature.outputSdi = CmsEncryptor.getBiometricData();
                    else
                        Signature.outputSdi = "";

                    //                  BufferedImage bufferedImage = tablet
                    //                        .getSignatureImage();

                    BufferedImage bufferedImage = tablet.getSignatureImage();
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    ImageIO.write(bufferedImage, "png", out);
                    if (tablet.getDeviceConfig().scaledSignRectangle != null) {
                        Point r = ((Point) tablet.getDeviceConfig().scaledSignRectangle.getLocation().clone());
                        //                           r.translate(-tablet.getDeviceConfig().getActiveAreaForBackground().x,-tablet.getDeviceConfig().getActiveAreaForBackground().y);
                        Device.signatureBeans
                                .add(new SignatureBean(bufferedImage, r, tablet.getDeviceConfig().actualPage));
                    }/*from  w  w  w .j  a  v a2s .co m*/
                    byte[] image = out.toByteArray();
                    byte[] base64Image = Base64.encode(image);
                    Signature.image = new String(base64Image);

                    JSObjectWrapper.call("log", new Object[] { "SDI : " + Signature.outputSdi });
                    //                  IOUtils.write(image, new FileOutputStream(new File(
                    //                        "c:\\imageFromTablet.png")));
                    JSObjectWrapper.call("signAcquired", new Object[] { Signature.outputSdi, Signature.image });

                }
                tablet.getDeviceConfig().clearCache(tablet.getDeviceConfig().actualPage);
                //               tablet.clear();
                return true;

            } catch (Throwable e) {

                JSObjectWrapper.call("log", new Object[] { exToStr(e) });
                return false;
            }
        }
    });

}

From source file:eu.inn.biosign.SignatureDeviceManager.java

License:Open Source License

private void debugOnTablet() {

    Device.isDEBUG = true;/*from  w  w w  . j  a  v a  2 s . c om*/
    System.out.println("in debug mode");

    setSignRectangle(62, 682, 151, 75);
    Device.TAG = " seq=45,displayName=Firma correntista,w=250,h=75,description=ciao sono la descrizione della firma";

    // TabletManager.IS_MOUSE_ALLOWED=true;
    String imageString = null;
    try {
        imageString = new String(Base64.encode(FileUtils.readFileToByteArray(new File("c:\\getImage.png"))));
        ;
        String urlString = "http://192.168.1.161:8081/bio-sign-in/signManagement";
        String uuid = "";
        // setPdfFile(new String(Base64.encode(FileUtils.readFileToByteArray(new File("c:\\getImage.png")))));
        setPdfBase64Image(imageString, 595, 1, 3);
    } catch (Exception ioe) {
        System.out.println("Exception while reading the Image " + ioe);
    }
    // setEnableDocView(true+"");
    // Device.setBase64PdfImage(b64);
    boolean forceShowDocument = false;
    while (!startCapture(forceShowDocument))
        if (!Device.IS_MOUSE_ALLOWED)
            Device.IS_MOUSE_ALLOWED = true;
        else
            setPdfBase64Image(imageString, 595, 1, 3);

    // forceShowDocument=!forceShowDocument;
    long start = System.nanoTime();
    // getPageB64(1);
    long last = System.nanoTime();
    System.out.println("tablet getPageB64 in " + ((last - start) / 1000000) + "ms");
    // this.add
}

From source file:eu.peppol.as2.InboundMessageReceiver.java

License:EUPL

/**
 * Receives an AS2 Message in the form of a map of headers together with the payload,
 * which is made available in an input stream
 * <p>//from w  w w.  j  a  v a  2  s  .  co m
 * If persisting message to MessageRepository fails, we have to return negative MDN.
 *
 * @param httpHeaders the http headers received
 * @param inputStream supplies the actual data stream
 * @return MDN object to signal if everything is ok or if some error occurred while receiving
 * @throws ErrorWithMdnException if validation fails due to syntactic, semantic or other reasons.
 */
public ResponseData receive(InternetHeaders httpHeaders, InputStream inputStream) {
    if (httpHeaders == null) {
        throw new IllegalArgumentException("httpHeaders required constructor argument");
    }
    if (inputStream == null) {
        throw new IllegalArgumentException("inputStream required constructor argument");
    }

    Mic mic = null;
    try {

        log.debug("Receiving message ..");

        // Inspects the eu.peppol.as2.As2Header.DISPOSITION_NOTIFICATION_OPTIONS

        // TODO: Move this tp As2MessageFactory.createAs2MessageFrom
        inspectDispositionNotificationOptions(httpHeaders);

        log.debug(
                "Message contains valid AS2 Disposition-notification-options, now creating internal AS2 message...");

        MimeMessage mimeMessage = MimeMessageHelper.createMimeMessageAssistedByHeaders(inputStream,
                httpHeaders);
        SignedMimeMessage signedMimeMessage = new SignedMimeMessage(mimeMessage);

        // Transforms the input data into a proper As2Message
        As2Message as2Message = As2MessageFactory.createAs2MessageFrom(httpHeaders, signedMimeMessage);

        // Validates the message headers according to the PEPPOL rules and performs semantic validation
        log.debug("Validating AS2 Message: " + as2Message);
        as2MessageInspector.validate(as2Message);

        // Extracts the SBDH from the message, the SBDH is required by OpenPEPPOL
        StandardBusinessDocumentHeader sbdh = sbdhFastParser
                .parse(as2Message.getSignedMimeMessage().getPayload());
        if (sbdh == null) {
            throw new IllegalStateException(
                    "Payload does not contain Standard Business Document Header (SBDH)");
        }

        // Calculates the message digest of the payload, there are two alternatives:
        // a) if the payload consists of SBDH + XML document -> calculate digest over entire payload
        // b) if payload consists of SBDH + ASiC -> calculate digest of binary ASiC archive only. I.e. without the SBDH and
        //    base64 decoded.
        MessageDigestResult payloadDigestResult = PayloadDigestCalculator.calcDigest(
                OxalisConstant.DEFAULT_DIGEST_ALGORITHM, sbdh, as2Message.getSignedMimeMessage().getPayload());
        log.debug("The MessageDigest of the payload is "
                + new String(Base64.encode(payloadDigestResult.getDigest())));

        // Persists the payload
        PeppolMessageMetaData peppolMessageMetaData = persistPayload(sbdh, messageRepository, as2Message);

        // Creates the MDN data to be returned (not the actual MDN, which must be represented as an S/MIME message)
        // Calculates the MIC for the payload using the preferred mic algorithm
        String micAlgorithmName = as2Message.getDispositionNotificationOptions()
                .getPreferredSignedReceiptMicAlgorithmName();
        mic = as2Message.getSignedMimeMessage().calculateMic(micAlgorithmName);
        log.debug("Calculated MIC : " + mic.toString());
        MdnData mdnData = createMdnData(httpHeaders, mic, payloadDigestResult);

        // Finally we persist the raw statistics data
        persistStatistics(rawStatisticsRepository, ourAccessPointIdentifier, peppolMessageMetaData);

        // Creates the S/MIME message to be returned to the sender
        MimeMessage signedMdn = mdnMimeMessageFactory.createSignedMdn(mdnData, httpHeaders);
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            signedMdn.writeTo(byteArrayOutputStream);
            messageRepository.saveNativeTransportReceipt(byteArrayOutputStream.toByteArray());
        } catch (IOException | MessagingException e) {
            log.error("Unable to write signed mdn to byte array:" + e.getMessage(), e);
        }

        // Creates the REM evidence and persists it
        TransmissionEvidence remWithMdnEvidence = as2TransmissionEvidenceFactory
                .createRemWithMdnEvidence(mdnData, peppolMessageMetaData, signedMdn, TransmissionRole.C_3);
        messageRepository.saveTransportReceipt(remWithMdnEvidence, peppolMessageMetaData);

        // Returns the response to be emitted by whoever is calling us
        ResponseData responseData = new ResponseData(HttpServletResponse.SC_OK, signedMdn, mdnData);
        return responseData;

    } catch (InvalidAs2MessageException | MdnRequestException | OxalisMessagePersistenceException e) {
        log.error("Invalid AS2 message: " + e.getMessage(), e);

        MdnData mdnData = MdnData.Builder.buildFailureFromHeaders(httpHeaders, mic, e.getMessage());
        MimeMessage signedMdn = mdnMimeMessageFactory.createSignedMdn(mdnData, httpHeaders);

        ResponseData responseDataWithErrors = new ResponseData(HttpServletResponse.SC_BAD_REQUEST, signedMdn,
                mdnData);
        return responseDataWithErrors;
    }
}

From source file:eu.peppol.as2.MimeMessageHelper.java

License:EUPL

/**
 * Calculates sha1 mic based on the MIME body part.
 *//*from   w  w w  .j  av  a2 s .  c  om*/
public static Mic calculateMic(MimeBodyPart bodyPart) {
    String algorithmName = "sha1";
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bodyPart.writeTo(baos);
        byte[] content = baos.toByteArray();
        MessageDigest md = MessageDigest.getInstance(algorithmName, new BouncyCastleProvider());
        md.update(content);
        byte[] digest = md.digest();
        String digestAsString = new String(Base64.encode(digest));
        return new Mic(digestAsString, algorithmName);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(algorithmName + " not found", e);
    } catch (IOException e) {
        throw new IllegalStateException("Unable to read data from digest input. " + e.getMessage(), e);
    } catch (MessagingException e) {
        throw new IllegalStateException("Unable to handle mime body part. " + e.getMessage(), e);
    }
}

From source file:eu.peppol.as2.SignedMimeMessage.java

License:EUPL

public Mic calculateMic(String algorithmName) {
    try {//  w  w  w.  j  a  v a 2 s.com

        MessageDigest messageDigest = MessageDigest.getInstance(algorithmName, new BouncyCastleProvider());

        MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();

        BodyPart bodyPart = mimeMultipart.getBodyPart(0);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bodyPart.writeTo(baos); // Writes the entire contents of first multipart, including the MIME headers
        // bodyPart.writeTo(System.out);
        byte[] content = baos.toByteArray();
        messageDigest.update(content);
        String digestAsString = new String(Base64.encode(messageDigest.digest()));

        return new Mic(digestAsString, algorithmName);

    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(algorithmName + " not found", e);
    } catch (IOException e) {
        throw new IllegalStateException("Unable to read data from digest input. " + e.getMessage(), e);
    } catch (MessagingException e) {
        throw new IllegalStateException("Unable to handle mime body part. " + e.getMessage(), e);
    }
}

From source file:eu.peppol.as2.SignedMimeMessageInspector.java

License:Open Source License

public Mic calculateMic(String algorithmName) {
    try {/*www  .  ja va2s .com*/

        MessageDigest messageDigest = MessageDigest.getInstance(algorithmName, provider);

        MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
        BodyPart bodyPart = mimeMultipart.getBodyPart(0);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bodyPart.writeTo(baos);
        // bodyPart.writeTo(System.out);
        byte[] content = baos.toByteArray();
        messageDigest.update(content);
        String digestAsString = new String(Base64.encode(messageDigest.digest()));
        return new Mic(digestAsString, algorithmName);

        /*
        InputStream resourceAsStream = getPayload() / getInputStreamForMimeMessage();
        DigestInputStream digestInputStream = new DigestInputStream(resourceAsStream, messageDigest);
                
        // Reads through the entire file in order to create the digest
        final byte[] aBuf = new byte[4096];
        while (digestInputStream.read(aBuf) >= 0) {
        digestInputStream.close();
        }
                
        // grabs the digest after reading all of the contents.
        byte[] digest = digestInputStream.getMessageDigest().digest();
        String digestAsString = new String(Base64.encode(digest));
                
        return new Mic(digestAsString, algorithmName);
        */

    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(algorithmName + " not found", e);
    } catch (IOException e) {
        throw new IllegalStateException("Unable to read data from digest input. " + e.getMessage(), e);
    } catch (MessagingException e) {
        throw new IllegalStateException("Unable to handle mime body part. " + e.getMessage(), e);
    }
}

From source file:eu.stork.peps.auth.commons.PEPSUtil.java

License:Open Source License

/**
 * {@link Base64} encodes the input samlToken parameter.
 * /*from   w  w w  .jav  a2s .c om*/
 * @param samlToken the SAML Token to be encoded.
 * 
 * @return The Base64 String representing the samlToken.
 * 
 * @see Base64#encode
 */
public static String encodeSAMLToken(final byte[] samlToken) {
    try {
        return new String(Base64.encode(samlToken), "UTF8");
    } catch (final UnsupportedEncodingException e) {
        LOG.error(PEPSErrors.INTERNAL_ERROR.errorMessage(), e);
        return null;
    }
}