我真的很努力地在Java和节点之间进行十六进制到字节的转换。 Java方法有效。我需要在两种语言之间创建相同的HMAC SHa1哈希。
我使用hexToBytes函数的结果作为生成HmacSHA1哈希的键。 使用转换后的密钥时,哈希值是不同的。
为什么字节值不累加? Java为什么会产生负整数?
Java:
private static byte[] hexToBytes(String hexValue) throws Exception {
String hb = "";
if ((hexValue.length() % 2) != 0) {
throw new Exception("Odd length on HEX " + hexValue + "");
}
byte[] value = new byte[(hexValue.length() / 2)];
try {
for (int i = 0; i < value.length; i++) {
hb = hexValue.substring(2 * i, (2 * i) + 2);
value[i] = (byte) (Integer.parseInt(hb, 16) & 0xff);
System.out.println("Loop: "+i+" HB: "+hb+" => "+value[i]);
}
} catch (NumberFormatException nfe) {
throw new Exception("Invalid HEX <" + hb + "> in string <" + hexValue + ">");
}
System.out.println("FINAL => "+value.toString());
String s = new String(value);
System.out.println("In string : " + s);
System.out.println(value);
String hex = bytesToHex(value);
System.out.println("Back TO HEX: "+hex);
return value;
}
hexToBytes(“ 0123456789ABCDEFFEDCBA9876666666”);
Loop: 0 HB: 01 => 1
Loop: 1 HB: 23 => 35
Loop: 2 HB: 45 => 69
Loop: 3 HB: 67 => 103
Loop: 4 HB: 89 => -119
Loop: 5 HB: AB => -85
Loop: 6 HB: CD => -51
Loop: 7 HB: EF => -17
Loop: 8 HB: FE => -2
Loop: 9 HB: DC => -36
Loop: 10 HB: BA => -70
Loop: 11 HB: 98 => -104
Loop: 12 HB: 76 => 118
Loop: 13 HB: 66 => 102
Loop: 14 HB: 66 => 102
Loop: 15 HB: 66 => 102
FINAL => [B@3214ee6
In string : #Eg?«?ï?ܺ?vfff
[B@3214ee6
Back TO HEX: 0123456789abcdeffedcba9876666666
这是我内置在Node中的简单函数。
async function hexToBytes (hexValue){
var bytes3 = Buffer.alloc(hexValue.length / 2, 'hex');
for (var bytes = new Array(), c = 0; c < bytes3.length; c ++){
var v = hexValue.substr(2*c, 2);
var t = parseInt("0x"+v, 16 & 0xFF);
console.log('Index: '+c+' V: '+v+' => '+t );
bytes[c] = t;
//bytes.push(t);
}
console.log('Back to HEX')
console.log(Buffer(bytes,'hex').toString('hex').toUpperCase());
return Buffer(bytes, 'utf8');
}
Node JS中hexToBytes(“ 0123456789ABCDEFFEDCBA9876666666”)的输出;
Length of SCERET :16
Index: 0 V: 01 => 1
Index: 1 V: 23 => 35
Index: 2 V: 45 => 69
Index: 3 V: 67 => 103
Index: 4 V: 89 => 137
Index: 5 V: AB => 171
Index: 6 V: CD => 205
Index: 7 V: EF => 239
Index: 8 V: FE => 254
Index: 9 V: DC => 220
Index: 10 V: BA => 186
Index: 11 V: 98 => 152
Index: 12 V: 76 => 118
Index: 13 V: 66 => 102
Index: 14 V: 66 => 102
Index: 15 V: 66 => 102
Back to HEX
0123456789ABCDEFFEDCBA9876666666
#Eg�����ܺ�vT2