Android exception java.io.IOException: last block incomplete - java

I am working on decrypting a binary file encrypted in C# using Rijndael encryption method. The file is copied to an android device. The decryption logic works fine when run in a java based desktop test program. But it throws java.io.IOException: last block incomplete when run in android. I am using the code below.
public static void Decrypt(String fileIn, String fileOut, byte[] key, byte[] IV, long offset)
{
// First we are going to open the file streams
FileInputStream fsIn;
try
{
fsIn = new FileInputStream(fileIn);,,
FileOutputStream fsOut = new FileOutputStream(fileOut);
// create cipher object
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(IV));
// create the encryption stream
CipherInputStream cis = new CipherInputStream(fsIn, cipher);
// set a buffer and keep writing to the stream
int bufferLen = KiloByte;
byte[] buffer = new byte[bufferLen];
int bytesRead = 0;
// read a chunk of data from the input file
while ( (bytesRead = cis.read(buffer, 0, bufferLen)) != -1)
{
// write to file
fsOut.write(buffer, 0, bytesRead);
}
fsOut.flush();
// close streams
fsOut.close();
cis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The key is generated by using the function
public static byte[] GetKey(String password, byte[] IV, int length)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
// Length is kept 16 to make it compatible with all platforms
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec ks = new PBEKeySpec(password.toCharArray(), IV, 1000, length*8);
SecretKey s = f.generateSecret(ks);
Key k = new SecretKeySpec(s.getEncoded(),"AES");
return k.getEncoded();
}
I have gone through many posts on internet related to the topic. Based on that, I have made sure that I use byte array rather String. But still getting this issue.

Related

BadPaddingException with Cipher class

I'm coding a program that generates a simmetrical AES key, encodes it using an assimetrical public key, writes that encoded AES key in a plain text file, and then it recovers the encoded AES key and decodes it.
This is the function that encodes the AES key and returns it as byte[]:
private static byte[] EncodeKey(String valueToEncode, Key myKey)
{
byte[] encodedKey = null;
try
{
//Cipher
Cipher c = Cipher.getInstance("RSA", "SunJCE");
c.init(Cipher.ENCRYPT_MODE, myKey);
//Encoding
encodedKey = c.doFinal(valueToEncode.getBytes());
}
catch (Exception ex)
{
System.out.println(ex.toString());
} //try
return encodedKey;
} //CifrarCadenaRSA
Then I write this byte array in a txt file with this another function:
private static void WriteTextFile(String path, byte[] valueToWrite)
{
try
{
//Check if file exists
File f = new File(path);
if (f.exists())
{
f.delete();
} //if
f.createNewFile();
//FileOutputStream
FileOutputStream fos = new FileOutputStream(f);
//Writing
fos.write(valueToWrite);
}
catch (Exception ex)
{
System.out.println(ex.toString());
} //try
} //EscribirArchivoTexto
And finally, I load the encoded data and try to decode it:
private static Key DecodeKeyFromFile(String path, Key keyToDecode)
{
//Clave descifrada
Key decodedKey = null;
try
{
//File
File f = new File(ruta);
//Reading text file
byte[] encodedKey = Files.readAllBytes(f.toPath());
//Cipher for decoding
Cipher c = Cipher.getInstance("RSA", "SunJCE");
c.init(Cipher.DECRYPT_MODE, clave);
//Decoding: THIS IS THROWING BadPaddingException
byte[] keyBytes = c.doFinal(encodedKey);
decodedKey = (Key) new SecretKeySpec(claveBytes, 0, claveBytes.length, "AES");
}
catch (Exception ex)
{
System.out.println(ex.toString());
} //try
return decodedKey;
} //CargarClaveCifrada
As you can see, I use the same algorithm and padding for both encoding and decoding. I also tried using "RSA/ECB/PKCS1Padding" but nothing changes. So why is decoding throwing a BadPaddingException?
The exception I get:
javax.crypto.BadPaddingException: Decryption error
And the trace:
javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at cifradoHibrido.CifradoHibrido.DecodeKeyFromFile(CifradoHibrido.java:197)
at cifradoHibrido.CifradoHibrido.DecodeMessage(CifradoHibrido.java:174)
at cifradoHibrido.CifradoHibrido.main(CifradoHibrido.java:98)

Java to VB.NET AES Encryption

I have this code here which I'm having difficulty converting to VB.NET and hoping someone who give me a hand with it.
I'm having difficulty with the part on the cipher - I have tried Googling but was unable to find a clear resource explaining it in simple terms. (I don't know how to proceed with it as it seems there's no equivalent for it??)
I have almost no knowledge of java hence am trying to google and find out what each part means and convert it after. Hope someone would be able to point me in the right direction!
public static byte[] decryptPDF(String password, String filePath) {
try {
byte[] headerSaltAndCipherText = Base64.decode(IOUtils.toString(new FileInputStream(new File(filePath)), "UTF-8").toString().getBytes("UTF-8"), 0);
byte[] salt = Arrays.copyOfRange(headerSaltAndCipherText, 8, 16);
byte[] encrypted = Arrays.copyOfRange(headerSaltAndCipherText, 16, headerSaltAndCipherText.length);
Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[][] keyAndIV = EVP_BytesToKey(32, aesCBC.getBlockSize(), MessageDigest.getInstance(CommonUtils.MD5_INSTANCE), salt, password.getBytes("UTF-8"), 1);
aesCBC.init(2, new SecretKeySpec(keyAndIV[0], "AES"), new IvParameterSpec(keyAndIV[1]));
return aesCBC.doFinal(encrypted);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (NoSuchPaddingException e2) {
e2.printStackTrace();
return null;
} catch (InvalidAlgorithmParameterException e3) {
e3.printStackTrace();
return null;
} catch (NoSuchAlgorithmException e4) {
e4.printStackTrace();
return null;
} catch (IllegalBlockSizeException e5) {
e5.printStackTrace();
return null;
} catch (BadPaddingException e6) {
e6.printStackTrace();
return null;
} catch (InvalidKeyException e7) {
e7.printStackTrace();
return null;
}
}
What I've tried so far is...
Public Shared Function decryptPDF(ByVal password As String, ByVal fileAsString As String) As Byte()
Try
Dim headerSaltAndCipherText() As Byte = System.Convert.FromBase64String(fileAsString)
Dim salt() As Byte = headerSaltAndCipherText.Skip(7).Take(8)
Dim encrypted() As Byte = headerSaltAndCipherText.Skip(15).Take(headerSaltAndCipherText.Length)
Dim aesCBC As Cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
Dim keyAndIV() As Byte = EVP_BytesToKey(32, aesCBC.getBlockSize, MessageDigest.getInstance(CommonUtils.MD5_INSTANCE), salt, password.getBytes("UTF-8"), 1)
aesCBC.init(2, New SecretKeySpec(keyAndIV(0), "AES"), New IvParameterSpec(keyAndIV(1)))
Return aesCBC.doFinal(encrypted)
End Try
End Function
Try that
Public Shared Function decryptPDF(ByVal password As String, ByVal filePath As String) As Byte()
Try
Dim headerSaltAndCipherText() As Byte = Base64.decode(IOUtils.toString(New FileInputStream(New File(filePath)), "UTF-8").toString.getBytes("UTF-8"), 0)
Dim salt() As Byte = Arrays.copyOfRange(headerSaltAndCipherText, 8, 16)
Dim encrypted() As Byte = Arrays.copyOfRange(headerSaltAndCipherText, 16, headerSaltAndCipherText.length)
Dim aesCBC As Cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
Dim keyAndIV(,) As Byte = EVP_BytesToKey(32, aesCBC.getBlockSize, MessageDigest.getInstance(CommonUtils.MD5_INSTANCE), salt, password.getBytes("UTF-8"), 1)
aesCBC.init(2, New SecretKeySpec(keyAndIV(0), "AES"), New IvParameterSpec(keyAndIV(1)))
Return aesCBC.doFinal(encrypted)
Catch e As IOException
e.printStackTrace
Return Nothing
Catch e2 As NoSuchPaddingException
e2.printStackTrace
Return Nothing
Catch e3 As InvalidAlgorithmParameterException
e3.printStackTrace
Return Nothing
Catch e4 As NoSuchAlgorithmException
e4.printStackTrace
Return Nothing
Catch e5 As IllegalBlockSizeException
e5.printStackTrace
Return Nothing
Catch e6 As BadPaddingException
e6.printStackTrace
Return Nothing
Catch e7 As InvalidKeyException
e7.printStackTrace
Return Nothing
End Try
End Function

How can I store hashed password in sqlite android

protected static byte[] getHashedKey(String password,String MODE)throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
saltIV = new byte[48];
salt = new byte[32];
ivBytes =new byte[16];
if(MODE.equals("CREATE_VAULT")){
//generate salt ,iv & save them
salt = generateSalt();
ivBytes = generateIV();
System.arraycopy(salt, 0, saltIV, 0, salt.length);
System.arraycopy(ivBytes, 0, saltIV, salt.length, ivBytes.length);
//save salt & iv
//FileOutputStream saltIvOutFile = new FileOutputStream("C:\\saltIv.ats");
//saltIvOutFile.write(saltIV);
//saltIvOutFile.close();
}
if(MODE.equals("OPEN_VAULT")){
FileInputStream saltIvInFile = new FileInputStream("C:\\saltIv.ats");
saltIvInFile.read(saltIV);
saltIvInFile.close();
System.arraycopy(saltIV, 0, salt, 0, salt.length);
System.arraycopy(saltIV, salt.length, ivBytes, 0, ivBytes.length);
}
// Derive the key
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
PBEKeySpec spec = new PBEKeySpec(
password.toCharArray(),
salt,
pswdIterations,
keySize
);
SecretKey secretKey = factory.generateSecret(spec);
return secretKey.getEncoded();
}
this is where the hashed password gets generated and
try {
String finalKey = Arrays.toString(androCrypter.getHashedKey(v.password,"CREATE_VAULT"));
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
boolean vaultCreationSuccessful = new TableController(context).addNewVault(finalKey,v.vaultName,v.algorithm);
this is where I save the hash as string and insert it to database
but it never gets saved.The sqlite column is TEXT type.I came to know that sqlite supports directly saving byte array so I tried with byte[] also but same result,no entry in database.There is nothing wrong with addVault() code as I have checked it with other normal string and all,it works just fine.
Here is the code
protected boolean addNewVault(String finalKey,String vaultName,String algorithm) {
ContentValues values = new ContentValues();
values.put("Vault_Name", vaultName);
values.put("KEY", finalKey);
values.put("Algorithm", algorithm);
SQLiteDatabase db = this.getWritableDatabase();
boolean createSuccessful = db.insert(DATABASE_NAME, null, values) > 0;
db.close();
return createSuccessful;
}
But in this case I cant get it to work.Nothing gets saved.I also read about BLOB but I think its not needed as because byte[] is supported in sqlite.
What is wrong ?
Any help/suggestion would be really appreciated.Thank you.
NOTE:Please ignore the FileInputStream and FileOutputtream lines in getHashedKey();
EDIT:
I just figured out that this
try {
finalKey = Arrays.toString(androCrypter.getHashedKey(v.password,"CREATE_VAULT"));
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
code is not getting executed that is the problem. I have created another class just to check if it works there and it does.
Tried another method and calling it like finalKey= getFinalKey(v.password) and this method contains the above code but that does not work.
I am completely out of clue.Please help.
What I would do is to convert the "byte[]" to String:
String hashAsString = new String(hashAsBytes,"UTF-8");
Where "hashAsBytes" is the the resulting of "getHashedKey", and "hashAsString" is your byte array converted to a String.
Then you just save the "hashAsString" in your DB, as you see fit.
Then to compare hashes:
public boolean compareHashes(String hashInDB, String hashNew){
return hashInDB.equals(hashNew);
}
This method will return TRUE if your hashInDB is equal to the new hash you have just calculated. In case the hashes do not match it will return FALSE.
Hope this helps!
Best, Federico.

AES encryption, got extra trash characters in decrypted file

Im making a debug loggin function in an android app.
I have a simple class which is logging to .txt file using 128 bit AES encryption.
After the logging is done, i decrypt the logged file with a simple JAVA program.
The problem is when i decrypt the encrypted log i got some weird content in it, i also got the encrypted content, but there are some extra characters, see below.
Android app logging part:
public class FileLogger {
//file and folder name
public static String LOG_FILE_NAME = "my_log.txt";
public static String LOG_FOLDER_NAME = "my_log_folder";
static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SSS");
//My secret key, 16 bytes = 128 bit
static byte[] key = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6};
//Appends to a log file, using encryption
public static void appendToLog(Context context, Object msg) {
String msgStr;
String timestamp = "t:" + formatter.format(new java.util.Date());
msgStr = msg + "|" + timestamp + "\n";
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(sdcard.getAbsolutePath() + "/" + LOG_FOLDER_NAME);
if (!dir.exists()) {
dir.mkdir();
}
File encryptedFile = new File(dir, LOG_FILE_NAME);
try {
//Encryption using my key above defined
Key secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] outputBytes = cipher.doFinal(msgStr.getBytes());
//Writing to the file using append mode
FileOutputStream outputStream = new FileOutputStream(encryptedFile, true);
outputStream.write(outputBytes);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
}
}
And this is the decrypter JAVA program:
public class Main {
//output file name after decryption
private static String decryptedFileName;
//input encrypted file
private static String fileSource;
//a prefix tag for output file name
private static String outputFilePrefix = "decrypted_";
//My key for decryption, its the same as in the encrypter program.
static byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };
//Decrypting function
public static void decrypt(byte[] key, File inputFile, File outputFile) throws Exception {
try {
Key secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
FileInputStream inputStream = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
byte[] outputBytes = cipher.doFinal(inputBytes);
FileOutputStream outputStream = new FileOutputStream(outputFile, true);
outputStream.write(outputBytes);
inputStream.close();
outputStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
//first argument is the intput file source
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Add log file name as a parameter.");
} else {
fileSource = args[0];
try {
File sourceFile = new File(fileSource);
if (sourceFile.exists()) {
//Decrption
decryptedFileName = outputFilePrefix + sourceFile.getName();
File decryptedFile = new File(decryptedFileName);
decrypt(key, sourceFile, decryptedFile);
} else {
System.out.println("Log file not found: " + fileSource);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Decryption done, output file: " + decryptedFileName);
}
}
}
Output decrypted log (Opened with notepad++):
There is the valid content, but you also can see the extra thrash characters. If I open with the default windows text editor i also got thrash charaters, but different ones.
This is my first try with encrypt -decrypt, what m i doing wrong?
Any ideas?
AES is a block cipher which only works on blocks. The plaintext that you want to encrypt can be of any length, so the cipher must always pad the plaintext to fill it up to a multiple of the block size (or add a complete block when it already is a multiple of the block size). In this PKCS#5/PKCS#7 padding each padding byte denotes the number of padded bytes.
The easy fix would be to iterate over outputBytes during decryption and remove those padding bytes which are always on the next line. This will break as soon as you use multiline log messages or use a semantically secure mode (more on that later).
The better fix would be to write the number of bytes for each log message before the message, read that and decrypt only that many bytes. This also probably easier to implement with file streams.
You currently use Cipher.getInstance("AES"); which is a non-fully qualified version of Cipher.getInstance("AES/ECB/PKCS5Padding");. ECB mode is not semantically secure. It simply encrypts each block (16 bytes) with AES and the key. So blocks that are the same will be the same in ciphertext. This is particularly bad, because some log messages start the same and an attacker might be able to distinguish them. This is also the reason why the decryption of the whole file worked despite being encrypted in chunks. You should use CBC mode with a random IV.
Here is some sample code for proper use of AES in CBC mode with a random IV using streams:
private static SecretKey key = generateAESkey();
private static String cipherString = "AES/CBC/PKCS5Padding";
public static void main(String[] args) throws Exception {
ByteArrayOutputStream log = new ByteArrayOutputStream();
appendToLog("Test1", log);
appendToLog("Test2 is longer", log);
appendToLog("Test3 is multiple of block size!", log);
appendToLog("Test4 is shorter.", log);
byte[] encLog = log.toByteArray();
List<String> logs = decryptLog(new ByteArrayInputStream(encLog));
for(String logLine : logs) {
System.out.println(logLine);
}
}
private static SecretKey generateAESkey() {
try {
return KeyGenerator.getInstance("AES").generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
private static byte[] generateIV() {
SecureRandom random = new SecureRandom();
byte[] iv = new byte[16];
random.nextBytes(iv);
return iv;
}
public static void appendToLog(String s, OutputStream os) throws Exception {
Cipher cipher = Cipher.getInstance(cipherString);
byte[] iv = generateIV();
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] data = cipher.doFinal(s.getBytes("UTF-8"));
os.write(data.length);
os.write(iv);
os.write(data);
}
public static List<String> decryptLog(InputStream is) throws Exception{
ArrayList<String> logs = new ArrayList<String>();
while(is.available() > 0) {
int len = is.read();
byte[] encLogLine = new byte[len];
byte[] iv = new byte[16];
is.read(iv);
is.read(encLogLine);
Cipher cipher = Cipher.getInstance(cipherString);
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] data = cipher.doFinal(encLogLine);
logs.add(new String(data, "UTF-8"));
}
return logs;
}
You've encrypted each log message with a distinct encryption context. When you call the doFinal method on the cipher object the plaintext is padded out to a multiple of 16. Effectively, your log file is sequence of many small encrypted messages. However on decryption you are ignoring these message boundaries and treating the file as a single encrypted message. The result is that the padding characters are not being properly stripped. What you are seeing as 'trash' characters are likely these padding bytes. You will need to redesign your logfile format, either to preserve the message boundaries so the decryptor can discover them or to eliminate them altogether.
Also, don't use defaults in Java cryptography: they're not portable. For example, Cipher.getInstance() takes a string of the form alg/mode/padding. Always specify all three. I notice you also use the default no-args String.getBytes() method. Always specify a Charset, and almost always "UTF8" is the best choice.

Java BadPaddingException "Given final block not properly padded" after several hours

Like many others over time I'm having issues with encryption in a system I'm maintaining.
Process A generates some encrypted text which later Process B must decode. They share the same code for this purpose which is as below:
public class DesEncryption {
private Cipher mEcipher;
private Cipher mDcipher;
private byte[] salt = {
(byte) 0x08, (byte) 0x90, (byte) 0xA6, (byte) 0x4B,
(byte) 0xBB, (byte) 0x51, (byte) 0x3C, (byte) 0xDE
};
// Iteration count
int iterationCount = 19;
DesEncryption(String passPhrase) throws EncryptionException {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
mEcipher = Cipher.getInstance(key.getAlgorithm());
mDcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
mEcipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
mDcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
throw new EncryptionException(e);
} catch (java.security.spec.InvalidKeySpecException e) {
throw new EncryptionException(e);
} catch (javax.crypto.NoSuchPaddingException e) {
throw new EncryptionException(e);
} catch (java.security.NoSuchAlgorithmException e) {
throw new EncryptionException(e);
} catch (java.security.InvalidKeyException e) {
throw new EncryptionException(e);
}
}
public String encrypt(String str) throws EncryptionException {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = mEcipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
throw new EncryptionException(e);
} catch (IllegalBlockSizeException e) {
throw new EncryptionException(e);
} catch (UnsupportedEncodingException e) {
throw new EncryptionException(e);
} catch (java.io.IOException e) {
throw new EncryptionException(e);
}
}
public String decrypt(String str) throws EncryptionException {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = mDcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
throw new EncryptionException(e);
} catch (IllegalBlockSizeException e) {
throw new EncryptionException(e);
} catch (UnsupportedEncodingException e) {
throw new EncryptionException(e);
} catch (java.io.IOException e) {
throw new EncryptionException(e);
}
}
}
The two processes run on separate servers, both Centos (5.3 for process A, 6.4 for Process B)
There are no apparent issues with Process A - The string to be encoded is done so reliably.
When process B starts, everything appears to be fine. It decodes and decrypts the required strings correctly.
At some point over the course of about 24 hours however, this stops working. At this point, I get the 'BadPaddingException "Given final block not properly padded"' Exceptions. This then continues every time the code is executed with any encoded string until such time as the process is restarted, at which point everything works again, including decoding strings that failed moments before.
At the time when this goes wrong, calling decrypt(encrypt("test")) will fail too so this seems to be unrelated to the actual encrypted value and more to do with the encryption and decryption getting out of sync some how.
If anyone could offer any suggestions about where I may be going wrong with this I'd appreciate it.
Many thanks in advance...
Andrew

Categories