Example usage for org.apache.commons.codec BinaryEncoder encode

List of usage examples for org.apache.commons.codec BinaryEncoder encode

Introduction

In this page you can find the example usage for org.apache.commons.codec BinaryEncoder encode.

Prototype

byte[] encode(byte[] source) throws EncoderException;

Source Link

Document

Encodes a byte array and return the encoded data as a byte array.

Usage

From source file:com.github.jinahya.codec.HexBinaryEncoderProxyTest.java

@Test
public void testAsBinaryEncoder() throws EncoderException {

    final BinaryEncoder encoder = (BinaryEncoder) HexBinaryEncoderProxy.newInstance();

    try {//  w  w w .  j  a v  a2  s.c  o  m
        encoder.encode((byte[]) null);
        Assert.fail("passed: encode((byte[]) null)");
    } catch (final NullPointerException npe) {
        // expected
    }

    final byte[] decoded = Tests.decodedBytes();
    final byte[] encoded = encoder.encode(decoded);
}

From source file:com.github.jinahya.codec.commons.RareBinaryEncoderProxyTest.java

@Test
public void testAsBinaryEncoder() throws EncoderException {

    final BinaryEncoder encoder = (BinaryEncoder) RareBinaryEncoderProxy.newInstance();

    try {/*from www. jav a 2  s .  co  m*/
        encoder.encode((byte[]) null);
        Assert.fail("passed: encode((byte[]) null)");
    } catch (final NullPointerException npe) {
        // expected
    }

    final byte[] expected = new byte[0];
    final byte[] actual = encoder.encode(expected);
    Assert.assertEquals(actual, expected);
}

From source file:com.github.jinahya.codec.PercentBinaryEncoderProxyTest.java

@Test
public void testAsBinaryDecoder() throws Exception {

    final BinaryEncoder encoder = (BinaryEncoder) PercentBinaryEncoderProxy.newInstance();

    try {/*from   w  w w  . ja v  a2s . c om*/
        encoder.encode((byte[]) null);
        Assert.fail("passed: encode((byte[]) null)");
    } catch (final NullPointerException npe) {
        // ok
    }

    final byte[] input = PercentCodecTestHelper.decodedBytes(1024);
    final byte[] output = encoder.encode(input);
}

From source file:com.github.jinahya.codec.PercentBinaryEncoderProxyTest.java

@Test(invocationCount = 128)
public void testEncode() throws Exception {

    final BinaryEncoder encoder = (BinaryEncoder) PercentBinaryEncoderProxy.newInstance();

    try {//w  w w. j  a  v a  2s  .co  m
        encoder.encode((Object) null);
        Assert.fail("passed: encode((Object) null)");
    } catch (final NullPointerException npe) {
        // expected
    }

    try {
        encoder.encode((byte[]) null);
        Assert.fail("passed: encode((byte[]) null)");
    } catch (final NullPointerException npe) {
        // expected
    }

    final byte[] origin = PercentCodecTestHelper.decodedBytes(1024);
    System.out.println("original ----------------------------------------");
    System.out.println(Base64.encodeBase64String(origin));

    final byte[] encoded = encoder.encode(origin);
    System.out.println("encoded -----------------------------------------");
    System.out.println(new String(encoded, "US-ASCII"));

    final byte[] decoded = PercentDecoder.decodeMultiple(encoded);
    System.out.println("decoded -----------------------------------------");
    System.out.println(Base64.encodeBase64String(decoded));

    Assert.assertEquals(decoded, origin);
}

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

/**
 * Evaluate in a general context/*from  w  ww. 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:de.betterform.xml.xforms.xpath.saxon.function.Hmac.java

/**
 * Evaluate in a general context/* w w w  . j  a va  2s  . 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.neovisionaries.security.Digest.java

/**
 * Perform the final update with the given byte array, and then
 * complete the hash computation and get the resulting hash value
 * as a string. The given encoder is used to convert the digest
 * value to a string.//w  ww  .  j  a  v a  2 s .  co  m
 *
 * @param input
 *         Byte array used for the last update. If {@code null}
 *         is given, it is just ignored.
 *
 * @param encoder
 *         Encoder to convert a digest value to a byte array
 *         whose elements are printable characters. For example,
 *         {@link org.apache.commons.codec.binary.Base64}.
 *
 * @return
 *         The result hash value encoded by the encoder.
 *
 * @throws IllegalArgumentException
 *         {@code encoder} is {@code null}.
 *
 * @throws RuntimeException
 *         If the encoder throws {@link EncoderException},
 *         a {@code RuntimeException} wrapping the
 *         {@code EncoderException} is thrown.
 *
 * @since 1.3
 */
public String digestAsString(byte[] input, BinaryEncoder encoder) {
    if (encoder == null) {
        throw new IllegalArgumentException("encoder is null.");
    }

    // Compute the digest value.
    byte[] digest = (input != null) ? digest(input) : digest();

    // Encoded value.
    byte[] encoded = null;

    try {
        // Encode the digest value.
        encoded = encoder.encode(digest);
    } catch (EncoderException e) {
        // Failed to encode the digest value.
        throw new RuntimeException("Failed to encode the digest value.", e);
    }

    try {
        // Convert the byte array into a string.
        return new String(encoded, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // This won't happen.
        return null;
    }
}