Java将十六进制转换为Base64

时间:2014-12-15 22:05:21

标签: java base64

我正在研究Matasano CryptoChallenge,第一个是创建Hex到Base 64转换器。老实说,我不知道如何从这里继续。我的代码:

public class HexToBase64 {

public static void main(String[] args) {
//        String hex  = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
    String hex = "DA65A";
    convertHexTo64(hex);
}

public static String convertHexTo64(String hex) {
    //convert each letter in the hex string to a 4-digit binary string to create a binary representation of the hex string
    StringBuilder binary = new StringBuilder();
    for (int i = 0; i < hex.length(); i++) {
        int dec = Integer.parseInt(hex.charAt(i) + "", 16);
        StringBuilder bin = new StringBuilder(Integer.toBinaryString(dec));
        while(bin.length() < 4){
            bin.insert(0,'0');
        }
        binary.append(bin);
    }
    //now take 6 bits at a time and convert to a single b64 digit to create the final b64 representation
    StringBuilder b64 = new StringBuilder();
    for (int i = 0; i < binary.length(); i++) {
        String temp = binary.substring(i, i+5);
        int dec = Integer.parseInt(temp, 10);
        //convert dec to b64 with the lookup table here then append to b64
    }

    return b64.toString();
}
}

因此,在我一次分离二进制6位并转换为十进制之后,如何将十进制数映射到b64中的相应数字? Hashmap / Hashtable实现是否有效?

此外,该算法显示了我将如何手动进行转换。有没有更好的方法呢?我正在寻找一种转换方式,这将需要一段合理的时间,因此时间和隐含的效率是相关的。

感谢您的时间

编辑:页面还提到&#34;始终在原始字节上操作,从不在编码字符串上操作。仅使用hex和base64进行漂亮打印。&#34;这究竟意味着什么?

2 个答案:

答案 0 :(得分:2)

从此Stack Overflow post中提取,引用Apache Commons Codec

byte[] decodedHex = Hex.decodeHex(hex);
byte[] encodedHexB64 = Base64.codeBase64(decodedHex);

答案 1 :(得分:0)

String hex = "00bc9d2a05ef06c79a6e972f8a36737e";
byte[] decodedHex = org.apache.commons.codec.binary.Hex.decodeHex(hex.toCharArray());
String result = Base64.encodeBase64String(decodedHex);
System.out.println("==> " + result);