java - Rijndael AES、addRoundKey、异或十六进制字符串并将它们存储为字节

标签 java byte aes rijndael

/*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 步骤从我尝试加密的每个 key 和文本中获取一列,然后对它们进行异或,对吧?

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

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

最佳答案

换行

keyArray[row][col] = Byte.valueOf(result, 16);

keyArray[row][col] = (byte) Integer.valueOf(result, 16).intValue();

编辑
甚至更短,正如 Bohemian 的答案中正确所述:

keyArray[row][col] = (byte) Integer.parseInt(result, 16);

关于java - Rijndael AES、addRoundKey、异或十六进制字符串并将它们存储为字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19734678/

相关文章:

java - 了解 Java 无符号数

c# - 将 byte[] 复制到另一个 byte[] 时出现问题

java - 将字节数组值以小端顺序转换为短值

java - 数组中的所有其他值都打印为 Null

java - 子类错误: CloneNotSupportedException never being thrown in the try body

java - AES加密j2me

Java 密码 NoSuchPaddingException

java - 尝试使用 AES 加密和解密字符串时出现 IllegalBlockSizeException

java - 将数组传递给可变参数方法

java - 通过JACOB获取java中VBScript(WMI)方法设置的输出参数值