Question

I'm doing this project for a client and the part i'm currently stuck on involves taking a XML String and encrypting it - this doesn't need to be state of the art, it just needs to encrypt it and decrypt it using a password.

So far the user enters a password which i've hashed using SHA-256, I then try and encrypt it by doing this:

public static String encryptString(String password, String source, String fileName, String fileDir) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, FileNotFoundException, IOException {
    FileOutputStream fos = null;
    CipherInputStream cis;

    byte key[] = password.getBytes();
    SecretKeySpec secretKey = new SecretKeySpec(key, "DES");

    Cipher encrypt = Cipher.getInstance("DES/ECB/PKCS5Padding");
    encrypt.init(Cipher.ENCRYPT_MODE, secretKey);

    InputStream fileInputStream = new ByteArrayInputStream(source.getBytes());//Here I am getting file data as byte array. You can convert your file data to InputStream  by other way too.

    File dataFile = new File(fileDir, fileName); //dataDir is location where my file is stored
    if (!dataFile.exists()) {
        cis = new CipherInputStream(fileInputStream, encrypt);
        try {
            fos = new FileOutputStream(dataFile);
            byte[] b = new byte[32];
            int i;
            while ((i = cis.read(b)) != -1) {
                fos.write(b, 0, i);
            }
            return fileName;
        } finally {
            try {
                if (fos != null) {
                    fos.flush();
                    fos.close();
                }
                cis.close();
                fileInputStream.close();
            } catch (IOException e) {
                //IOException
            }
        }
    }
    return "";
}

The password being passed in is the hashed password - from here I try and run it but I get a:

java.security.InvalidKeyException: Invalid key length: 64 bytes exception.

Can someone help please?

Or tell me of a better way to encrypt an XML file with a password?

Thanks

Was it helpful?

Solution

From the docs.

If this cipher requires any algorithm parameters that cannot be derived from the given key, the underlying cipher implementation is supposed to generate the required parameters itself (using provider-specific default or random values) if it is being initialized for encryption or key wrapping, and raise an InvalidKeyException if it is being initialized for decryption or key unwrapping. The generated parameters can be retrieved using getParameters or getIV (if the parameter is an IV).

A very simple way of encrypting is taking your hash and XOR it with the bytes in the file in a loop (256 bits at a time). It's kind of a low-level approach but you won't need to debug the API. You should be able to implement this with very minimal code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top