I am trying to adapt this DES encryption example for AES, so I made changes and try to run this:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class AesEncrypter {
private Cipher ecipher;
private Cipher dcipher;
private byte[] buf = new byte[1024];
public AesEncrypter(SecretKey key) throws Exception {
byte[] iv = new byte[] { (byte) 0x8E, 0x12, 0x39, (byte) 0x9C, 0x07, 0x72, 0x6F, 0x5A };
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
ecipher = Cipher.getInstance("AES/CBC/NoPadding");
dcipher = Cipher.getInstance("AES/CBC/NoPadding");
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
}
public void encrypt(InputStream in, OutputStream out) throws Exception {
out = new CipherOutputStream(out, ecipher);
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
out.close();
}
public void decrypt(InputStream in, OutputStream out) throws Exception {
in = new CipherInputStream(in, dcipher);
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
out.close();
}
public static void main(String[] args) throws Exception {
System.out.println("Starting...");
SecretKey key = KeyGenerator.getInstance("AES").generateKey();
InputStream in = new FileInputStream(new File("/home/wellington/Livros/O Alienista/speechgen0001.mp3/"));
OutputStream out = System.out;
AesEncrypter encrypter = new AesEncrypter(key);
encrypter.encrypt(in, out);
System.out.println("Done!");
}
}
but I got an exception:
InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long
So, I tried to solve by changing
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
for
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv, 0, 16);
but the result
IV buffer too short for given offset/length combination
I can just try until this works, but I would like to know who works with AES, what is the commonly used buffer size?