Java Rijndael AES、addRoundKey、xor十六进制字符串,并将它们存储为字节 /*keyArray包含一行加密密钥,inputArray包含一个正在加密的文本*/ 公共静态void addRoundKey(){ 字符串keyEle=“”; 字符串inputEle=“”; 字符串结果=”; 对于(int col=0;col

Java Rijndael AES、addRoundKey、xor十六进制字符串,并将它们存储为字节 /*keyArray包含一行加密密钥,inputArray包含一个正在加密的文本*/ 公共静态void addRoundKey(){ 字符串keyEle=“”; 字符串inputEle=“”; 字符串结果=”; 对于(int col=0;col,java,byte,aes,rijndael,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

更改行

/*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);           
            }
        }
    }

编辑
甚至更短,正如波希米亚人的回答中正确指出的:

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

使用base 16将“99”解析为
字节时出现错误,可能解释为:

keyArray[row][col] = (byte) Integer.parseInt(result, 16);
因为
byte
是有符号的,有效范围为-128到127,但您是有符号的

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

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

您可以发布它抱怨的确切错误和行吗?它们已经作为注释出现在我的代码中。请检查这行中的注释,“keyArray[row][col]=Byte.valueOf(result,16);”谢谢你的评论。这已编译,但仍然没有给我正确的结果。你知道我的AES“添加圆键”的实现是否有任何问题吗?@Nayana不知道,很抱歉+1在我的回答中提到了
Integer.parseInt
而不是
Integer.valueOf
。但是,
byte b=(byte)(i<128?i:i-256);
相当于
byte b=(byte)i;
BTW,您的原始赋值
keyArray[row][col]=i<128?i:i-256;
如果不转换为字节,则不会compile@kiruwka谢谢你的反馈。我用iPhone输入我所有的代码,所以有时候我会忽略类似的东西。我已经更正了我的答案——现在看起来好多了:)干杯
byte b = Byte.valueOf("99", 16);
keyArray[row][col] = (byte)Integer.parseInt(result, 16);