十六进制到Base64转换

时间:2017-01-27 07:07:59

标签: java amazon-web-services base64 hex md5

我尝试按照Web上的几个示例将Hex值转换为Base64并失败。 Hex to Base64 convertion

http://tomeko.net/online_tools/hex_to_base64.php?lang=en

我需要比较AWS对象的eTag值和Google Cloud Storage MD5值。 base64(eTag)=GCS_MD5eTag:6a95b4dd5419f2ffb9f655309c931cb0MD5:apW03VQZ8v+59lUwnJMcsA== 如何将Hex转换为Base64?

我尝试了堆栈溢出的各种示例,但仍然无法做到。

public static void main(String[] args) throws IOException {
    String hexadecimal = "6a95b4dd5419f2ffb9f655309c931cb0";
    System.out.println("hexadecimal: " + hexadecimal);
    String binaryNum = hexToBin(hexadecimal);
    System.out.println("" + binaryNum + ", length:" + binaryNum.length());
    byte[] encoded = Base64.encodeBase64(binaryNum.getBytes());
    byte[] decoded = Base64.decodeBase64(binaryNum.getBytes());
    System.out.println("encoded: " + Base64.isBase64(encoded));
    System.out.println("decoded: " + Base64.isBase64(decoded));
    System.out.println(Arrays.toString(encoded));
    String encodedString = new String(encoded);
    System.out.println(binaryNum + " = " + encodedString);

    String decodedString = new String(decoded);
    System.out.println(binaryNum + " = " + decodedString);

    System.out.println("ByteEncoding::" + base64Encode(binaryNum.getBytes()));
    System.out.println("ByteDecoding::" + base64Decode(binaryNum));
}

2 个答案:

答案 0 :(得分:2)

使用你似乎正在使用的相同的库(假设Apache Commons Base64,因为标准的Base64类有其他方法),这里有一些简短的代码将十六进制字符串转换为(最终)一个base64字符串,并检查它是base64编码的。它会转换为您给出的相同base64值,并且链接转换器输出:

import java.math.BigInteger;
import org.apache.commons.codec.binary.Base64;

public class Main {
  public static void main(String... args) {
    String hexadecimal = "6a95b4dd5419f2ffb9f655309c931cb0";
    System.out.println("hexadecimal: " + hexadecimal);

    BigInteger bigint = new BigInteger(hexadecimal, 16);

    StringBuilder sb = new StringBuilder();
    byte[] ba = Base64.encodeInteger(bigint);
    for (byte b : ba) {
        sb.append((char)b);
    }
    String s = sb.toString();
    System.out.println("base64: " + s);
    System.out.println("encoded: " + Base64.isBase64(s));
  }
}

//Output:
//hexadecimal: 6a95b4dd5419f2ffb9f655309c931cb0
//base64: apW03VQZ8v+59lUwnJMcsA==
//encoded: true

如果您没有导入Apache Base64,那可能会导致问题。它是一个外部库,因此您必须从here下载它,将其添加到IDE中的项目中,然后按照上面的代码导入。

答案 1 :(得分:0)

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

来自here