Android中十六进制转字符数组及hex转base64的正确实现方法
问题根因
你当前的错误写法是直接对十六进制字符串的字符编码字节做Base64编码,本质是把「十六进制文本」本身做了编码,而非对十六进制字符串代表的原始二进制数据做编码,因此反向解码只能拿到十六进制字符串,无法还原到最初的原始字符串。
正确实现方案(Java语言适配)
核心修正点
需要先将十六进制字符串转换为其对应的原始二进制字节数组,再对字节数组做Base64编码,而不是直接调用hexValue.getBytes()获取字节,该方法返回的是十六进制每个字符的ASCII编码字节,并非十六进制表示的真实二进制数据。
工具方法准备
// 字节数组转十六进制字符串 public static String bytesToHex(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02x", b)); } return sb.toString(); } // 十六进制字符串转字节数组 public static byte[] hexToBytes(String hex) { int len = hex.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i+1), 16)); } return data; }
十六进制转Base64正确代码
String encodedString = Base64.getEncoder().encodeToString(hexToBytes(hexValue));
完整链路验证示例
以下是String→hex→base64→string全流程的可运行代码:
import java.util.Base64; public class HexBase64Convert { // 字节数组转十六进制字符串 public static String bytesToHex(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02x", b)); } return sb.toString(); } // 十六进制字符串转字节数组 public static byte[] hexToBytes(String hex) { int len = hex.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i+1), 16)); } return data; } public static void main(String[] args) { // 原始输入字符串 String originalInput = "测试字符串test123!@#"; // 正向转换链路 byte[] originalBytes = originalInput.getBytes(); String hexStr = bytesToHex(originalBytes); String base64Str = Base64.getEncoder().encodeToString(hexToBytes(hexStr)); System.out.println("生成Base64结果:" + base64Str); // 反向转换链路 byte[] decodedBase64Bytes = Base64.getDecoder().decode(base64Str); String restoredHexStr = bytesToHex(decodedBase64Bytes); String restoredStr = new String(hexToBytes(restoredHexStr)); System.out.println("还原原始字符串:" + restoredStr); System.out.println("还原一致性校验:" + originalInput.equals(restoredStr)); } }
内容的提问来源于stack exchange,提问作者GOBLiN TheDev
相关产品推荐
相关产品推荐

