Aaron
Aaron

Reputation: 1016

Copying Byte Array

I'm experimenting with AES encryption. However, I get an error I wrote from the following code:

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;
}

This is the code from the method calling readKey(). I also am having problems copying the byte array read in through the readKey() method to the decrypt() method. Please read the comments in the methods for more detailed explanations.

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;
}

Any ideas to fixing this problem?

Upvotes: 0

Views: 10908

Answers (3)

dinox0r
dinox0r

Reputation: 16039

You have to load the keys variable using one of Properties.load methods before checking for a key.

Additionally you can clone the array using System.arraycopy, the clone method or Arrays.copyOfRange

Upvotes: 2

nilamber
nilamber

Reputation: 371

You are not initialize Property with values in the file so keys is empty and when you are calling keys.contains("") its returning false you have write InputStream stream=new FileInputStream(keyFile); keys.load(stream);

after property keys=new Property(); in readKey() method then you will get a byte array if you will try to find a valid key.

Upvotes: 2

Jason Braucht
Jason Braucht

Reputation: 2368

You need to use System.arrayCopy() to copy arrays.

EDIT

Another option is to use Arrays.copyOf() although that just uses System.arrayCopy() under the hood.

Upvotes: 3

Related Questions