Java将十六进制转换为Base64

Yaz*_*zra 1 java base64

我正在开展 Matasano CryptoChallenge,第一个任务是创建一个十六进制到 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();
}
}
Run Code Online (Sandbox Code Playgroud)

那么我将二进制一次分离6位并转换为十进制后,如何将十进制数映射到b64中对应的数字呢?Hashmap/Hashtable 实现是否高效?

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

感谢您的时间

编辑:该页面还提到“始终对原始字节进行操作,而不是对编码字符串进行操作。仅使用十六进制和 base64 进行漂亮打印。” 这到底是什么意思?

JP *_*ura 6

摘自Stack Overflow 帖子,其中引用了Apache Commons Codec

byte[] decodedHex = Hex.decodeHex(hex);
byte[] encodedHexB64 = Base64.codeBase64(decodedHex);
Run Code Online (Sandbox Code Playgroud)

  • 你忘了提及 Hex 来自 Commons Codec (2认同)
  • @yazan这里是相关的javadoc,解释了它们的作用和返回的内容:http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Hex.html#decodeHex( char[]) -- 和 -- http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html#decodeBase64(byte[]) (2认同)