AES Decryption ERROR: android pad block corrupted - java

I've looked around stack to find an answer to my problem and yet nothing did work.
What im trying to achive is to encrypte XML file that is downloaded in ASYNCtask and later on decrypt it.
What I've already checked:
-Generated key is the same when encrypring and decrypting and saved in sharedpreferenced with Base64.
-IV is the same since at the moment its in static variable for testing purposes.
-Cipher is set to AES/CBC/PKCS5Padding
-Key is set to AES
The error appear in decryptXml() at line:
byte[] decrypted = cipher.doFinal(bytes);
Im all out of ideas and nothing seems to work. I hope some of u can find mistake in my code. Thanks for help!
CODE:
genetateKey()
SharedPreferences sharedPreferences = context.getSharedPreferences(GENERATED_KEY, Context.MODE_PRIVATE);
String keyStr = sharedPreferences.getString(GENERATED_KEY, null);
if (keyStr == null) {
final int outputKeyLength = 128;
SecureRandom secureRandom = new SecureRandom();
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(outputKeyLength, secureRandom);
SecretKey key = keyGenerator.generateKey();
byte[] bytes = key.getEncoded();
keyStr = Base64.encodeToString(bytes, Base64.DEFAULT);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(GENERATED_KEY, keyStr);
editor.commit();
return key.toString();
} else {
return keyStr;
}
XML encryption:
connection = (HttpURLConnection) url.openConnection();
connection.connect();
SecretKey secretKey = getSecretKey(context);
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
spec = generateIv(cipher.getBlockSize());
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, spec);
input = connection.getInputStream();
cis = new CipherInputStream(input, cipher);
String FILEPATH = context.getFilesDir().getParentFile().getPath();
File file = new File(FILEPATH, "/download/" + id + "/");
if (!file.exists()) {
file.mkdirs();
}
xmlFile = new File(FILEPATH + "/download/" + id + "/", "xmldata.xml");
output = new FileOutputStream(xmlFile);
cos = new CipherOutputStream(output, cipher);
byte data[] = new byte[4096];
int count;
while ((count = cis.read(data)) != -1) {
if (isCancelled()) throw new TaskCanceledException();
cos.write(data, 0, count);
progress = -1;
publishProgress();
}
if (isCancelled()) throw new TaskCanceledException();
Decryption:
public String decryptXml() {
String data = null;
File file = new File(context.getFilesDir().getParentFile().getPath() + "/download/" + id + "/xmldata.xml");
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(getSecretKey(context).getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, DownloadBookAsyncTask.spec);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
bis.read(bytes, 0, bytes.length);
bis.close();
byte[] decrypted = cipher.doFinal(bytes);
}
getSecretKey():
public SecretKey getSecretKey(Context context){
SharedPreferences sharedPreferences = context.getSharedPreferences(DashboardFragment.GENERATED_KEY, Context.MODE_PRIVATE);
String stringKey = sharedPreferences.getString(DashboardFragment.GENERATED_KEY, null);
byte[] encodedKey = Base64.decode(stringKey, Base64.DEFAULT);
return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
}
EDIT
Adding IV generator method
public AlgorithmParameterSpec generateIv(int size) throws NoSuchAlgorithmException {
AlgorithmParameterSpec ivspec;
byte[] iv = new byte[size];
new SecureRandom().nextBytes(iv);
ivspec = new IvParameterSpec(iv);
return ivspec;
}

Ok I've found the problem.
The reason my code did not work was that I have used CipherInputStream in my encryption and I shouldn't have done that.
I have also redo whole decryption method which looks like this now:
byte[] wholeFileByte = null;
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, key, DownloadBookAsyncTask.ivspec);
File file = new File(context.getFilesDir().getParentFile().getPath() + "/download/" + id + "/xmldata.xml");
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
CipherInputStream cis = new CipherInputStream(fis, cipher);
byte data[] = new byte[4096];
int count;
while ((count = cis.read(data)) != -1) {
bos.write(data, 0, count);
}
if(cis != null)
cis.close();
if(bos != null)
bos.close();
if(fis != null)
fis.close();
wholeFileByte = bos.toByteArray();
String kk = new String(wholeFileByte, "UTF-8");
I think other mistake that I made was that I used doFinal in the decryption even tho the Cipher did the decryption already and that was source of some of my errors.
Thanks to #GariBN because u put me in right tracks and will upvote you when my rep allow me to :)

You create IV to encrypt the plaintext.
I'm not sure that you use the same IV in order to decrypt the ciphertext.
Usually, you want to concatenate the IV to the ciphertext, and when decrypting, read it (the first 16 bytes), and then decrypt all the other bytes (the ciphertext) with cipher that was initialized with the IV used for the encryption.
For example, if you encrypt with:
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, spec);
First, try to decrypt (right later) with:
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, spec);
cipher.doFinal(bytes)
If you succeed, then the problem is probably because inappropriate IV, and you can fix it easily.

Related

AES+ Base64 Decrypt file appeared garbled

I am using socket to transfer file and AES 256 to encrypt/decrypt, I use the byte array to accept file's content and encrypt it, but only the first byte size array success to decrypt and other appeared garbled(the encrypted byte size extend to 1368 and AES block size is 128bits not sure is it effect),below is my code:
public void sendfile() {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
byte[] byteArray = new byte[1024];
int bytesCount = 0;
while ((bytesCount = fis.read(byteArray)) >= 0) {
String encryptString = new String(byteArray, "UTF-8");
bos.write(EncryptAES.encrypt(encryptString, "12345").getBytes("UTF-8"));
}
}
public void receiveFile(File file, BufferedInputStream bis) {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
byte[] byteArray = new byte[1024];
int bytesCount = 0;
while ((bytesCount = bis.read(byteArray)) >= 0) {
String encryptString = new String(byteArray, "UTF-8");
bos.write(EncryptAES.decrypt(encryptString, "12345").getBytes("UTF-8"));
}
}
public static String encrypt(String content,SecretKey secretKey) {
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] byteContent = cipher.doFinal(content.getBytes("UTF-8"));
return Base64.getEncoder().withoutPadding().encodeToString(byteContent);
}
public static String decrypt(String content,SecretKey secretKey) {
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] byteCipherText = Base64.getDecoder().decode(content);
String encryptString = new String(byteCipherText, "UTF-8");
byte[] decryptedText = cipher.doFinal(byteCipherText);
encryptString = new String(decryptedText, "UTF-8");
return new String(decryptedText, "UTF-8");
}

How to add and get specific number of bytes from a file using file input and output streams?

I am working on a class to encrypt/decrypt large files so I am trying to use the streams instead of byte arrays to avoid OutOfMemory exceptions.
In the encryption method I add random salt and iv to the beginning of the encrypted file and it works fine, and here is the code:
public File encryptFile(File inputFile, File outPutFile, String password, ProgressBar progressBar, Label progressPercentage){
//Create IV
byte[] ivBytes = new byte[16];
SecureRandom random1 = new SecureRandom();
random1.nextBytes(ivBytes);
IvParameterSpec iv = new IvParameterSpec(ivBytes);
//Create the key with the salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[SALT_SIZE];
random.nextBytes(salt);
SecretKeySpec keySpec = generateAesKey(password, salt);
//Create and Init the cipher
Cipher c = Cipher.getInstance("AES/CBC/"+padding);
c.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] buf = new byte[8192];
FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream(outPutFile);
int nread;
int progress = 0;
byte[] ivAndSalt = new byte[ivBytes.length + salt.length];
System.arraycopy(ivBytes,0, ivAndSalt,0, ivBytes.length );
System.arraycopy(salt, 0, ivAndSalt, ivBytes.length, salt.length);
out.write(ivAndSalt);
while((nread = in.read(buf)) != -1) {
byte[] enc = c.update(buf, 0, nread);
out.write(enc);
progress++;
}
Then I try to get the iv and salt in decryption method and then decrypt the rest of the file into an output one with FileInputStream.getChannel.position():
public File decryptFile(File inputFile, File outPutFile, String password, ProgressBar progressBar, Label progressPercentage) {
//Create and Init Cipher
Cipher c = Cipher.getInstance("AES/CBC/" + padding);
FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream(outPutFile);
//Getting the iv and salt
byte[] ivBytes = new byte[16];
byte[] salt = new byte[SALT_SIZE];
byte[] ivAndSalt = new byte[ivBytes.length+SALT_SIZE];
in.read(ivAndSalt, 0, ivBytes.length+SALT_SIZE);
System.arraycopy(ivAndSalt, 0, ivBytes, 0, ivBytes.length);
System.arraycopy(ivAndSalt, ivBytes.length, salt, 0, SALT_SIZE);
IvParameterSpec iv =new IvParameterSpec(ivBytes);
SecretKeySpec keySpec = generateAesKey(password, salt);
c.init(Cipher.DECRYPT_MODE, keySpec, iv);
in.getChannel().position(ivAndSalt.length);
int nread;
int progress = 0;
byte[] buf = new byte[8192];
while((nread = in.read(buf)) != -1) {
byte[] enc = c.update(buf, 0, nread);
out.write(enc);
progress++;
/*if (enc.length / 8192 != 0)
System.out.println((nread*progress) + "%");*/
}
System.out.println("Size of out before doFinal(): " + out.getChannel().size());
byte[] enc = c.doFinal();
out.write(enc);
System.out.println("Size of out after doFinal(): " + out.getChannel().size());
return outPutFile;
}
I didn't get an error on calling decryptFile() but the produced file is corrupted and this means that there is an issue somewhere in the decrypting.
The problem was totally something silly, I forgot to close the input and output streams after doFinal() and writing the enc bytes array to output:
in.close();
out.close();

Symmetric encryption with CBC mode using AES in java

I am trying to encrypt and decrypt data using CBC mode.
Here, I am first reading the data from a plaintext.txt file and writing the output which is the data of the plaintext.txt to another ciphertext.txt file. While trying to decrypt, I am reading the encrypted data from the file into bytes but for some reason, it's giving me an error. Can someone help me solving this?
Here is my encryption function
// The encryption Function CBC MODE
public static byte[] encrypt(String plainText, String key) throws Exception
{
// Loading the secret key from the Key.txt file
String fileName="../data/key.txt";
try
{
BufferedReader in = new BufferedReader(new FileReader(fileName)); // Initialize a Buffer reader
key = in.readLine(); // Reading the data from txt file
}
//error message if the file is not found
catch(FileNotFoundException ex)
{
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex)
{
System.out.println("Error reading file '" + fileName + "'");
}
byte[] clean = plainText.getBytes(); //Getting the data in bytes from the plain text
// Generating IV.
//From the initialization vector, we create an IvParameterSpec which is required when creating the Cipher.
int ivSize = 16;
byte[] iv = new byte[ivSize];
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
//System.out.println("The Iv is = "+ivParameterSpec);
// Hashing key.
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(key.getBytes("UTF-8"));
byte[] keyBytes = new byte[32];
System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
// Encrypt.
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(clean);
// Combine IV and encrypted part.
byte[] encryptedIVAndText = new byte[ivSize + encrypted.length];
System.arraycopy(iv, 0, encryptedIVAndText, 0, ivSize);
System.arraycopy(encrypted, 0, encryptedIVAndText, ivSize, encrypted.length);
try
{
PrintWriter writer = new PrintWriter("../data/ciphertext.txt");
writer.println(encryptedIVAndText);
writer.close();
}
catch(Exception ex)
{
System.out.println(ex);
System.out.println("File is not there");
}
return encryptedIVAndText;
}
And here is my decryption function.
// Decrypting fucntion CBC mode
public static String decrypt(byte[] encryptedIvTextBytes, String key) throws Exception
{
FileInputStream encryptedTextFis = new FileInputStream("../data/ciphertext.txt");
byte[] encText = new byte[encryptedTextFis.available()];
int lol = encryptedTextFis.available();
System.out.println("lol "+ lol);
encryptedTextFis.read(encText);
encryptedTextFis.close();
// encrypted = readFile("../data/ciphertext.txt", StandardCharsets.UTF_8).getBytes();
encryptedIvTextBytes = encText;
//System.out.println("..........??????");
String fileName="../data/key.txt";
String fileName2="../data/ciphertext.txt";
try
{
BufferedReader in = new BufferedReader(new FileReader(fileName));
BufferedReader in2 = new BufferedReader(new FileReader(fileName2));
key = in.readLine();
// byte[] array = Files.readAllBytes(new File("/path/to/file").toPath());
}
//error message if the file is not found
catch(FileNotFoundException ex)
{
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex)
{
System.out.println("Error reading file '" + fileName + "'");
}
int ivSize = 16;
int keySize = 32;
//System.out.println("..........??????");
// Extract IV.
byte[] iv = new byte[ivSize];
System.arraycopy(encryptedIvTextBytes, 0, iv, 0, iv.length);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
System.out.println("..........??????");
// Extract encrypted part.
int encryptedSize = encryptedIvTextBytes.length - ivSize;
byte[] encryptedBytes = new byte[encryptedSize];
System.arraycopy(encryptedIvTextBytes, ivSize, encryptedBytes, 0, encryptedSize);
System.out.println("..........??????");
// Hash key.
byte[] keyBytes = new byte[keySize];
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(key.getBytes());
System.arraycopy(md.digest(), 0, keyBytes, 0, keyBytes.length);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
// Decrypt.
Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); //Decrypting the encrypted data to a cipherblock data
byte[] decrypted = cipherDecrypt.doFinal(encryptedBytes); // Decrypting the cipher dadat to Plaintext
//Writing the output to a txt file
try
{
PrintWriter writer = new PrintWriter("../data/result.txt");
writer.println(new String(decrypted));
writer.close();
}
catch(Exception ex)
{
System.out.println(ex);
System.out.println("File is not there");
}
return new String(decrypted); //Returning the decrypted data to main function
}
The output of the encrypted text file is of the form [B#3159c4b8.
I am getting the below error.
It seems exception is here:
System.arraycopy(encryptedIvTextBytes, 0, iv, 0, iv.length);
The length of array encryptedIvTextBytes is 11 (as you say and the result is shown also). Now you want to copy 16 (as the length of iv) bytes from encryptedIvTextBytes.
But the main reason is from this note that your saving method to save encrypted data is not valid. Encrypted data may contain some bytes which are not a readable character. When you save encrypted data as a string such bytes are dropped. To solve this problem see #Maarten and #MS90 comments.
Here is a code that suits your needs:
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
String key = "abcdefghijklmop";// you could store it somewhere ...
justToMakePlainTextFile();
byte[] encrypted = encrypt("plaintext",key);
decrypt(encrypted, key);
}
public static void justToMakePlainTextFile() {
try {
RandomAccessFile randomAccessFile = new RandomAccessFile("plaintext", "rw");
FileChannel fileChannel = randomAccessFile.getChannel();
String randomText = "Ho-ho-ho-ho! This is going to be a nice weekend and I am going to swim soon.";
byte[] bytes = randomText.getBytes();
ByteBuffer byteBuffer = ByteBuffer.allocate(randomText.length());//alocate new ByteBuffer of size randomeText.length
byteBuffer.put(bytes);
byteBuffer.flip();
fileChannel.write(byteBuffer);
randomAccessFile.close();
fileChannel.close();
} catch (IOException ioE) {
System.err.println("JVM reported an error! Take a look: " + ioE);
}
}
public static byte[] encrypt(String file, String key) throws Exception {
RandomAccessFile reader = new RandomAccessFile(file, "r");
FileChannel channel = reader.getChannel();
int bufferSize = 1024;
if (bufferSize > channel.size()) {
bufferSize = (int) channel.size();
}
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
channel.read(buff);
buff.flip();
byte[] clean = buff.array();
channel.close();
reader.close();
// Generating IV.
int ivSize = 16;
byte[] iv = new byte[ivSize];
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
// Hashing key.
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(key.getBytes("UTF-8"));
byte[] keyBytes = new byte[16];
System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
// Encrypt.
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(clean);
// Combine IV and encrypted part.
byte[] encryptedIVAndText = new byte[ivSize + encrypted.length];
System.arraycopy(iv, 0, encryptedIVAndText, 0, ivSize);
System.arraycopy(encrypted, 0, encryptedIVAndText, ivSize, encrypted.length);
return encryptedIVAndText;
}
public static void decrypt(byte[] encryptedIvTextBytes, String key) throws Exception {
int ivSize = 16;
int keySize = 16;
// Extract IV.
byte[] iv = new byte[ivSize];
System.arraycopy(encryptedIvTextBytes, 0, iv, 0, iv.length);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
// Extract encrypted part.
int encryptedSize = encryptedIvTextBytes.length - ivSize;
byte[] encryptedBytes = new byte[encryptedSize];
System.arraycopy(encryptedIvTextBytes, ivSize, encryptedBytes, 0, encryptedSize);
// Hash key.
byte[] keyBytes = new byte[keySize];
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(key.getBytes());
System.arraycopy(md.digest(), 0, keyBytes, 0, keyBytes.length);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
// Decrypt.
Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decrypted = cipherDecrypt.doFinal(encryptedBytes);
try {
RandomAccessFile randomAccessFile = new RandomAccessFile("ciphertext", "rw");
FileChannel fileChannel = randomAccessFile.getChannel();
byte[] bytes = decrypted;
ByteBuffer byteBuffer = ByteBuffer.allocate(decrypted.length);//alocate new ByteBuffer of size randomeText.length
byteBuffer.put(bytes);
byteBuffer.flip();
fileChannel.write(byteBuffer);
randomAccessFile.close();
fileChannel.close();
} catch (IOException ioE) {
System.err.println("JVM reported an error! Take a look: " + ioE);
}
}
ciphertext and plaintext files are in your projects home folder created.

AES encryption while uploading and decryption on the fly or on user PC

I'm uploading file on my web site (created using JSP). I want to used encryption while user uploading the file and decrypt in his PC when he needs back his file. I know that I have to send him password, salt, & iv. I will send it through mail. But how to encrypt it at the time of uploading and decrypt it in user PC I don't know.
I have given here AES encryption and decryption code.
encrytion
public class AESFileEncryption {
public static void main(String[] args) throws Exception {
// file to be encrypted
FileInputStream inFile = new FileInputStream("C:\\Users\\gholv\\Desktop\\techpaper.pdf");
// encrypted file
FileOutputStream outFile = new FileOutputStream("C:\\Users\\gholv\\Desktop\\techpaper.aes");
// password to encrypt the file
String password = "javapapers";
// password, iv and salt should be transferred to the other end
// in a secure manner
// salt is used for encoding
// writing it to a file
// salt should be transferred to the recipient securely
// for decryption
byte[] salt = new byte[8];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(salt);
System.out.println(salt);
FileOutputStream saltOutFile = new FileOutputStream("C:\\Users\\gholv\\Desktop\\techpapersalt.enc");
saltOutFile.write(salt);
saltOutFile.close();
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536,
128);
SecretKey secretKey = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
//
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
// iv adds randomness to the text and just makes the mechanism more
// secure
// used while initializing the cipher
// file to store the iv
FileOutputStream ivOutFile = new FileOutputStream("C:\\Users\\gholv\\Desktop\\techpaperiv.enc");
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
System.out.println(iv);
ivOutFile.write(iv);
ivOutFile.close();
//file encryption
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = inFile.read(input)) != -1) {
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null)
outFile.write(output);
}
byte[] output = cipher.doFinal();
if (output != null)
outFile.write(output);
inFile.close();
outFile.flush();
outFile.close();
System.out.println("File Encrypted.");
}
}
decryption
public class AESFileDecryption {
public static void main(String[] args) throws Exception {
String password = "javapapers";
// reading the salt
// user should have secure mechanism to transfer the
// salt, iv and password to the recipient
FileInputStream saltFis = new FileInputStream("C:\\Users\\gholv\\Desktop\\techpapersalt.enc");
byte[] salt = new byte[8];
saltFis.read(salt);
saltFis.close();
// reading the iv
FileInputStream ivFis = new FileInputStream("C:\\Users\\gholv\\Desktop\\techpaperiv.enc");
byte[] iv = new byte[16];
ivFis.read(iv);
ivFis.close();
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536,
128);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
// file decryption
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
FileInputStream fis = new FileInputStream("C:\\Users\\gholv\\Desktop\\techpaper.aes");
FileOutputStream fos = new FileOutputStream("C:\\Users\\gholv\\Desktop\\plainfile_decrypted.pdf");
byte[] in = new byte[64];
int read;
while ((read = fis.read(in)) != -1) {
byte[] output = cipher.update(in, 0, read);
if (output != null)
fos.write(output);
}
byte[] output = cipher.doFinal();
if (output != null)
fos.write(output);
fis.close();
fos.flush();
fos.close();
System.out.println("File Decrypted.");
}
}

javax.crypto.BadPaddingException: Given final block not properly padded while decryption

I am trying to decrypt a file in java. The first 16 bytes of decrypted file are IV (initialization vector). Please help in resolving the above exception.
I am trying to prepend the IV in the output file in AESFileEncryption() and then reading it while decryption.
Thank You.
public class AESFileEncryption {
public static void encrypt(String path,String pwd) throws Exception {
FileOutputStream outFile;
try (
FileInputStream inFile = new FileInputStream(path)) {
String fileName=path;
System.out.println(path);
outFile = new FileOutputStream(fileName+".aes");
// password to encrypt the file
String password = pwd;
byte[] salt = {
(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
};
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(),salt,65536,128);// user-chosen password that can be used with password-based encryption (PBE).
SecretKey secretKey = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");//Secret KeySpec is a class and implements inteface SecretKey
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[16];
random.nextBytes(bytes);
IvParameterSpec ivspec = new IvParameterSpec(bytes);
cipher.init(Cipher.ENCRYPT_MODE, secret,ivspec);//opmode,key
outFile.write(bytes);
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = inFile.read(input)) != -1) {
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null)
Files.write(Paths.get(fileName+".aes"), output, StandardOpenOption.APPEND);
} byte[] output = cipher.doFinal();
if (output != null)
Files.write(Paths.get(fileName+".aes"), output, StandardOpenOption.APPEND);
}
outFile.flush();
outFile.close();
File f=new File(path);
boolean x=f.delete();
if(x){
System.out.println("File deleted");
}
JOptionPane.showMessageDialog(null,"File Encrypted.");
}
}
Decryption code
public class AESFileDecryption {
public static void decrypt(String path,String pwd) throws Exception {
String password = pwd;
String fileName=path;
File file=new File(path);
//System.out.println(inFile.toString());
String fileNameWithOutExt = path.replaceFirst("[.][^.]+$", "");
System.out.println(fileName);
System.out.println(fileNameWithOutExt);
byte[] salt = {
(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
};
System.out.println("1");
FileInputStream fis = new FileInputStream(path);
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(),salt,65536,128);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
System.out.println("2");
// file decryption
Cipher cipher=null;
byte bytes[]=new byte[16];
fis.read(bytes, 0, 16);
IvParameterSpec ivspec = new IvParameterSpec(bytes);
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, ivspec);
System.out.println("3");
FileOutputStream fos = new FileOutputStream(fileNameWithOutExt);
System.out.println("4");
byte[] in = new byte[64];
int read;
while ((read = fis.read(in,16,(int)file.length()-16)) != -1) {
byte[] output = cipher.update(in, 0, read);
if (output != null)
fos.write(output);
}
try{
byte[] output = cipher.doFinal();
if (output != null)
fos.write(output);
fis.close();
fos.flush();
fos.close();
System.out.println("File Decrypted.");
}
catch(IOException | BadPaddingException | IllegalBlockSizeException e)
{
System.out.println(e+"");
}
}
}
There are a few problems with the small example, but the one that is most immediately your problem is the line
while ((read = fis.read(in,16,(int)file.length()-16)) != -1) {
You seem to be confused about the meaning of the offset parameter to the read(). It is not the offset into the file, but rather the offset into the array (in) that is specified in the first parameter.
A non-exhaustive list of other problems that I see include:
writing to the file using the two independent mechanisms (FileOutputStream.write() and Files.write()). This actually worked ok when I ran your program but it seems like it's asking for trouble. There's no reason to use Files.write() here.
fis.read(bytes, 0, 16); does not check the return value.
It seems you are struggling with finding some IO idioms that you're comfortable with. Or perhaps just experimenting. At the risk of giving you even more options to juggle, you might consider investigating google's open source Guava library. Many people find it has just what they needed.

Categories