0
/*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 步骤从我要加密的每个密码密钥和文本中提取一列,然后对它们进行异或,对吗?

所以,这就是我的实现,我明白为什么会出现“值超出范围”错误,这是因为 byte 采用范围从 -128 到 127 的数字,对吗?

但我不太确定如何解决它。我无法更改 keyArray 的类型,即 Byte。

4

2 回答 2

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);
于 2013-11-01T20:54:36.717 回答
1

将“99”解析为byte使用基数 16 时出现错误,可以解释为:

byte b = Byte.valueOf("99", 16);

因为byte是有符号的,有效范围是-128到127,但你是

首先使用 Integer.parseInt() 将其解析为 Integer,然后将其转换为有符号字节,例如:

keyArray[row][col] = (byte)Integer.parseInt(result, 16);
于 2013-11-02T04:52:44.233 回答