Example usage for org.apache.commons.codec.binary Hex decodeHex

List of usage examples for org.apache.commons.codec.binary Hex decodeHex

Introduction

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

Prototype

public static byte[] decodeHex(char[] data) throws IllegalArgumentException 

Source Link

Document

Converts an array of characters representing hexadecimal values into an array of bytes of those same values.

Usage

From source file:org.ballerinalang.stdlib.crypto.CryptoTest.java

@Test(description = "Test RSA-512 siging")
public void testSignRsaSha512() throws DecoderException {
    byte[] expectedSignature = Hex.decodeHex(("6995ba8d2382a8c4f0ed513033126b2305df419a8b105ee60483243229d2c496"
            + "b7f670783c52068cd2b4b8c2392f2932c682f30057cb4d8d616ba3a142356b0394747b2a3642da4d23447bb997eacb086f"
            + "173b4045ee8ee014e1e667e34522defb7a4ac1b5b3f175d40a409d947d562fcf7b2b2631d273751a0f8c658bd8c1d1d23a"
            + "0dbe685b15e13abf45f998114577c85a6478d915a445645a6360944e4962c56bee79d2363931c77f8040c620692debc747"
            + "4c1e62d9d4b0b39fa664b8c3a32155c7c1966ef3d55993ad8f7f3bf4d929cf047ab91344facefeba944b043e1e31496753"
            + "9cb2e6e669ec3352073a8933a2a0cac6056b4997b3628132f7a7e553").toCharArray());

    byte[] payload = "Ballerina test".getBytes(StandardCharsets.UTF_8);

    BValue[] returnValues = BRunUtil.invoke(compileResult, "testSignRsaSha512",
            new BValue[] { new BValueArray(payload),
                    new BString(confRoot.resolve("testKeystore.p12").toString()), new BString("ballerina"),
                    new BString("ballerina"), new BString("ballerina") });
    Assert.assertFalse(returnValues == null || returnValues.length == 0 || returnValues[0] == null);
    Assert.assertEquals(((BValueArray) returnValues[0]).getBytes(), expectedSignature);

    returnValues = BRunUtil.invoke(compileResult, "testVerifyRsaSha512",
            new BValue[] { new BValueArray(payload), returnValues[0],
                    new BString(confRoot.resolve("testKeystore.p12").toString()), new BString("ballerina"),
                    new BString("ballerina") });
    Assert.assertFalse(returnValues == null || returnValues.length == 0 || returnValues[0] == null);
    Assert.assertEquals(((BBoolean) returnValues[0]).booleanValue(), true);
}

From source file:org.ballerinalang.stdlib.crypto.CryptoTest.java

@Test(description = "Test RSA-MD5 siging")
public void testSignRsaMd5() throws DecoderException {
    byte[] expectedSignature = Hex.decodeHex(("457050eca794baf2149f53631f373525fbc7b40de83e0af5b03473e7b726064b"
            + "3eb6a8b7ce48218e4adaf2b598429236192a458ad5cef1ab2f456164f2646ba57a1ce6b858403504ddc49915bf8bf34558"
            + "0366bd9f7d1d777572fcacd3aa935267af6cf5dc988668b8cea0f57cd0e286658f0ca7c060d7a68b6330bc590b6db59489"
            + "aa676b1c539e5bb0116c64a963f8a03789b9fd7e689bac5576eea15d93d45be3547aef7c7dc26251dfa7bdf23b47c6a346"
            + "ae3603c158cbd32ff9298df71f930cebdda8564199e948f1ac03173e9f9d425240c7f99857d5f469dd0b23c0248b4fa42e"
            + "67145ec0e6e8abfc3f7f10122cc278b5469eb970034483839f290eec").toCharArray());

    byte[] payload = "Ballerina test".getBytes(StandardCharsets.UTF_8);

    BValue[] returnValues = BRunUtil.invoke(compileResult, "testSignRsaMd5",
            new BValue[] { new BValueArray(payload),
                    new BString(confRoot.resolve("testKeystore.p12").toString()), new BString("ballerina"),
                    new BString("ballerina"), new BString("ballerina") });
    Assert.assertFalse(returnValues == null || returnValues.length == 0 || returnValues[0] == null);
    Assert.assertEquals(((BValueArray) returnValues[0]).getBytes(), expectedSignature);

    returnValues = BRunUtil.invoke(compileResult, "testVerifyRsaMd5",
            new BValue[] { new BValueArray(payload), returnValues[0],
                    new BString(confRoot.resolve("testKeystore.p12").toString()), new BString("ballerina"),
                    new BString("ballerina") });
    Assert.assertFalse(returnValues == null || returnValues.length == 0 || returnValues[0] == null);
    Assert.assertEquals(((BBoolean) returnValues[0]).booleanValue(), true);
}

From source file:org.bankinterface.util.Utils.java

/**
 * ????//w  w w .  j ava  2  s  .  co  m
 * 
 * @param data
 * @param code
 * @return
 * @throws DecoderException
 * @throws UnsupportedEncodingException
 */
public static String decode(String data, String code) throws DecoderException, UnsupportedEncodingException {
    if (data == null) {
        throw new IllegalArgumentException();
    }
    if (code == null) {
        return data;
    }
    if (Utils.CODE_BASE64.equals(code)) {
        return new String(Base64.decodeBase64(data));
    } else if (Utils.CODE_HEX.equals(code)) {
        return new String(Hex.decodeHex(data.toCharArray()));
    } else if (Utils.CODE_URL_UTF8.equals(code)) {
        return URLDecoder.decode(data, CHARSET_UTF8);
    } else if (Utils.CODE_URL_GBK.equals(code)) {
        return URLDecoder.decode(data, CHARSET_GBK);
    } else {
        throw new UnsupportedOperationException();
    }
}

From source file:org.basinmc.irc.bridge.github.GitHubServerHandler.java

/**
 * Verifies a request signature.//from  w  w  w.  j  ava2 s  .com
 *
 * @param data      a payload.
 * @param signature a signature.
 * @return true if valid, false otherwise.
 */
private boolean verifySignature(@Nonnull String data, @Nonnull String signature) {
    if (this.secret == null) {
        logger.warn("No secret key specified. Signature checks will be skipped!");
        return true;
    }

    try {
        Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM);
        mac.init(this.secret);

        byte[] expected = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Arrays.equals(expected, Hex.decodeHex(signature.toCharArray()));
    } catch (InvalidKeyException | NoSuchAlgorithmException ex) {
        logger.error("Could not verify signature: " + ex.getMessage(), ex);
    } catch (DecoderException ex) {
        logger.warn("Could not decode signature: " + ex.getMessage(), ex);
    }

    throw new IllegalStateException("Could not verify signature");
}

From source file:org.bimserver.ifc.step.deserializer.IfcStepDeserializer.java

private String readString(String value) throws DeserializeException {
    String result = value.substring(1, value.length() - 1);
    // Replace all '' with '
    while (result.contains("''")) {
        int index = result.indexOf("''");
        result = result.substring(0, index) + "'" + result.substring(index + 2);
    }/*from ww  w  .j a  v  a2s  . c o m*/
    while (result.contains("\\S\\")) {
        int index = result.indexOf("\\S\\");
        char x = result.charAt(index + 3);
        ByteBuffer b = ByteBuffer.wrap(new byte[] { (byte) (x + 128) });
        CharBuffer decode = Charsets.ISO_8859_1.decode(b);
        result = result.substring(0, index) + decode.get() + result.substring(index + 4);
    }
    while (result.contains("\\X\\")) {
        int index = result.indexOf("\\X\\");
        int code = Integer.parseInt(result.substring(index + 3, index + 5), 16);
        ByteBuffer b = ByteBuffer.wrap(new byte[] { (byte) (code) });
        CharBuffer decode = Charsets.ISO_8859_1.decode(b);
        result = result.substring(0, index) + decode.get() + result.substring(index + 5);
    }
    while (result.contains("\\X2\\")) {
        int index = result.indexOf("\\X2\\");
        int indexOfEnd = result.indexOf("\\X0\\");
        if (indexOfEnd == -1) {
            throw new DeserializeException("\\X2\\ not closed with \\X0\\");
        }
        if ((indexOfEnd - index) % 4 != 0) {
            throw new DeserializeException("Number of hex chars in \\X2\\ definition not divisible by 4");
        }
        try {
            ByteBuffer buffer = ByteBuffer
                    .wrap(Hex.decodeHex(result.substring(index + 4, indexOfEnd).toCharArray()));
            CharBuffer decode = Charsets.UTF_16BE.decode(buffer);
            result = result.substring(0, index) + decode.toString() + result.substring(indexOfEnd + 4);
        } catch (DecoderException e) {
            throw new DeserializeException(e);
        }
    }
    while (result.contains("\\X4\\")) {
        int index = result.indexOf("\\X4\\");
        int indexOfEnd = result.indexOf("\\X0\\");
        if (indexOfEnd == -1) {
            throw new DeserializeException("\\X4\\ not closed with \\X0\\");
        }
        if ((indexOfEnd - index) % 8 != 0) {
            throw new DeserializeException("Number of hex chars in \\X4\\ definition not divisible by 8");
        }
        try {
            ByteBuffer buffer = ByteBuffer
                    .wrap(Hex.decodeHex(result.substring(index + 4, indexOfEnd).toCharArray()));
            CharBuffer decode = Charset.forName("UTF-32").decode(buffer);
            result = result.substring(0, index) + decode.toString() + result.substring(indexOfEnd + 4);
        } catch (DecoderException e) {
            throw new DeserializeException(e);
        } catch (UnsupportedCharsetException e) {
            throw new DeserializeException("UTF-32 is not supported on your system", e);
        }
    }
    // Replace all \\ with \
    while (result.contains("\\\\")) {
        int index = result.indexOf("\\\\");
        result = result.substring(0, index) + "\\" + result.substring(index + 2);
    }
    return result;
}

From source file:org.bimserver.tests.TestEnc.java

private void start() {
    byte[] key = new byte[16];
    new Random().nextBytes(key);
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");

    String toEncrypt = "1";

    try {/*from w  ww .  j a va 2  s.c o m*/
        Cipher encodingCipher = Cipher.getInstance("AES");
        encodingCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encodedBytes = encodingCipher.doFinal(toEncrypt.getBytes(Charsets.UTF_8));
        System.out.println("Encoded size: " + encodedBytes.length);
        String encodedHexString = new String(Hex.encodeHex(encodedBytes));

        System.out.println("Encoded hex: " + encodedHexString);

        Cipher decodingCipher = Cipher.getInstance("AES");
        decodingCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        ByteBuffer wrap = ByteBuffer
                .wrap(decodingCipher.doFinal(Hex.decodeHex(encodedHexString.toCharArray())));
        String result = new String(wrap.array(), Charsets.UTF_8);

        System.out.println(result);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (DecoderException e) {
        e.printStackTrace();
    }
}

From source file:org.bimserver.webservices.authorization.Authorization.java

public static Authorization fromToken(SecretKeySpec key, String token) throws AuthenticationException {
    if (token == null) {
        throw new IllegalArgumentException("Token required");
    }/*from w w  w .jav  a2 s .c  o  m*/
    try {
        int hashSizeBytes = 16;
        Cipher decodingCipher = Cipher.getInstance("AES");
        decodingCipher.init(Cipher.DECRYPT_MODE, key);
        ByteBuffer buffer = ByteBuffer.wrap(decodingCipher.doFinal(Hex.decodeHex(token.toCharArray())));
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        byte[] foundHash = new byte[hashSizeBytes];
        buffer.get(foundHash, 0, hashSizeBytes);
        byte[] hashInput = new byte[buffer.capacity() - hashSizeBytes];
        buffer.get(hashInput);
        buffer.position(hashSizeBytes);
        byte[] calculatedHash = messageDigest.digest(hashInput);
        if (Arrays.equals(foundHash, calculatedHash)) {
            byte type = buffer.get();
            Authorization authorization = null;
            long expires = buffer.getLong();
            long uoid = buffer.getLong();
            switch (type) {
            case ExplicitRightsAuthorization.ID:
                authorization = ExplicitRightsAuthorization.fromBuffer(buffer);
                break;
            case UserAuthorization.ID:
                authorization = UserAuthorization.fromBuffer(buffer);
                break;
            case SystemAuthorization.ID:
                authorization = SystemAuthorization.fromBuffer(buffer);
                break;
            case AnonymousAuthorization.ID:
                authorization = AnonymousAuthorization.fromBuffer(buffer);
                break;
            case AdminAuthorization.ID:
                authorization = AdminAuthorization.fromBuffer(buffer);
                break;
            case SingleProjectAuthorization.ID:
                authorization = SingleProjectAuthorization.fromBuffer(buffer);
                break;
            default:
                throw new AuthenticationException("Unknown authorization type: " + type);
            }
            authorization.setUoid(uoid);
            authorization.setExpires(expires);
            if (authorization.getExpires().getTimeInMillis() < new GregorianCalendar().getTimeInMillis()) {
                throw new AuthenticationException("This token has expired");
            }
            return authorization;
        } else {
            throw new AuthenticationException("Given token is corrupt");
        }
    } catch (GeneralSecurityException e) {
        throw new AuthenticationException("Invalid token", e);
    } catch (DecoderException e) {
        throw new AuthenticationException(e);
    }
}

From source file:org.breizhbeans.thrift.tools.thriftmongobridge.secured.TBSONSecuredWrapper.java

public byte[] decipherSecuredField(Short id, DBObject securedWraper) {
    try {/*from w w w .j a  v a 2  s  . co  m*/
        String key = Short.toString(id);
        String hexValue = (String) securedWraper.get(key);
        byte[] protectedData = Hex.decodeHex(hexValue.toCharArray());

        return decipher(protectedData);
    } catch (Exception exp) {

    }
    return null;
}

From source file:org.breizhbeans.thrift.tools.thriftmongobridge.secured.TBSONSecuredWrapper.java

public byte[] decipherValue(String hexValue) {
    try {/*  w ww.  j a v  a  2 s  . c  o  m*/
        byte[] protectedData = Hex.decodeHex(hexValue.toCharArray());
        return decipher(protectedData);
    } catch (Exception exp) {

    }
    return null;
}