AES+ Base64 Decrypt file appeared garbled - java

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");
}

Related

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.

javax.crypto.BadPaddingException: Given final block not properly padded while decrypting a file

I am trying to write a program to encrypt and decrypt files using java, but I get an error on the decrypt function:
Caused by: javax.crypto.BadPaddingException: Given final block not properly padded
here is the code for the encryption:
public static void EncryptFile(String inFile, PublicKey rsaPublicKey) {
AesManaged aesManaged = new AesManaged();
try {
aesManaged.keySize = 256;
aesManaged.blockSize = 128;
aesManaged.mode = "AES/CBC/PKCS5Padding";
byte[] key = generateKey(aesManaged.keySize);
byte[] keyEncrypted = encryptKey(key, rsaPublicKey);
byte[] LenK = new byte[4];
byte[] LenIV = new byte[4];
int lKey = keyEncrypted.length;
LenK = BitConverter.GetBytes(lKey);
int lIV = aesManaged.IV().length;
LenIV = BitConverter.GetBytes(lIV);
// Write the following to the FileStream
// for the encrypted file (outFs):
// - length of the key
// - length of the IV
// - ecrypted key
// - the IV
// - the encrypted cipher content
String outFile = "test.lamar";
ByteArrayOutputStream outFs = new ByteArrayOutputStream();
outFs.write(LenK);
outFs.write(LenIV);
outFs.write(keyEncrypted);
byte[] i = aesManaged.IV();
outFs.write(i);
IvParameterSpec ivspec = new IvParameterSpec(aesManaged.IV());
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance(aesManaged.mode);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec);
FileInputStream fileIn = new FileInputStream(inFile);
CipherOutputStream cipherOut = new CipherOutputStream(outFs, cipher);
int blockSiseByte = aesManaged.blockSize / 8;
byte[] data = new byte[blockSiseByte];
int count;
// Read in the data from the file and encrypt it
while ((count = fileIn.read(data, 0, blockSiseByte)) != -1) {
cipherOut.write(data, 0, count);
}
try (OutputStream outputStream = new FileOutputStream(outFile)) {
outFs.writeTo(outputStream);
}
// Close the encrypted file
fileIn.close();
outFs.close();
cipherOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and the code for the decryption:
public static void DecryptFile(String inFile, String outFile,
PrivateKey rsaPrivateKey) {
FileOutputStream outFs = null;
try {
// Create instance of AesManaged for
// symetric decryption of the data.
AesManaged aesManaged = new AesManaged();
{
aesManaged.keySize = 256;
aesManaged.blockSize = 128;
aesManaged.mode = "AES/CBC/PKCS5Padding";
// Create byte arrays to get the length of
// the encrypted key and IV.
// These values were stored as 4 bytes each
// at the beginning of the encrypted package.
byte[] LenK = new byte[4];
byte[] LenIV = new byte[4];
// Use FileStream objects to read the encrypted
// file (inFs) and save the decrypted file (outFs).
{
byte[] fileBytes = FileUtils.readFileToByteArray(new File(inFile));
ByteArrayInputStream inFs = new ByteArrayInputStream(
fileBytes);
;
for (int i = 0; i < LenK.length; i++) {
LenK[i] = (byte) inFs.read();
}
for(int i = 0; i< LenIV.length;i++){
LenIV[i] = (byte)inFs.read();
}
// Convert the lengths to integer values.
int lenK = BitConverter.ToInt32(LenK, 0);
int lenIV = BitConverter.ToInt32(LenIV, 0);
//int startC = lenK + lenIV + 8;
//int lenC = (int) fileBytes.length - startC;
// Create the byte arrays for
// the encrypted AesManaged key,
// the IV, and the cipher text.
byte[] KeyEncrypted = new byte[lenK];
byte[] IV = new byte[lenIV];
// Extract the key and IV
for(int i = 0;i<lenK;i++){
KeyEncrypted[i] = (byte)inFs.read();
}
for(int i =0;i<lenIV;i++){
IV[i] = (byte)inFs.read();
}
// to decrypt the AesManaged key.
byte[] KeyDecrypted = decryptKey(KeyEncrypted,rsaPrivateKey);
Cipher transform = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivspec = new IvParameterSpec(IV);
SecretKeySpec secretKeySpec = new SecretKeySpec(KeyDecrypted, "AES");
transform.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec);
// Decrypt the key.
outFs = new FileOutputStream(outFile);
int count = 0;
int offset = 0;
int blockSizeBytes = aesManaged.blockSize / 8;
byte[] data = new byte[blockSizeBytes];
CipherInputStream cipherIn = new CipherInputStream(
inFs, transform);
while ((count = cipherIn.read(data, 0, blockSizeBytes)) != -1) {
outFs.write(data, 0, count);
}
inFs.close();
cipherIn.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
The error occurred at the line:while ((count = cipherIn.read(data, 0, blockSizeBytes)) != -1) after many iterations.
What am I missing here?

TripleDES encrypting with vb.net and decrypting with java

I'm creating an interface for two applications that will communicate using encrypted text in .txt files. vb.net app will encrypt and java will decrypt.
vb code
Dim nget As String = System.IO.File.ReadAllText(sInputFilename)
Dim textBytes As Byte() = System.Text.Encoding.Unicode.GetBytes(nget)
Dim Passphrase As String = sKey
Dim UTF8 As New System.Text.UTF8Encoding()
Dim HashProvider As New MD5CryptoServiceProvider()
Dim TDESKey As Byte() = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase))
Dim TDESAlgorithm As New TripleDESCryptoServiceProvider()
TDESAlgorithm.Key = TDESKey
TDESAlgorithm.Mode = CipherMode.ECB
TDESAlgorithm.Padding = PaddingMode.PKCS7
Dim ms As New System.IO.MemoryStream()
Dim encStream As New CryptoStream(ms, TDESAlgorithm.CreateEncryptor(), CryptoStreamMode.Write)
encStream.Write(textBytes, 0, textBytes.Length)
encStream.FlushFinalBlock()
Dim strSave As String = Convert.ToBase64String(ms.ToArray())
My.Computer.FileSystem.WriteAllText(sOutputFilename, strSave, False)
java code
public static void main(String[] args) {
String codedtext = null;
try {
codedtext = readFile("ect.txt", StandardCharsets.UTF_8);
} catch (IOException e1) {
e1.printStackTrace();
}
String decodedtext = null;
try {
decodedtext = _decrypt(codedtext,"abcdefgh");
} catch (Exception e) {
e.printStackTrace();
}
}
private static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
private static String _encrypt(String message, String secretKey) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainTextBytes = message.getBytes("utf-8");
byte[] buf = cipher.doFinal(plainTextBytes);
byte [] base64Bytes = Base64.encodeBase64(buf);
String base64EncryptedString = new String(base64Bytes);
return base64EncryptedString;
}
private static String _decrypt(String encryptedText, String secretKey) throws Exception {
byte[] message = Base64.decodeBase64(encryptedText.getBytes("utf-8"));
//byte[] message = encryptedText.getBytes("utf-8");
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
//Cipher decipher = Cipher.getInstance("DESede");
Cipher decipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
but I'm getting the error
at java.lang.ArrayIndexOutOfBoundsException: -17
at org.apache.commons.codec.binary.Base64.isBase64(Base64.java:137)
at org.apache.commons.codec.binary.Base64.discardNonBase64(Base64.java:478)
at org.apache.commons.codec.binary.Base64.decodeBase64(Base64.java:374)
at Test.MyDec._decrypt(MyDec.java:74)
at Test.MyDec.main(MyDec.java:33)
when decoding from base64

AES Decryption ERROR: android pad block corrupted

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.

Categories