import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import sun.misc.BASE64Decoder;
public class ByteUtil {
public static final String nLine = "----------------------------------------------------------------------------";
/**
*
* @param iSource
* @param iArrayLen
* @return
*/
public static byte[] Int2ByteArray(int iSource, int iArrayLen) {
byte[] bLocalArr = new byte[iArrayLen];
for (int i = iArrayLen; (i < 4) && (i > 0); i--) {
bLocalArr[i - 1] = (byte) (iSource >> 8 * (iArrayLen - i) & 0xFF);
}
return bLocalArr;
}
public static String trace(byte[] inBytes) {
int i, j = 0;
byte[] temp = new byte[76];
bytesSet(temp, ' ');
StringBuffer strc = new StringBuffer("");
strc.append(nLine + "\n");
for (i = 0; i < inBytes.length; i++) {
if (j == 0) {
System.arraycopy(String.format("%03d: ", i).getBytes(), 0,
temp, 0, 5);
System.arraycopy(String.format(":%03d", i + 15).getBytes(), 0,
temp, 72, 4);
}
System.arraycopy(String.format("%02X ", inBytes[i]).getBytes(), 0,
temp, j * 3 + 5 + (j > 7 ? 1 : 0), 3);
if (inBytes[i] == 0x00) {
temp[j + 55 + ((j > 7 ? 1 : 0))] = '.';
} else {
temp[j + 55 + ((j > 7 ? 1 : 0))] = inBytes[i];
}
j++;
if (j == 16) {
strc.append(new String(temp)).append("\n");
bytesSet(temp, ' ');
j = 0;
}
}
if (j != 0) {
strc.append(new String(temp)).append("\n");
bytesSet(temp, ' ');
}
strc.append(nLine + "\n");
// System.out.println(strc.toString());
return strc.toString();
}
private static void bytesSet(byte[] inBytes, char fill) {
if (inBytes.length == 0) {
return;
}
for (int i = 0; i < inBytes.length; i++) {
inBytes[i] = (byte) fill;
}
}
public static byte[] byteAndByte(byte[] begin, byte[] second) {
if (begin == null || begin.length == 0) {
if (second != null && second.length != 0) {
return second;
} else {
return null;
}
} else if (second == null || second.length == 0) {
return begin;
}
byte[] newTotal = new byte[begin.length + second.length];
for (int i = 0; i < begin.length; i++) {
newTotal[i] = begin[i];
}
for (int i = begin.length; i < second.length + begin.length; i++) {
newTotal[i] = second[i - begin.length];
}
return newTotal;
}
public static byte[] getsubByte(byte[] total, int begin, int length) {
if (length > 0) {
byte[] newTotal = new byte[length];
for (int i = begin; i < length + begin; i++) {
newTotal[i - begin] = total[i];
}
return newTotal;
}
return null;
}
/**
* 填充字符串
*
* @param string
* 填充前的字符串
* @param filler
* 需要填充的字符
* @param totalLength
* 填充后的总长度
* @param atEnd
* true为在原字符串的右边添加,false为在原字符串的昨天添加
* @return String
*/
public static String fillString(String string, char filler,
int totalLength, boolean atEnd) {
byte[] tempbyte = string.getBytes();
int currentLength = tempbyte.length;
int delta = totalLength - currentLength;
for (int i = 0; i < delta; i++) {
if (atEnd) {
string += filler;
} else {
string = filler + string;
}
}
return string;
}
/**
* Convert hex string to byte[]
*
* @param hexString
* the hex string
* @return byte[]s
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* Convert char to byte
*
* @param c
* char
* @return byte
*/
public static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* 将byte[]转换成16进制字符串
*
* @param src
* @return
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 字符串转换成16进制表示 610EF02F=610EF02F
*
* @param s
* @return
*/
public static String toHexString(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;// 0x表示十六进制
}
/**
* 将指定byte数组以16进制的形式打印到控制台 有空格
*
* @param hint
* String
* @param b
* byte[]
* @return void
*/
public static String printHexString1(byte[] b) {
StringBuffer returnValue = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
returnValue.append(hex.toUpperCase() + " ");
}
return "[" + returnValue.toString() + "]";
}
/**
* 把字节数组转换成16进制字符串 无空格
*/
public static final String bytesToHexString2(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
/**
* 将指定字符串src,以每两个字符分割转换为16进制形式 如:"2B44EFD9" --> byte[]{0x2B, 0x44, 0xEF,
* 0xD9}
*
* @param src
* String
* @return byte[]
*/
public static byte[] HexString2Bytes(String src) {
byte[] ret = new byte[8];
byte[] tmp = src.getBytes();
for (int i = 0; i < 8; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
/*
* 把16进制字符串转换成字节数组 * @param hex * @return
*/
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}
/**
* 16进制压缩
*
* @param value
* @param buf
*/
public static void to16Bcd(String value, byte[] buf) {
int charpos = 0; // char where we start
int bufpos = 0;
if (value.length() % 2 == 1) {
// for odd lengths we encode just the first digit in the first byte
buf[0] = (byte) (value.charAt(0) - 48);
charpos = 1;
bufpos = 1;
}
// encode the rest of the string
while (charpos < value.length()) {
buf[bufpos] = (byte) (((value.charAt(charpos) - 48) << 4) | (value
.charAt(charpos + 1) - 48));
charpos += 2;
bufpos++;
}
}
/**
* 返还byte的10进制串
*
* @param src
* @param begin
* @param length
* @return
*/
public static String bytesToString(byte[] src, int begin, int length) {
String str1 = null;
StringBuilder sb = new StringBuilder("");
if (begin == 0 && length == 0) {
for (byte element : src) {
sb.append(" ");
sb.append(String.valueOf(element));
}
} else {
for (int i = begin; i < begin + length; i++) {
byte element = src[i];
sb.append(" ");
sb.append(String.valueOf(element));
}
}
str1 = sb.toString();
return str1;
}
/**
*
* @param b
* byte[]
* @return String
*/
public static String Bytes2HexString(byte[] b) {
String ret = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
return ret;
}
/**
* 将两个ASCII字符合成一个字节; 如:"EF"--> 0xEF
*
* @param src0
* byte
* @param src1
* byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
.byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
.byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
/**
* 将byte[]转为各种进制的字符串
*
* @param bytes
* byte[]
* @param radix
* 基数可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,
* 超出范围后变为10进制
* @return 转换后的字符串
*/
public static String binary(byte[] bytes, int radix) {
return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
}
/*
* 把byte转化成2进制字符串
*
* @param b
*
* @return
*/
public static String getBinaryStrFromByte(byte b) {
String result = "";
byte a = b;
;
for (int i = 0; i < 8; i++) {
byte c = a;
a = (byte) (a >> 1);// 每移一位如同将10进制数除以2并去掉余数。
a = (byte) (a << 1);
if (a == c) {
result = "0" + result;
} else {
result = "1" + result;
}
a = (byte) (a >> 1);
}
return result;
}
/**
* 把byte转化成2进制字符串
*
* @param b
* @return
*/
public static String getBinaryStrFromByte2(byte b) {
String result = "";
byte a = b;
;
for (int i = 0; i < 8; i++) {
result = (a % 2) + result;
a = (byte) (a >> 1);
}
return result;
}
/**
* 把byte转化成2进制字符串
*
* @param b
* @return
*/
public static String getBinaryStrFromByte3(byte b) {
String result = "";
byte a = b;
;
for (int i = 0; i < 8; i++) {
result = (a % 2) + result;
a = (byte) (a / 2);
}
return result;
}
/**
* 把byte数组转化成2进制字符串
*
* @param bArr
* @return
*/
public static String getBinaryStrFromByteArr(byte[] bArr) {
String result = "";
for (byte b : bArr) {
result += getBinaryStrFromByte(b);
}
return result;
}
/**
* 转换日期到相应的格式 Formats a Date if the receiver is DATE10, DATE4, DATE_EXP or
* TIME; throws an exception otherwise.
*/
public static String date2Str(Date value, String bzType) {
if ("date14".equals(bzType)) {
return new SimpleDateFormat("YYYYMMddHHmmss").format(value);
} else if ("date10".equals(bzType)) {
return new SimpleDateFormat("MMddHHmmss").format(value);
} else if ("date8".equals(bzType)) {
return new SimpleDateFormat("MMddHHmmss").format(value);
} else if ("date4".equals(bzType)) {
return new SimpleDateFormat("MMdd").format(value);
} else if ("dateexp".equals(bzType)) {
return new SimpleDateFormat("yyMM").format(value);
} else if ("time".equals(bzType)) {
return new SimpleDateFormat("HHmmss").format(value);
}
throw new IllegalArgumentException("Cannot format date as ");
}
/**
* 10进制串转为BCD码
*
* @param asc
* @return
*/
public static byte[] lengthToBcd(String asc) {
int len = asc.length();
int mod = len % 2;
if (mod != 0) {
asc = "0" + asc;
len = asc.length();
}
byte abt[] = new byte[len];
if (len >= 2) {
len = len / 2;
}
byte bbt[] = new byte[len];
abt = asc.getBytes();
int j, k;
for (int p = 0; p < asc.length() / 2; p++) {
if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
j = abt[2 * p] - '0';
} else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
j = abt[2 * p] - 'a' + 0x0a;
} else {
j = abt[2 * p] - 'A' + 0x0a;
}
if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
k = abt[2 * p + 1] - '0';
} else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
k = abt[2 * p + 1] - 'a' + 0x0a;
} else {
k = abt[2 * p + 1] - 'A' + 0x0a;
}
int a = (j << 4) + k;
byte b = (byte) a;
bbt[p] = b;
}
return bbt;
}
public static String bcdToStr(byte[] bytes) {
char temp[] = new char[bytes.length * 2], val;
for (int i = 0; i < bytes.length; i++) {
val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
val = (char) (bytes[i] & 0x0f);
temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
}
return new String(temp);
}
/**
* Encode the value as BCD and put it in the buffer. The buffer must be big
* enough to store the digits in the original value (half the length of the
* string).
*/
public static void toBcd(String value, byte[] buf) {
int charpos = 0; // char where we start
int bufpos = 0;
if (value.length() % 2 == 1) {
// for odd lengths we encode just the first digit in the first byte
buf[0] = (byte) (value.charAt(0) - 48);
charpos = 1;
bufpos = 1;
}
// encode the rest of the string
while (charpos < value.length()) {
buf[bufpos] = (byte) (((value.charAt(charpos) - 48) << 4) | (value
.charAt(charpos + 1) - 48));
charpos += 2;
bufpos++;
}
}
public static void rightBcd(String value, byte[] buf) {
Double strLength = new Double(value.length());
int byteLength = (int) Math.ceil(strLength / new Double(2));
byte[] fullDate = new byte[buf.length - byteLength];
for (int i = 0; i < fullDate.length; i++) {
fullDate[i] = 0;
}
byte[] data = new byte[byteLength];
toBcd(value, data);
System.arraycopy(fullDate, 0, buf, 0, fullDate.length);
System.arraycopy(data, 0, buf, fullDate.length, data.length);
}
public static String amount2Str(BigDecimal value) {
String v = new DecimalFormat("0000000000.00").format(value);
return v.substring(0, 10) + v.substring(11);
}
public static BigDecimal str2Amount(String v) {
String ams=v.substring(0, 10) + "."+v.substring(10,12);
BigDecimal amount=new BigDecimal(ams);
return amount;
}
/**
* 将明文密码安装腾付通要求的方式进行处理 例如:明文PIN为: 123456, 假设: 磁卡上的PAN:1234 5678 9012 3456 78
* 截取下的PAN:6789 0123 4567 则用于PIN加密的PAN为:0x00 0x00 0x67 0x89 0x01 0x23 0x45
* 0x67 PIN BLOCK为: 0x06 0x12 0x34 0x56 0xFF 0xFF 0xFF 0xFF 异或: 0x00 0x00
* 0x67 0x89 0x01 0x23 0x45 0x67 结果为: 0x06 0x12 0x53 0xDF 0xFE 0xDC 0xBA
* 0x98
*
* @param pin
* @param pan
* @return
*/
public static byte[] pinHandler(String pin, String pan) {
byte[] result = new byte[8];
int length = pin.length();
byte[] pinb = new byte[8];
pinb[0] = (byte) length;
Double strLength = new Double(pin.length());
int byteLength = (int) Math.ceil(strLength / new Double(2));
byte[] bcd = new byte[byteLength];
toBcd(pin, bcd);
System.arraycopy(bcd, 0, pinb, 1, byteLength);
for (int i = 8 - 1 - byteLength; i < 8; i++) {
pinb[i] = (byte) 0xff;
}
System.out.println(printHexString1(pinb));
// pan转bcd
byte[] panbcd = lengthToBcd(pan);
byte[] panbyte = new byte[8];
for (int i = 0; i < 8 - panbcd.length; i++) {
panbyte[i] = (byte) 0x00;
}
System.arraycopy(panbcd, 0, panbyte, 8 - panbcd.length, panbcd.length);
System.out.println(printHexString1(panbyte));
// 安位亦或
for (int i = 0; i < 8; i++) {
result[i] = (byte) (panbyte[i] ^ pinb[i]);
}
return result;
}
// 将 s 进行 BASE64 编码
public static String getBASE64(String s) {
if (s == null)
return null;
return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
}
// 将 BASE64 编码的字符串 s 进行解码
public static String getFromBASE64(String s) {
if (s == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(s);
return new String(b);
} catch (Exception e) {
return null;
}
}
public static void main(String args[]) {
// String ss=getFromBASE64("MjAxNDEyMDkxNDQzMDV8MTQwMDAwMDAwMXw2MjI2MDk2NTg3OTQ1NnzpmYjlsI/mmI58MjUwLjAwfGNvbGxlY3R8Q05ZfA==MjAxNDEyMDkxNDQzMDV8MTQwMDAwMDAwMXw2MjI2MDk2NTg3OTQ1NnzpmYjlsI/mmI58MjUwLjAwfGNvbGxlY3R8Q05ZfA==MjAxNDEyMDkxNDQzMDV8MTQwMDAwMDAwMXw2MjI2MDk2NTg3OTQ1NnzpmYjlsI/mmI58MjUwLjAwfGNvbGxlY3R8Q05ZfA==");
// System.out.println(ss);
System.out.println(ByteUtil.bytesToHexString(ByteUtil.pinHandler("123456", "024044703551")));
/*String ss=getBASE64("D59B9E79DF2F38BA37A7F42F02164364");
System.out.println(ss);
String sss=getFromBASE64(ss);
System.out.println(sss);
//BigDecimal big=str2Amount("000000000010");
/* BigDecimal bigg=new BigDecimal(1);
BigDecimal big2=bigg.divide(new BigDecimal(100));
System.out.println(new Date().getTime());*/
/*
* byte[] bcd=new byte[6]; toBcd("00002793004",bcd);
* System.out.println(bcd.length);
* System.out.println("RRR"+ByteUtil.printHexString1(bcd));
*/
/*
* byte[] pan={0x67};
*
* byte[] pin={0x34};
* System.out.println(Integer.toHexString(pan[0]^pin[0]));
*/
/*
* System.out.println(Integer.toHexString(60)); Integer.toHexString(60);
* byte[] bcd=new byte[1]; toBcd(Integer.toHexString(60),bcd); byte[]
* bcdm=lengthToBcd(Integer.toHexString(960));
* System.out.println("RRR"+ByteUtil.printHexString1(bcdm));
* System.out.println(ByteUtil.getBinaryStrFromByteArr(bcdm)); byte []
* bcd16= {0x3c};
* System.out.println(Integer.parseInt(bcdToStr(bcd16),16));
*/
/*
* byte[] key=hexStringToByte(
* "417FA5F91AEE8DA05E27E6C49CF4EB75CD322F31D03359F217843D8E4048D0E9EA8D09328420"
* ); System.out.println("key:"+ByteUtil.bytesToHexString2(key));
* System.out.println(toHexString("610EF02F"));
* System.out.println("E2FBC470".getBytes());
*/
// System.out.println(ByteUtil.printHexString1(pinHandler( "120728",
// "609021133777")));
}
}
ByteUtil
最新推荐文章于 2023-04-07 14:33:46 发布