/*keyArray contains a line of cipherkey, and inputArray contains a text that is being encrypted.*/
public static void addRoundKey() {
String keyEle = "";
String inputEle = "";
String result = "";
for(int col=0; col<4; col++) {
for(int row = 0; row<4; row++) {
keyEle = Integer.toHexString(keyArray[row][col] & 0xff);
inputEle = Integer.toHexString(inputArray[row][col] & 0xff);
if(keyEle.equals("0")) {
keyEle = "00";
}
if(inputEle.equals("0")) {
inputEle = "00";
}
BigInteger keyNum = new BigInteger(keyEle,16);
BigInteger inputNum = new BigInteger(inputEle, 16);
result = keyNum.xor(inputNum).toString();
System.out.println("result = " + result);
keyArray[row][col] = Byte.valueOf(result, 16);
//The above line causes Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"99" Radix:16`
//keyArray[row][col] = (byte) (Integer.parseInt(result) & 0xff);
}
}
}
我认为addRoundKey步骤从我尝试加密的每个密钥和文本中取一列,然后xor它们,对吗?
所以,这是我的实现,我理解为什么会出现“超出范围”错误,这是因为byte的数字范围是-128到127,对吗?
但我不太确定如何解决它。我无法更改keyArray的类型,即Byte。
答案 0 :(得分:1)
更改行
keyArray[row][col] = Byte.valueOf(result, 16);
到
keyArray[row][col] = (byte) Integer.valueOf(result, 16).intValue();
修改
甚至更短,正如波西米亚的回答中所说:
keyArray[row][col] = (byte) Integer.parseInt(result, 16);
答案 1 :(得分:1)
使用基数16解析“99”作为byte
时出错,可能会被解释为:
byte b = Byte.valueOf("99", 16);
因为byte
已签名,有效范围为-128到127,但您
首先使用Integer.parseInt()将其解析为Integer,然后将其转换为带符号的字节,例如:
keyArray[row][col] = (byte)Integer.parseInt(result, 16);