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

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

Introduction

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

Prototype

public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe) 

Source Link

Document

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Usage

From source file:com.activecq.api.utils.EncodingUtil.java

/**
 * Base64 Decode data from UTF-8/URL Friendly format
 *
 * @param encodedData//w ww . ja  v  a  2 s .c o  m
 * @return
 * @throws UnsupportedEncodingException
 */
public static String decode(String encodedData) throws UnsupportedEncodingException {
    return new String(new Base64(0, null, true).decode(encodedData.getBytes("UTF-8")));
}

From source file:com.activecq.api.utils.EncodingUtil.java

/**
 * Base64 Encode data to UTF-8/URL Friendly format
 *
 * @param unencodedData//w w w.  j av  a  2  s. com
 * @return
 * @throws UnsupportedEncodingException
 */
public static String encode(String unencodedData) throws UnsupportedEncodingException {
    return new String(new Base64(0, null, true).encode(unencodedData.getBytes("UTF-8")));
}

From source file:com.completetrsst.crypto.Common.java

/**
 * Converts an EC PublicKey to an X509-encoded string.
 *///w w  w.ja v a 2  s . co m
public static String toX509FromPublicKey(PublicKey publicKey) throws GeneralSecurityException {
    KeyFactory factory = KeyFactory.getInstance("EC");
    X509EncodedKeySpec spec = factory.getKeySpec(publicKey, X509EncodedKeySpec.class);
    return new Base64(0, null, true).encodeToString(spec.getEncoded());
}

From source file:de.zib.gndms.gritserv.tests.EncTest.java

public static void dryRun(EndpointReferenceType epr) throws Exception {

    ByteArrayOutputStream bse = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bse);
    String sepr = ObjectSerializer.toString(epr, QNAME);
    System.out.println(sepr);// w  w w . jav  a  2s . c  om
    oos.writeObject(sepr);

    Base64 b64 = new Base64(0, new byte[] {}, true);
    String uuepr = b64.encodeToString(bse.toByteArray());
    System.out.println("uuepr: \"" + uuepr + "\"");

    byte[] bt = b64.decode(uuepr.getBytes());

    ByteArrayInputStream bis = new ByteArrayInputStream(bt);
    ObjectInputStream ois = new ObjectInputStream(bis);
    String eprs = (String) ois.readObject();
    System.out.println(eprs);
}

From source file:de.betterform.xml.xforms.xpath.saxon.function.Digest.java

/**
 * Evaluate in a general context/*from   w w w  .  j a v  a  2 s  .  c  o m*/
 */
public Item evaluateItem(XPathContext xpathContext) throws XPathException {

    // XXX In some cases the xforms-compute-exception should be an xforms-bind-exception

    final String data = argument[0].evaluateAsString(xpathContext).toString();
    final String algorithm = argument[1].evaluateAsString(xpathContext).toString();
    final String encoding = argument != null && argument.length >= 3
            ? argument[2].evaluateAsString(xpathContext).toString()
            : kBASE64;

    if (!kSUPPORTED_ALG.contains(algorithm)) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(new XFormsComputeException("Unsupported algorithm '" + algorithm + "'",
                xformsElement.getTarget(), this));
    }

    if (!kSUPPORTED_ENCODINGS.contains(encoding)) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(new XFormsComputeException("Unsupported encoding '" + encoding + "'",
                xformsElement.getTarget(), this));
    }

    MessageDigest messageDigest;
    try {
        messageDigest = MessageDigest.getInstance(algorithm);
        messageDigest.update(data.getBytes("utf-8"));

        byte[] digest = messageDigest.digest();

        final BinaryEncoder encoder;
        if ("base64".equals(encoding)) {
            encoder = new Base64(digest.length, "".getBytes(), false);
        } else {
            encoder = new Hex();
        }
        return new StringValue(new String(encoder.encode(digest), "ASCII"));

    } catch (NoSuchAlgorithmException e) {
        throw new XPathException(e);
    } catch (UnsupportedEncodingException e) {
        throw new XPathException(e);
    } catch (EncoderException e) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(
                new XFormsComputeException("Encoder exception.", e, xformsElement.getTarget(), this));
    }

}

From source file:ECToken3.java

public static final String encryptv3(String key, String input) throws java.io.UnsupportedEncodingException,
        java.security.NoSuchAlgorithmException, javax.crypto.NoSuchPaddingException,
        java.security.InvalidKeyException, javax.crypto.IllegalBlockSizeException,
        javax.crypto.BadPaddingException, java.security.InvalidAlgorithmParameterException {

    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| Encrypt\n");
    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| key:                   %s\n", key);
    //System.out.format("| token:                 %s\n", input);

    //----------------------------------------------------
    // Get SHA-256 of key
    //----------------------------------------------------
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(key.getBytes("ASCII"));
    byte[] keyDigest = md.digest();

    //----------------------------------------------------
    // Get Random IV
    //----------------------------------------------------
    SecureRandom random = new SecureRandom();
    byte[] ivBytes = new byte[12];
    random.nextBytes(ivBytes);// w  w w. j a  v a  2  s  .  co  m

    //----------------------------------------------------
    // Encrypt
    //----------------------------------------------------
    AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
    cipher.init(true, new AEADParameters(new KeyParameter(keyDigest), MAC_SIZE_BITS, ivBytes));
    byte[] inputBytes = input.getBytes("ASCII");

    byte[] enc = new byte[cipher.getOutputSize(inputBytes.length)];

    try {
        int res = cipher.processBytes(inputBytes, 0, inputBytes.length, enc, 0);
        cipher.doFinal(enc, res);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    byte[] ivPlusCipherText = new byte[ivBytes.length + enc.length];
    System.arraycopy(ivBytes, 0, ivPlusCipherText, 0, ivBytes.length);
    System.arraycopy(enc, 0, ivPlusCipherText, ivBytes.length, enc.length);

    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| iv:                    %s\n", bytesToHex(ivBytes));
    //System.out.format("| ciphertext:            %s\n", bytesToHex(Arrays.copyOfRange(enc, 0, enc.length - 16)));
    //System.out.format("| tag:                   %s\n", bytesToHex(Arrays.copyOfRange(enc, enc.length - 16, enc.length)));
    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| token:                 %s\n", bytesToHex(ivPlusCipherText));
    //System.out.format("+-------------------------------------------------------------\n");

    String result = null;
    byte[] temp = null;
    Base64 encoder = new Base64(0, temp, true);
    byte[] encodedBytes = encoder.encode(ivPlusCipherText);
    String encodedStr = new String(encodedBytes, "ASCII").trim();
    String encodedStrTrim = encodedStr.trim();
    return encodedStr.trim();
}

From source file:de.zib.gndms.gritserv.delegation.DelegationAux.java

public static EndpointReferenceType extractDelegationEPR(ContextT con) throws Exception {

    ContextTEntry[] entries = con.getEntry();
    ArrayList<ContextTEntry> al = new ArrayList<ContextTEntry>(entries.length);
    EndpointReferenceType epr = null;//from w  w w  .  j a  va2s  .c  o  m

    for (ContextTEntry e : entries) {
        if (e.getKey().equals(DELEGATION_EPR_KEY)) {
            //epr = eprFormXML( e.get_value().toString( ) );
            final String uuepr = e.get_value().toString();
            logger.debug("encoded delegation epr: " + uuepr);

            final Base64 b64 = new Base64(4000, new byte[] {}, true);
            byte[] ba = b64.decode(uuepr);
            ByteArrayInputStream bis = new ByteArrayInputStream(ba);
            ObjectInputStream ois = new ObjectInputStream(bis);
            String eprs = (String) ois.readObject();
            InputSource is = new InputSource(new StringReader(eprs));

            epr = (EndpointReferenceType) ObjectDeserializer.deserialize(is, EndpointReferenceType.class);
        } else
            al.add(e);
    }

    ContextTEntry[] r = al.toArray(new ContextTEntry[al.size()]);

    con.setEntry(r);

    return epr;
}

From source file:com.igormaznitsa.jcp.expression.functions.FunctionBINFILE.java

@Nonnull
private static String convertTo(@Nonnull final File file, @Nonnull final Type type, final boolean deflate,
        final int lineLength, @Nonnull final String endOfLine) throws IOException {
    final StringBuilder result = new StringBuilder(512);
    byte[] array = FileUtils.readFileToByteArray(file);

    if (deflate) {
        array = deflate(array);/*from   ww w  . j  a  v  a 2s .  co  m*/
    }

    int endLinePos = lineLength;
    boolean addNextLine = false;

    switch (type) {
    case BASE64: {
        final String baseEncoded = new Base64(lineLength, endOfLine.getBytes("UTF-8"), false)
                .encodeAsString(array);
        result.append(baseEncoded.trim());
    }
        break;
    case BYTEARRAY:
    case INT8:
    case UINT8: {
        for (final byte b : array) {
            if (result.length() > 0) {
                result.append(',');
            }

            if (addNextLine) {
                addNextLine = false;
                result.append(endOfLine);
            }

            switch (type) {
            case BYTEARRAY: {
                result.append("(byte)0x").append(Integer.toHexString(b & 0xFF).toUpperCase(Locale.ENGLISH));
            }
                break;
            case UINT8: {
                result.append(Integer.toString(b & 0xFF).toUpperCase(Locale.ENGLISH));
            }
                break;
            case INT8: {
                result.append(Integer.toString(b).toUpperCase(Locale.ENGLISH));
            }
                break;
            default:
                throw new Error("Unexpected type : " + type);
            }

            if (lineLength > 0 && result.length() >= endLinePos) {
                addNextLine = true;
                endLinePos = result.length() + lineLength;
            }
        }

    }
        break;
    default:
        throw new Error("Unexpected type : " + type);
    }

    return result.toString();
}

From source file:de.betterform.xml.xforms.xpath.saxon.function.Hmac.java

/**
 * Evaluate in a general context//from  ww  w. j  ava2s  . c  o m
 */
public Item evaluateItem(XPathContext xpathContext) throws XPathException {
    final String key = argument[0].evaluateAsString(xpathContext).toString();
    final String data = argument[1].evaluateAsString(xpathContext).toString();
    final String originalAlgorithmString = argument[2].evaluateAsString(xpathContext).toString();
    final String algorithm = "Hmac" + originalAlgorithmString.replaceAll("-", "");
    final String encoding = argument != null && argument.length >= 4
            ? argument[3].evaluateAsString(xpathContext).toString()
            : kBASE64;

    if (!kSUPPORTED_ALG.contains(originalAlgorithmString)) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(new XFormsComputeException(
                "Unsupported algorithm '" + originalAlgorithmString + "'", xformsElement.getTarget(), this));
    }

    if (!kSUPPORTED_ENCODINGS.contains(encoding)) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(new XFormsComputeException("Unsupported encoding '" + encoding + "'",
                xformsElement.getTarget(), this));
    }

    try {
        // Generate a key for the HMAC-MD5 keyed-hashing algorithm; see RFC 2104
        // In practice, you would save this key.
        SecretKey secretKey = new SecretKeySpec(key.getBytes("utf-8"), algorithm);

        // Create a MAC object using HMAC-MD5 and initialize with kesaxoniay
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        mac.update(data.getBytes("utf-8"));

        byte[] digest = mac.doFinal();

        final BinaryEncoder encoder;
        if ("base64".equals(encoding)) {
            encoder = new Base64(digest.length, "".getBytes(), false);
        } else {
            encoder = new Hex();
        }

        return new StringValue(new String(encoder.encode(digest), "ASCII"));

    } catch (NoSuchAlgorithmException e) {
        throw new XPathException(e);
    } catch (UnsupportedEncodingException e) {
        throw new XPathException(e);
    } catch (EncoderException e) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(
                new XFormsComputeException("Encoder exception.", e, xformsElement.getTarget(), this));
    } catch (InvalidKeyException e) {
        throw new XPathException(e);
    }

}

From source file:com.github.hdl.tensorflow.yarn.app.ClusterSpec.java

public static String decodeJsonString(String base64String) {
    Base64 decoder = new Base64(0, null, true);
    byte[] data = decoder.decode(base64String);
    return new String(data);
}