Reputation: 105067
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:
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
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
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