devoured elysium
devoured elysium

Reputation: 105067

Using CipherOutputStream + AES to write a string to a file

I'm looking for a way to, given a password of any size, encrypt a file I'm receiving over a stream with AES. To make things easier to start with, I was trying to just write some encrypted message to a file. But I'm having trouble:

  1. I'd like to be able to define a password of any size. Is it possible to accomplish it in a "standard" form or will I have to pad the passwords to 2^k sizes? I'm currently circumventing the problem providing a temporary "aaaaaaaaaaaaaaaa" password, but I'd like to get rid of it as soon as possible.
  2. If I try to write a long string to cos, something encrypted will be written to the file. But if I try something smaller, as "abc", nothing will be written. I've played with several padding options but they seem of no avail (PKCS5Padding, SSL3Padding, NoPadding).

Here is the code I'm using:

    SecretKeySpec localSecretKeySpec = new SecretKeySpec("aaaaaaaaaaaaaaaa".getBytes(), "AES");
    Cipher localCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    localCipher.init(Cipher.ENCRYPT_MODE, localSecretKeySpec);

    CipherOutputStream cos = new CipherOutputStream(new FileOutputStream("abc"), localCipher);
    IOUtils.write("abc", cos);
    cos.flush();

Upvotes: 0

Views: 4292

Answers (2)

David R Tribble
David R Tribble

Reputation: 12204

You could use a cryptographic hash (e.g., SHA-1) to convert any string into a fixed-length binary value.

That's what I did in a simple file encrypter I wrote some time ago. See the deriveKey() methods in: http://david.tribble.com/src/java/tribble/crypto/FileEncrypter.java

Upvotes: 2

vhallac
vhallac

Reputation: 13907

This answer shows how to use a SecretKeyFactory to generate a key based on arbitrary length passwords.

As for your second problem, cos.flush() is not enough to pad and encrypt the last block. You need to call cos.close() for that. Here is the documentation for the close() method which states this fact.

Upvotes: 4

Related Questions