字节流表示的16进制字符串加密
有这样一串字符串
“9C99BCA60B00C266A0B90BC837CF77ABCF3FAECC3BB46F1E43465FEDA9EF0486”
这实际上是字节流表示的16进制,所以需要先把如\x9c解码成10进制再转换成byte
下面展示 16进制解码成二进制流
逻辑。
/**
* 将十六进制字符串表示的字节数据还原成字节数组
*
* @param text 被还原的字符串
* @return 还原之后的字节数组
*/
public static byte[] fromHexString(String text) {
if (text == null)
return new byte[0];
byte[] result = new byte[text.length() / 2];
text = text.toLowerCase();
for (int i = 0; i < text.length(); i += 2) {
char ch = text.charAt(i);
char cl = text.charAt(i + 1);
int high, low;
if ('0' <= ch && ch <= '9') {
high = ch - '0';
} else {
high = ch - 'a' + 10;
}
if ('0' <= cl && cl <= '9') {
low = cl - '0';
} else {
low = cl - 'a' + 10;
}
result[i / 2] = (byte) ((high << 4) | low);
}
return result;
}
完整的测试代码如下
package com.thghh;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Hello world!
*/
public class App {
public static void main(String[] args) {
String hexString = "9C99BCA60B00C266A0B90BC837CF77ABCF3FAECC3BB46F1E43465FEDA9EF0486";
System.out.println(getSHA256(hexString));
}
/**
* 将十六进制字符串表示的字节数据还原成字节数组
*
* @param text 被还原的字符串
* @return 还原之后的字节数组
*/
public static byte[] fromHexString(String text) {
if (text == null)
return new byte[0];
byte[] result = new byte[text.length() / 2];
text = text.toLowerCase();
for (int i = 0; i < text.length(); i += 2) {
char ch = text.charAt(i);
char cl = text.charAt(i + 1);
int high, low;
if ('0' <= ch && ch <= '9') {
high = ch - '0';
} else {
high = ch - 'a' + 10;
}
if ('0' <= cl && cl <= '9') {
low = cl - '0';
} else {
low = cl - 'a' + 10;
}
result[i / 2] = (byte) ((high << 4) | low);
}
return result;
}
/**
* 利用java原生的类实现SHA256加密
*
* @param hexText 十六进制字符串表示的字节数据
* @return
*/
public static String getSHA256(String hexText) {
MessageDigest messageDigest;
String encodestr = "";
try {
messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(fromHexString(hexText));
encodestr = byte2Hex(messageDigest.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}/* catch (UnsupportedEncodingException e) {
e.printStackTrace();
}*/
return encodestr;
}
/**
* 将byte转为16进制
*
* @param bytes
* @return
*/
private static String byte2Hex(byte[] bytes) {
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
for (int i = 0; i < bytes.length; i++) {
temp = Integer.toHexString(bytes[i] & 0xFF);
if (temp.length() == 1) {
//1得到一位的进行补0操作
stringBuffer.append("0");
}
stringBuffer.append(temp);
}
return stringBuffer.toString();
}
}