Example usage for org.apache.commons.codec.binary Base64 encodeBase64String

List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64String

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 encodeBase64String.

Prototype

public static String encodeBase64String(final byte[] binaryData) 

Source Link

Document

Encodes binary data using the base64 algorithm but does not chunk the output.

Usage

From source file:com.techcavern.pircbotz.cap.SASLCapHandler.java

public boolean handleUnknown(PircBotZ bot, String rawLine) throws CAPException {
    if (rawLine.equals("AUTHENTICATE +")) {
        //Server ackowledges our request to use plain authentication
        String encodedAuth = Base64
                .encodeBase64String((username + '\0' + username + '\0' + password).getBytes(Charsets.UTF_8));
        bot.sendRaw().rawLineNow("AUTHENTICATE " + encodedAuth);
    }//from   ww  w.j av  a 2s .  c  om

    //Check for 904 and 905 
    String[] parsedLine = rawLine.split(" ", 4);
    if (parsedLine.length >= 1)
        if (parsedLine[1].equals("904") || parsedLine[1].equals("905")) {
            //Remove sasl as an enabled capability
            bot.getEnabledCapabilities().remove("sasl");

            if (!ignoreFail)
                throw new CAPException(CAPException.Reason.SASLFailed,
                        "SASL Authentication failed with message: " + parsedLine[3].substring(1));

            //Pretend like nothing happened
            return true;
        } else if (parsedLine[1].equals("900") || parsedLine[1].equals("903"))
            //Success!
            return true;
    return false;
}

From source file:com.whizzosoftware.hobson.twilio.TwilioSMSAction.java

@Override
public void executeAction(PropertyContainer pc) {
    logger.info("Sending to " + pc.getPropertyValue("phoneNumber") + ": " + pc.getPropertyValue("message"));

    try {//ww w .j  a v a  2  s . c  om
        String auth = accountSid + ":" + authToken;
        StringBuilder data = new StringBuilder("To=")
                .append(URLEncoder.encode(pc.getStringPropertyValue("phoneNumber"), "UTF8")).append("&From=")
                .append(URLEncoder.encode(phoneNumber, "UTF8")).append("&Body=")
                .append(URLEncoder.encode(pc.getStringPropertyValue("message"), "UTF8"));

        plugin.sendHttpRequest(
                new URI("https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Messages.json"),
                HttpRequest.Method.POST,
                Collections.singletonMap("Authorization",
                        "Basic " + Base64.encodeBase64String(auth.getBytes())),
                null, data.toString().getBytes(), null);
    } catch (Exception e) {
        logger.error("Error sending SMS", e);
    }
}

From source file:com.confighub.core.security.Encryption.java

private static String encryptShared(CipherTransformation ct, String decrypted, String secret)
        throws ConfigException {
    if (null == decrypted)
        return null;

    try {// www  .j av a 2  s . c  o  m
        Cipher cipher = Cipher.getInstance(ct.getName());
        final int blockSize = cipher.getBlockSize();

        SecretKeySpec sharedKey = new SecretKeySpec(getKeyAsBytes(secret, ct.getKeyLen()), ct.getAlgo());

        if ("CBC".equals(ct.getMode()))
            cipher.init(Cipher.ENCRYPT_MODE, sharedKey, new IvParameterSpec(getIV(blockSize)));
        else
            cipher.init(Cipher.ENCRYPT_MODE, sharedKey);

        byte[] encrypted = cipher.doFinal(Utils.isBlank(decrypted) ? new byte[0] : decrypted.getBytes("UTF8"));
        return Base64.encodeBase64String(encrypted);
    } catch (Exception e) {
        throw new ConfigException(Error.Code.ENCRYPTION_ERROR);
    }
}

From source file:com.security.ch08_rsa.RSACoderTextKey.java

/**
 * Encrypt a string by provide public key
 * @param data string to encrypt/*from  w ww  .  j  av a 2s. c o m*/
 * @param key base64 encoded string
 * @return base64 encoded data
 * @throws Exception
 */
public static String encryptByPublicKey(String data, String key) throws Exception {
    byte[] result = encryptByPublicKey(data.getBytes(UTF_8), Base64.decodeBase64(key));
    return Base64.encodeBase64String(result);
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoDigestService.java

/**
 * HmacSHA1//  w ww  .ja  va 2s.  c o m
 *
 * @param keyB64 Secret key Base64 encoded
 * @param dataB64 Data to sign Base64 encoded
 * @return HmacSha1 MAC for the given key and data Base64 encoded
 */
public String hmacSha1(String keyB64, String dataB64) {
    validateB64(keyB64);
    validateB64(dataB64);
    final byte[] key = Base64.decodeBase64(keyB64);
    final byte[] data = Base64.decodeBase64(dataB64);

    return Base64.encodeBase64String(HmacUtils.hmacSha1(key, data));
}

From source file:eu.europa.ejusticeportal.dss.controller.action.GetSealedPdf.java

/**
 * Gets the sealed PDF document./*from   www. j a v a 2s .co  m*/
 * 
 * @param portal the PortalFacade
 * @param request the HttpServletRequest
 * @param o not used - required for the interface
 */
@Override
protected Object getResponseObject(final PortalFacade portal, final HttpServletRequest request,
        final Object o) {

    try {
        String disclaimer = portal.getLocalisedMessages(request, null)
                .get(MessagesEnum.dss_applet_digest_disclaimer.name());
        final byte[] doc = SealedPDFService.getInstance().sealDocument(portal.getPDFDocument(request),
                portal.getPDFDocumentXML(request), disclaimer,
                portal.getDocumentValidationConfig().getSealMethod());
        SealedPDF pdf = new SealedPDF();
        pdf.setFileName(portal.getPDFDocumentName(request));
        pdf.setPdfBase64(Base64.encodeBase64String(doc));
        pdf.setSignDate(new Date());
        return pdf;
    } catch (Exception e) {
        throw new SigningException(e);
    }

}

From source file:com.moz.fiji.mapreduce.framework.FijiTableInputFormat.java

/**
 * Configures a Hadoop M/R job to read from a given table.
 *
 * @param job Job to configure.// w ww  .  ja v  a  2s. com
 * @param tableURI URI of the table to read from.
 * @param dataRequest Data request.
 * @param startRow Minimum row key to process. May be left null to indicate
 *     that scanning should start at the beginning of the table.
 * @param endRow Maximum row key to process. May be left null to indicate that
 *     scanning should continue to the end of the table.
 * @param filter Filter to use for scanning. May be left null.
 * @throws IOException on I/O error.
 */
public static void configureJob(Job job, FijiURI tableURI, FijiDataRequest dataRequest, EntityId startRow,
        EntityId endRow, FijiRowFilter filter) throws IOException {
    Preconditions.checkNotNull(job, "job must not be null");
    Preconditions.checkNotNull(tableURI, "tableURI must not be null");
    Preconditions.checkNotNull(dataRequest, "dataRequest must not be null");

    final Configuration conf = job.getConfiguration();

    // TODO: Check for jars config:
    // GenericTableMapReduceUtil.initTableInput(hbaseTableName, scan, job);

    // Write all the required values to the job's configuration object.
    final String serializedRequest = Base64.encodeBase64String(SerializationUtils.serialize(dataRequest));
    conf.set(FijiConfKeys.FIJI_INPUT_DATA_REQUEST, serializedRequest);
    conf.set(FijiConfKeys.FIJI_INPUT_TABLE_URI, tableURI.toString());
    if (null != startRow) {
        conf.set(FijiConfKeys.FIJI_START_ROW_KEY, Base64.encodeBase64String(startRow.getHBaseRowKey()));
    }
    if (null != endRow) {
        conf.set(FijiConfKeys.FIJI_LIMIT_ROW_KEY, Base64.encodeBase64String(endRow.getHBaseRowKey()));
    }
    if (null != filter) {
        conf.set(FijiConfKeys.FIJI_ROW_FILTER, filter.toJson().toString());
    }
}

From source file:com.zotoh.crypto.MICUte.java

/**
 * Calculates a Message Integrity Check (Message Disposition)
 *
 * @param content The content across which the MIC is calculated. This can
 *                   be of type InputStream, String, byte[], or a Multipart (multipart/signed)
 * @param algorithm  The algorithm to use to calculate the MIC (e.g. sha1, md5)
 * @param addcrlfToString If true, adds a CRLF on the String data
 *                   since the receiving MTA uses canonicalized data to calculate MIC
 * @param addcrlfTobyte If true, adds a CRLF on the byte data
 *                   since the receiving MTA uses canonicalized data to calculate MIC
 * @return The base 64 encoded MIC value
 * @exception Exception/*from w w w.  j av a 2  s .  c o m*/
 */
public static String calc(Object content, Certificate[] certs, String algo, boolean addcrlfToString,
        boolean addcrlfToBytes) throws Exception {
    InputStream micStream = null;
    byte micBits[] = null;
    boolean addcrlf = false;

    if (content instanceof byte[]) {
        micBits = fromBytes((byte[]) content, addcrlfToBytes);
    } else if (content instanceof String) {
        micBits = fromString((String) content, addcrlfToString);
    } else if (content instanceof InputStream) {
        if (addcrlfToBytes || addcrlfToString)
            addcrlf = true;
        micStream = (InputStream) content;
    } else if (CryptoUte.isSigned(content)) {
        return fromSMP(certs, content);
    } else if (content instanceof Multipart) {
        Object rc = fromMP((Multipart) content);
        if (rc instanceof InputStream)
            micStream = (InputStream) rc;
        else if (rc instanceof byte[])
            micBits = (byte[]) rc;
    } else {
        error(content);
    }

    MessageDigest messageDigest = MessageDigest.getInstance(algo);
    byte[] mic;

    if (micBits != null) {
        mic = messageDigest.digest(micBits);
    } else {
        byte[] buf = new byte[4096];
        int c;
        while ((c = micStream.read(buf)) > 0) {
            messageDigest.update(buf, 0, c);
        }

        if (addcrlf) {
            messageDigest.update(CRLFBITS);
        }

        if (micStream.markSupported())
            micStream.reset();

        mic = messageDigest.digest();
    }

    return Base64.encodeBase64String(mic);
}

From source file:com.consol.citrus.validation.ValidationUtils.java

/**
 * Validates actual against expected value of element
 * @param actualValue// w ww  .j a  va  2  s  . c  o  m
 * @param expectedValue
 * @param pathExpression
 * @param context
 * @throws com.consol.citrus.exceptions.ValidationException if validation fails
 */
public static void validateValues(Object actualValue, Object expectedValue, String pathExpression,
        TestContext context) throws ValidationException {
    try {
        if (actualValue != null) {
            Assert.isTrue(expectedValue != null, ValidationUtils.buildValueMismatchErrorMessage(
                    "Values not equal for element '" + pathExpression + "'", null, actualValue));

            if (expectedValue instanceof Matcher) {
                Assert.isTrue(((Matcher) expectedValue).matches(actualValue),
                        ValidationUtils.buildValueMismatchErrorMessage(
                                "Values not matching for element '" + pathExpression + "'", expectedValue,
                                actualValue));
                return;
            }

            if (!(expectedValue instanceof String)) {
                Object converted = TypeConversionUtils.convertIfNecessary(actualValue,
                        expectedValue.getClass());

                if (converted instanceof List) {
                    Assert.isTrue(converted.toString().equals(expectedValue.toString()),
                            ValidationUtils.buildValueMismatchErrorMessage(
                                    "Values not equal for element '" + pathExpression + "'",
                                    expectedValue.toString(), converted.toString()));
                } else if (converted instanceof String[]) {
                    String convertedDelimitedString = StringUtils
                            .arrayToCommaDelimitedString((String[]) converted);
                    String expectedDelimitedString = StringUtils
                            .arrayToCommaDelimitedString((String[]) expectedValue);

                    Assert.isTrue(convertedDelimitedString.equals(expectedDelimitedString),
                            ValidationUtils.buildValueMismatchErrorMessage(
                                    "Values not equal for element '" + pathExpression + "'",
                                    expectedDelimitedString, convertedDelimitedString));
                } else if (converted instanceof byte[]) {
                    String convertedBase64 = Base64.encodeBase64String((byte[]) converted);
                    String expectedBase64 = Base64.encodeBase64String((byte[]) expectedValue);

                    Assert.isTrue(convertedBase64.equals(expectedBase64),
                            ValidationUtils.buildValueMismatchErrorMessage(
                                    "Values not equal for element '" + pathExpression + "'", expectedBase64,
                                    convertedBase64));
                } else {
                    Assert.isTrue(converted.equals(expectedValue),
                            ValidationUtils.buildValueMismatchErrorMessage(
                                    "Values not equal for element '" + pathExpression + "'", expectedValue,
                                    converted));
                }
            } else {
                String expectedValueString = expectedValue.toString();
                String actualValueString;
                if (List.class.isAssignableFrom(actualValue.getClass())) {
                    actualValueString = StringUtils.arrayToCommaDelimitedString(
                            ((List) actualValue).toArray(new Object[((List) actualValue).size()]));
                    expectedValueString = expectedValueString.replaceAll("^\\[", "").replaceAll("\\]$", "")
                            .replaceAll(",\\s", ",");
                } else {
                    actualValueString = actualValue.toString();
                }

                if (ValidationMatcherUtils.isValidationMatcherExpression(String.valueOf(expectedValueString))) {
                    ValidationMatcherUtils.resolveValidationMatcher(pathExpression, actualValueString,
                            String.valueOf(expectedValueString), context);
                } else {
                    Assert.isTrue(actualValueString.equals(expectedValueString),
                            ValidationUtils.buildValueMismatchErrorMessage(
                                    "Values not equal for element '" + pathExpression + "'",
                                    expectedValueString, actualValueString));
                }
            }
        } else {
            Assert.isTrue(expectedValue == null || String.valueOf(expectedValue).length() == 0,
                    ValidationUtils.buildValueMismatchErrorMessage(
                            "Values not equal for element '" + pathExpression + "'", expectedValue, null));
        }
    } catch (IllegalArgumentException e) {
        throw new ValidationException("Validation failed:", e);
    }
}

From source file:com.puzzle.module.send.sign.SignXml.java

/**
 * ?xml????xml//w  w w. ja va  2 s  .c o  m
 *
 * @param xml
 * @return
 */
public static String sign(String xml) {

    xml = xml.substring(xml.indexOf("encoding=\"UTF-8\"?>") + "encoding=\"UTF-8\"?>".length() + 1,
            xml.length());//
    ClientApi api = ClientApi.getSingletonClientApi();
    StringBuffer b = new StringBuffer();
    StringBuffer tempXml = null;
    try {

        //??
        String copCode = ConfigUtils.getSingleInstance().config.getProperty("copCode");
        String dxpMode = ConfigUtils.getSingleInstance().config.getProperty("dxpMode");
        String copName = ConfigUtils.getSingleInstance().config.getProperty("copName");
        String dxpId = ConfigUtils.getSingleInstance().config.getProperty("dxpId");
        String cebHeadMessage = ConfigUtils.getSingleInstance().config.getProperty("cebHeadMessage").trim();
        //            if (cebHeadMessage.equals("CEB311Message")||cebHeadMessage.equals("CEB621Message")||cebHeadMessage.equals("CEB511Message")) {
        //                String appTime = StringUtils.substringBetween(xml, "<appTime>", "</appTime>");
        //                appTime = appTime.substring(0, 8);
        //               
        //                int st1 = xml.indexOf("<appTime>");
        //                int st2 = xml.indexOf("</appTime>");
        //                xml = xml.substring(0, st1 + "<appTime>".length()) + appTime + xml.substring(st2, xml.length());
        //
        //            }
        //??sha1?

        //???xml
        b.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")//
                .append("<" + cebHeadMessage
                        + "  xmlns=\"http://www.chinaport.gov.cn/ceb\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\" guid=\""
                        + UUID.randomUUID().toString() + "\" version=\"v1.0\">")
                .append(xml).append("<BaseTransfer>\n" + "      <copCode>").append(copCode)
                .append("</copCode>\n" + "      <copName>").append(copName)
                .append("</copName>\n" + "      <dxpMode>").append(dxpMode)
                .append("</dxpMode>\n" + "      <dxpId>").append(dxpId)
                .append("</dxpId>\n" + "      <note></note>\n" + "   </BaseTransfer>\n");
        tempXml = new StringBuffer(b);
        String spliteCusXmlbeforeSign = b.append("</" + cebHeadMessage + ">").toString();

        byte[] signData = api.getSignData2(spliteCusXmlbeforeSign);
        if (signData == null) {
            log.info("??API");
            return null;
        }
        String SignatureValue = Base64.encodeBase64String(signData);
        //            String SignatureValue = new String(signData);

        String DigestValue = getSha_1zhaiyao(spliteCusXmlbeforeSign);

        String KeyName = getKeyName();
        if (KeyName == null) {
            log.info("?UKEY?");
            return null;
        }
        //            StringBuffer b2 = new StringBuffer();
        tempXml.append("<ds:Signature xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + "<ds:SignedInfo>\n"
                + "<ds:CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\"></ds:CanonicalizationMethod>\n"
                + "<ds:SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"></ds:SignatureMethod>\n"
                + "<ds:Reference URI=\"\">\n" + "<ds:Transforms>\n"
                + "<ds:Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"></ds:Transform>\n"
                + "</ds:Transforms>\n"
                + "<ds:DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"></ds:DigestMethod><ds:DigestValue>")
                .append(DigestValue)
                .append("</ds:DigestValue></ds:Reference>\n" + "</ds:SignedInfo>\n" + "<ds:SignatureValue>")
                .append(SignatureValue).append("</ds:SignatureValue>\n" + "<ds:KeyInfo>\n" + "<ds:KeyName>")
                .append(KeyName)
                .append("</ds:KeyName>\n" + "</ds:KeyInfo>\n" + "</ds:Signature>\n</" + cebHeadMessage + ">");

    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        return null;
    }
    return tempXml.toString();
}