I used a code like these to encrypt some text (content):
Code:
public EncryptFile(String fileName, String content) {
try {
FileConnection fconn = (FileConnection) Connector.open(fileName);
if (!fconn.exists()) {
fconn.create();
OutputStream os = fconn.openOutputStream();
AESKey key = new AESKey(FileOperations.KEY.getBytes("UTF-8"));//get an instance of AESKey with my key
NoCopyByteArrayOutputStream out = new NoCopyByteArrayOutputStream();
BlockEncryptor cryptoStream = new BlockEncryptor(new AESEncryptorEngine(key), out);
cryptoStream.write(content.getBytes("UTF-8"));
byte[] cipherText = new byte[content.getBytes("UTF-8").length];
System.arraycopy(out.getByteArray(), 0, cipherText, 0, out.size());
//cryptoStream.flush();
//cryptoStream.close();
os.write(cipherText);
os.flush();
os.close();
}
fconn.close();
} catch (CryptoTokenException e) {
Dialog.alert("Exception: " + e);
} catch (CryptoUnsupportedOperationException e) {
Dialog.alert("Exception: " + e);
} catch (IOException e) {
Dialog.alert("The database is corrupted!" + e);
} catch (Exception e) {
Dialog.alert("Exception: " + e);
}
} Here I get CryptoIOException (BadPaddingException) that makes me think that the encryption of the String content object or of the KEY is not right or something else...When I comment these rows that throws the exception
//cryptoStream.flush();
//cryptoStream.close();
I realized that the content is encrypted and after that i decrypt the content but the last four or more (depends on the text length) symbols are lost and not encrypted. What is the problem. Here is my Decryption Code:
Code:
public Document readEncryptedInputStream(String fileName) {
InputStream is = null;
Document doc = null;
try {
fconn = (FileConnection) Connector.open(fileName);
is = fconn.openInputStream();
AESKey key = new AESKey(KEY.getBytes("UTF-8"));
BlockDecryptor cryptoStream = new BlockDecryptor(new AESDecryptorEngine(key), is);
byte[] content = new byte[(int) fconn.fileSize()];
cryptoStream.read(content);
fconn = (FileConnection) Connector.open(INFO_DB_TEMP);
if (!fconn.exists()) {
fconn.create();
}
fconn.truncate(0);
OutputStream os = fconn.openOutputStream();
os.write(content);
os.close();
doc = readInputStream(INFO_DB_TEMP);
} catch (Exception e) {
Dialog.alert("Exception: " + e);
}
return doc;
}