Java 复制字节数组
我正在试验AES加密。但是,我从以下代码中得到一个错误:Java 复制字节数组,java,arrays,cryptography,copy,byte,Java,Arrays,Cryptography,Copy,Byte,我正在试验AES加密。但是,我从以下代码中得到一个错误: private static byte[] readKey(String request) throws KeyFileNotFoundException, UnsupportedEncodingException, UnknownKeyException { File keyFile = new File(Logging.getCurrentDir() + "\\cikey.key"); Properties key
private static byte[] readKey(String request) throws KeyFileNotFoundException,
UnsupportedEncodingException, UnknownKeyException {
File keyFile = new File(Logging.getCurrentDir() + "\\cikey.key");
Properties keys = new Properties();
byte[] storage;
if (!keyFile.exists())
throw new KeyFileNotFoundException("Key file not located.");
if (keys.containsKey(request) == false)
throw new UnknownKeyException("Key not found."); //I RECIEVE THIS ERROR
storage = keys.getProperty(request).getBytes(); //read the STRING value and turn into a byte array
return storage;
}
这是调用readKey()
的方法中的代码。将通过readKey()
方法读入的字节数组复制到decrypt()
方法时,我也遇到了问题。请阅读方法中的注释以了解更详细的说明
public static String decrypt(String in) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException, IOException,
KeyFileNotFoundException, UnknownKeyException {
String out = " "; //decrypted String to return
byte[] key = readKey("key").clone(); //my attempt to copy a byte array
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
byte iv[] = readKey("iv"); //works here? same as above so I don't know.
IvParameterSpec ivspec = new IvParameterSpec(iv);
//initialize the cipher for decryption
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
// decrypt the message
byte[] decrypted = cipher.doFinal(in.getBytes());
out = asHex(decrypted);
return out;
}
有没有解决此问题的方法?您需要使用来复制阵列
编辑
另一个选项是使用,尽管它只是在引擎盖下使用
System.arrayCopy()
。您没有使用文件中的值初始化属性,因此键是空的,当您调用键时。包含(“”)返回false您已经写入
InputStream=新文件InputStream(keyFile);
键。加载(流)
属性键之后=新属性();
在readKey()方法中,您将得到
如果要尝试查找
有效键。在检查键之前,必须使用其中一种方法加载
键
变量
此外,您还可以使用clone方法或克隆阵列,只需添加[API](,int,java.lang.Object,int,int))@SrinathGanesh感谢javadoc链接。事实上,我的原始答案中包含了这一点,但我想当链接与格式化为代码的文本绑定时,它们不会很好地显示出来。我上面的链接也被弄乱了。链接中的“(”会杀死链接您似乎没有将keyFile的内容读取到Properties对象中。克隆()是复制数组的一种非常有效的方法。但是,我不明白在这种情况下为什么需要复制数组。另外,将密钥用作IV可能会很危险。我不敢相信我没有注意到我没有加载它。