tags:

views:

91

answers:

3

this code is showing ArrayIndexOutOfBoundsException: at the line char[] password = args[0].toCharArray(); . what to do ?

package org.temp2.cod1;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.KeySpec;

import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;

public class Code2 {

public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeySpecException, InvalidParameterSpecException {

    char[] password = args[0].toCharArray();
    byte[] salt = new byte[8];
    for (int i = 0; i < 8; ++i) {
      salt[i] = (byte) Integer.parseInt(args[1].substring(i * 2, i * 2 + 2), 16);
    }


    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(password, salt, 1024, 256);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes("UTF-8"));


    }
}
+3  A: 

Check if you really pass 2 arguments to the main method or use args[0] to access the first one. And check, if the second parameter has am minimum length of 16 chars.

Andreas_D
He is using `args[0]`. +1 on checking the number of arguments, though
ChssPly76
Later he uses args[1], too ...
tanascius
+1  A: 

Since you asked what to do; Check the stacktrace and see which line is throwing that exception. And check if you are providing enough arguments

erdogany
A: 

This code throws the same exception as long as you call it with no args...

public class Code2 {
  public static void main(String[] args) {
    string firstArgument = args[0];
  }
}

args is an array of strings and contains the arguments passed to your program. With args[0] you try to acces the first argument but there is not such first argument...

pgras