add Base16Codec

This commit is contained in:
Looly 2022-03-18 01:02:31 +08:00
parent b0605b55ba
commit 7b4fd66d81
6 changed files with 150 additions and 113 deletions

View File

@ -0,0 +1,118 @@
package cn.hutool.core.codec;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.util.StrUtil;
/**
* Base16Hex编码解码器<br>
* 十六进制简写为hex或下标16在数学中是一种逢16进1的进位制一般用数字0到9和字母A到F表示其中:A~F即10~15<br>
* 例如十进制数57在二进制写作111001在16进制写作39
*
* @author looly
* @since 5.7.23
*/
public class Base16Codec implements Encoder<byte[], char[]>, Decoder<CharSequence, byte[]> {
public static final Base16Codec CODEC_LOWER = new Base16Codec(true);
public static final Base16Codec CODEC_UPPER = new Base16Codec(false);
private final char[] alphabets;
/**
* 构造
*
* @param lowerCase 是否小写
*/
public Base16Codec(boolean lowerCase) {
this.alphabets = (lowerCase ? "0123456789abcdef" : "0123456789ABCDEF").toCharArray();
}
@Override
public char[] encode(byte[] data) {
final int len = data.length;
final char[] out = new char[len << 1];//len*2
// two characters from the hex value.
for (int i = 0, j = 0; i < len; i++) {
out[j++] = alphabets[(0xF0 & data[i]) >>> 4];// 高位
out[j++] = alphabets[0x0F & data[i]];// 低位
}
return out;
}
@Override
public byte[] decode(CharSequence encoded) {
if (StrUtil.isEmpty(encoded)) {
return null;
}
encoded = StrUtil.cleanBlank(encoded);
int len = encoded.length();
if ((len & 0x01) != 0) {
// 如果提供的数据是奇数长度则前面补0凑偶数
encoded = "0" + encoded;
len = encoded.length();
}
final byte[] out = new byte[len >> 1];
// two characters form the hex value.
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(encoded.charAt(j), j) << 4;
j++;
f = f | toDigit(encoded.charAt(j), j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
/**
* 将指定char值转换为Unicode字符串形式常用于特殊字符例如汉字转Unicode形式<br>
* 转换的字符串如果u后不足4位则前面用0填充例如
*
* <pre>
* '你' ='\u4f60'
* </pre>
*
* @param ch char值
* @return Unicode表现形式
*/
public String toUnicodeHex(char ch) {
return "\\u" +//
alphabets[(ch >> 12) & 15] +//
alphabets[(ch >> 8) & 15] +//
alphabets[(ch >> 4) & 15] +//
alphabets[(ch) & 15];
}
/**
* 将byte值转为16进制并添加到{@link StringBuilder}
*
* @param builder {@link StringBuilder}
* @param b byte
*/
public void appendHex(StringBuilder builder, byte b) {
int high = (b & 0xf0) >>> 4;//高位
int low = b & 0x0f;//低位
builder.append(alphabets[high]);
builder.append(alphabets[low]);
}
/**
* 将十六进制字符转换成一个整数
*
* @param ch 十六进制char
* @param index 十六进制字符在字符数组中的位置
* @return 一个整数
* @throws UtilException 当ch不是一个合法的十六进制字符时抛出运行时异常
*/
private static int toDigit(char ch, int index) {
int digit = Character.digit(ch, 16);
if (digit < 0) {
throw new UtilException("Illegal hexadecimal character {} at index {}", ch, index);
}
return digit;
}
}

View File

@ -83,12 +83,12 @@ public class Base62Codec implements Encoder<byte[], byte[]>, Decoder<byte[], byt
/** /**
* 编码指定消息bytes为Base62格式的bytes * 编码指定消息bytes为Base62格式的bytes
* *
* @param message 被编码的消息 * @param data 被编码的消息
* @return Base62内容 * @return Base62内容
*/ */
@Override @Override
public byte[] encode(byte[] message) { public byte[] encode(byte[] data) {
final byte[] indices = convert(message, STANDARD_BASE, TARGET_BASE); final byte[] indices = convert(data, STANDARD_BASE, TARGET_BASE);
return translate(indices, alphabet); return translate(indices, alphabet);
} }

View File

@ -19,6 +19,7 @@ import java.nio.charset.Charset;
*/ */
public class Base64 { public class Base64 {
private static final Charset DEFAULT_CHARSET = CharsetUtil.CHARSET_UTF_8;
// -------------------------------------------------------------------- encode // -------------------------------------------------------------------- encode
/** /**
@ -29,7 +30,9 @@ public class Base64 {
* @return 编码后的bytes * @return 编码后的bytes
*/ */
public static byte[] encode(byte[] arr, boolean lineSep) { public static byte[] encode(byte[] arr, boolean lineSep) {
return Base64Encoder.encode(arr, lineSep); return lineSep ?
java.util.Base64.getMimeEncoder().encode(arr) :
java.util.Base64.getEncoder().encode(arr);
} }
/** /**
@ -39,7 +42,9 @@ public class Base64 {
* @param lineSep 在76个char之后是CRLF还是EOF * @param lineSep 在76个char之后是CRLF还是EOF
* @return 编码后的bytes * @return 编码后的bytes
* @since 3.0.6 * @since 3.0.6
* @deprecated 按照RFC2045规范URL安全的Base64无需换行
*/ */
@Deprecated
public static byte[] encodeUrlSafe(byte[] arr, boolean lineSep) { public static byte[] encodeUrlSafe(byte[] arr, boolean lineSep) {
return Base64Encoder.encodeUrlSafe(arr, lineSep); return Base64Encoder.encodeUrlSafe(arr, lineSep);
} }
@ -51,7 +56,7 @@ public class Base64 {
* @return 被加密后的字符串 * @return 被加密后的字符串
*/ */
public static String encode(CharSequence source) { public static String encode(CharSequence source) {
return Base64Encoder.encode(source); return encode(source, DEFAULT_CHARSET);
} }
/** /**
@ -62,7 +67,7 @@ public class Base64 {
* @since 3.0.6 * @since 3.0.6
*/ */
public static String encodeUrlSafe(CharSequence source) { public static String encodeUrlSafe(CharSequence source) {
return Base64Encoder.encodeUrlSafe(source); return encodeUrlSafe(source, DEFAULT_CHARSET);
} }
/** /**
@ -95,7 +100,9 @@ public class Base64 {
* @param charset 字符集 * @param charset 字符集
* @return 被加密后的字符串 * @return 被加密后的字符串
* @since 3.0.6 * @since 3.0.6
* @deprecated 请使用 {@link #encodeUrlSafe(CharSequence, Charset)}
*/ */
@Deprecated
public static String encodeUrlSafe(CharSequence source, String charset) { public static String encodeUrlSafe(CharSequence source, String charset) {
return encodeUrlSafe(source, CharsetUtil.charset(charset)); return encodeUrlSafe(source, CharsetUtil.charset(charset));
} }
@ -105,10 +112,10 @@ public class Base64 {
* *
* @param source 被编码的base64字符串 * @param source 被编码的base64字符串
* @param charset 字符集 * @param charset 字符集
* @return 加密后的字符串 * @return 编码后的字符串
*/ */
public static String encode(CharSequence source, Charset charset) { public static String encode(CharSequence source, Charset charset) {
return Base64Encoder.encode(source, charset); return encode(StrUtil.bytes(source, charset));
} }
/** /**
@ -120,7 +127,7 @@ public class Base64 {
* @since 3.0.6 * @since 3.0.6
*/ */
public static String encodeUrlSafe(CharSequence source, Charset charset) { public static String encodeUrlSafe(CharSequence source, Charset charset) {
return Base64Encoder.encodeUrlSafe(source, charset); return encodeUrlSafe(StrUtil.bytes(source, charset));
} }
/** /**
@ -130,7 +137,7 @@ public class Base64 {
* @return 被加密后的字符串 * @return 被加密后的字符串
*/ */
public static String encode(byte[] source) { public static String encode(byte[] source) {
return Base64Encoder.encode(source); return java.util.Base64.getEncoder().encodeToString(source);
} }
/** /**
@ -152,7 +159,7 @@ public class Base64 {
* @since 3.0.6 * @since 3.0.6
*/ */
public static String encodeUrlSafe(byte[] source) { public static String encodeUrlSafe(byte[] source) {
return Base64Encoder.encodeUrlSafe(source); return java.util.Base64.getUrlEncoder().encodeToString(source);
} }
/** /**
@ -163,7 +170,7 @@ public class Base64 {
* @since 4.0.9 * @since 4.0.9
*/ */
public static String encode(InputStream in) { public static String encode(InputStream in) {
return Base64Encoder.encode(IoUtil.readBytes(in)); return encode(IoUtil.readBytes(in));
} }
/** /**
@ -174,7 +181,7 @@ public class Base64 {
* @since 4.0.9 * @since 4.0.9
*/ */
public static String encodeUrlSafe(InputStream in) { public static String encodeUrlSafe(InputStream in) {
return Base64Encoder.encodeUrlSafe(IoUtil.readBytes(in)); return encodeUrlSafe(IoUtil.readBytes(in));
} }
/** /**
@ -185,7 +192,7 @@ public class Base64 {
* @since 4.0.9 * @since 4.0.9
*/ */
public static String encode(File file) { public static String encode(File file) {
return Base64Encoder.encode(FileUtil.readBytes(file)); return encode(FileUtil.readBytes(file));
} }
/** /**
@ -196,7 +203,7 @@ public class Base64 {
* @since 4.0.9 * @since 4.0.9
*/ */
public static String encodeUrlSafe(File file) { public static String encodeUrlSafe(File file) {
return Base64Encoder.encodeUrlSafe(FileUtil.readBytes(file)); return encodeUrlSafe(FileUtil.readBytes(file));
} }
/** /**

View File

@ -13,8 +13,8 @@ public interface Decoder<T, R> {
/** /**
* 执行解码 * 执行解码
* *
* @param data 被解码的数据 * @param encoded 被解码的数据
* @return 解码后的数据 * @return 解码后的数据
*/ */
R decode(T data); R decode(T encoded);
} }

View File

@ -13,8 +13,8 @@ public interface Encoder<T, R> {
/** /**
* 执行编码 * 执行编码
* *
* @param encoded 被编码的数据 * @param data 被编码的数据
* @return 编码后的数据 * @return 编码后的数据
*/ */
R encode(T encoded); R encode(T data);
} }

View File

@ -1,5 +1,6 @@
package cn.hutool.core.util; package cn.hutool.core.util;
import cn.hutool.core.codec.Base16Codec;
import cn.hutool.core.exceptions.UtilException; import cn.hutool.core.exceptions.UtilException;
import java.awt.Color; import java.awt.Color;
@ -17,15 +18,6 @@ import java.nio.charset.Charset;
*/ */
public class HexUtil { public class HexUtil {
/**
* 用于建立十六进制字符的输出的小写字符数组
*/
private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* 用于建立十六进制字符的输出的大写字符数组
*/
private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/** /**
* 判断给定字符串是否为16进制数<br> * 判断给定字符串是否为16进制数<br>
* 如果是需要使用对应数字类型对象的{@code decode}方法解码<br> * 如果是需要使用对应数字类型对象的{@code decode}方法解码<br>
@ -80,7 +72,7 @@ public class HexUtil {
* @return 十六进制char[] * @return 十六进制char[]
*/ */
public static char[] encodeHex(byte[] data, boolean toLowerCase) { public static char[] encodeHex(byte[] data, boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); return (toLowerCase ? Base16Codec.CODEC_LOWER : Base16Codec.CODEC_UPPER).encode(data);
} }
/** /**
@ -122,7 +114,7 @@ public class HexUtil {
* @return 十六进制String * @return 十六进制String
*/ */
public static String encodeHexStr(byte[] data, boolean toLowerCase) { public static String encodeHexStr(byte[] data, boolean toLowerCase) {
return encodeHexStr(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER); return new String(encodeHex(data, toLowerCase));
} }
// ---------------------------------------------------------------------------------------------------- decode // ---------------------------------------------------------------------------------------------------- decode
@ -192,31 +184,7 @@ public class HexUtil {
* @since 5.6.6 * @since 5.6.6
*/ */
public static byte[] decodeHex(CharSequence hexData) { public static byte[] decodeHex(CharSequence hexData) {
if (StrUtil.isEmpty(hexData)) { return Base16Codec.CODEC_LOWER.decode(hexData);
return null;
}
hexData = StrUtil.cleanBlank(hexData);
int len = hexData.length();
if ((len & 0x01) != 0) {
hexData = "0" + hexData;
len = hexData.length();
// throw new UtilException("Odd number of characters.");
}
final byte[] out = new byte[len >> 1];
// two characters form the hex value.
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(hexData.charAt(j), j) << 4;
j++;
f = f | toDigit(hexData.charAt(j), j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
} }
// ---------------------------------------------------------------------------------------- Color // ---------------------------------------------------------------------------------------- Color
@ -310,11 +278,7 @@ public class HexUtil {
* @since 4.0.1 * @since 4.0.1
*/ */
public static String toUnicodeHex(char ch) { public static String toUnicodeHex(char ch) {
return "\\u" +// return Base16Codec.CODEC_LOWER.toUnicodeHex(ch);
DIGITS_LOWER[(ch >> 12) & 15] +//
DIGITS_LOWER[(ch >> 8) & 15] +//
DIGITS_LOWER[(ch >> 4) & 15] +//
DIGITS_LOWER[(ch) & 15];
} }
/** /**
@ -370,12 +334,7 @@ public class HexUtil {
* @since 4.4.1 * @since 4.4.1
*/ */
public static void appendHex(StringBuilder builder, byte b, boolean toLowerCase) { public static void appendHex(StringBuilder builder, byte b, boolean toLowerCase) {
final char[] toDigits = toLowerCase ? DIGITS_LOWER : DIGITS_UPPER; (toLowerCase ? Base16Codec.CODEC_LOWER : Base16Codec.CODEC_UPPER).appendHex(builder, b);
int high = (b & 0xf0) >>> 4;//高位
int low = b & 0x0f;//低位
builder.append(toDigits[high]);
builder.append(toDigits[low]);
} }
/** /**
@ -411,51 +370,4 @@ public class HexUtil {
return builder.toString(); return builder.toString();
} }
// ---------------------------------------------------------------------------------------- Private method start
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @param toDigits 用于控制输出的char[]
* @return 十六进制String
*/
private static String encodeHexStr(byte[] data, char[] toDigits) {
return new String(encodeHex(data, toDigits));
}
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @param toDigits 用于控制输出的char[]
* @return 十六进制char[]
*/
private static char[] encodeHex(byte[] data, char[] toDigits) {
final int len = data.length;
final char[] out = new char[len << 1];//len*2
// two characters from the hex value.
for (int i = 0, j = 0; i < len; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];// 高位
out[j++] = toDigits[0x0F & data[i]];// 低位
}
return out;
}
/**
* 将十六进制字符转换成一个整数
*
* @param ch 十六进制char
* @param index 十六进制字符在字符数组中的位置
* @return 一个整数
* @throws UtilException 当ch不是一个合法的十六进制字符时抛出运行时异常
*/
private static int toDigit(char ch, int index) {
int digit = Character.digit(ch, 16);
if (digit < 0) {
throw new UtilException("Illegal hexadecimal character {} at index {}", ch, index);
}
return digit;
}
// ---------------------------------------------------------------------------------------- Private method end
} }