How to Encrypt or Decrypt a File in Java? - java

I want to encrypt and decrypt a file in java, i had read this url http://www-users.york.ac.uk/~mal503/lore/pkencryption.htm and i got two files namely public Security certificate and private security certificate file and private.pem file, i copied these files and pasted in the current directory and worte java code as follows, when i run this no encryption or decryption is performed, pls see this and tell me where i went wrong
Encrypt Code
File ecryptfile=new File("encrypt data");
File publickeydata=new File("/publickey");
File encryptmyfile=new File("/sys_data.db");
File copycontent =new File("Copy Data");
secure.makeKey();
secure.saveKey(ecryptfile, publickeydata);
secure.encrypt(encryptmyfile, copycontent);
Decrypt code
File ecryptfile=new File("encrypt data");
File privateKeyFile=new File("/privatekey");
File encryptmyfile=new File("/sys_data.db");
File unencryptedFile =new File("unencryptedFile");
try {
secure.loadKey(encryptmyfile, privateKeyFile);
secure.decrypt(encryptmyfile, unencryptedFile);
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

You simply have muddled your files. This code works using the DER files generated from openssl as described in the article you linked:
FileEncryption secure = new FileEncryption();
// Encrypt code
{
File encryptFile = new File("encrypt.data");
File publicKeyData = new File("public.der");
File originalFile = new File("sys_data.db");
File secureFile = new File("secure.data");
// create AES key
secure.makeKey();
// save AES key using public key
secure.saveKey(encryptFile, publicKeyData);
// save original file securely
secure.encrypt(originalFile, secureFile);
}
// Decrypt code
{
File encryptFile = new File("encrypt.data");
File privateKeyFile = new File("private.der");
File secureFile = new File("secure.data");
File unencryptedFile = new File("unencryptedFile");
// load AES key
secure.loadKey(encryptFile, privateKeyFile);
// decrypt file
secure.decrypt(secureFile, unencryptedFile);
}

Here is the Simplest Piece of Code for encrypting a document with any Key(Here Random Key)
randomKey = randomKey.substring(0, 16);
keyBytes = randomKey.getBytes();
key = new SecretKeySpec(keyBytes, "AES");
paramSpec = new IvParameterSpec(iv);
ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
in = new FileInputStream(srcFile);
out = new FileOutputStream(encryptedFile);
out = new CipherOutputStream(out, ecipher);
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
in.close();
out.flush();
out.close();

Related

Decrypting file in Java with pre-existing AES key

I am trying to do something pretty simple. I encrypted a file in Windows using AxCrypt. In my Android application, I want to decrypt this file.
The 128bit AES key generated by AxCrypt is
CWTr 45Qg eHhy n23d YPC3 DjRi IxUe bt77 TVzQ NtSh HEc=
I assume this a Base64 encoded string but maybe I'm wrong. I plugged it in to my code below with the spaces but I also tried without the spaces and I get the same result.
The java code to decrypt the file is below. The decryption process starts but errors out with "last block incomplete in decryption" and the resulting file (an mp4 video) cannot be played.
Java code:
try {
Utils.logDebug(TAG, "Decrypting!");
File encfile = new File(getFilesDir() + "/encrypted.axx");
int read;
if (!encfile.exists())
encfile.createNewFile();
File decfile = new File(getFilesDir() + "/decrypted.mp4");
if (!decfile.exists())
decfile.createNewFile();
FileInputStream encfis = new FileInputStream(encfile);
FileOutputStream decfos = new FileOutputStream(decfile);
Cipher decipher = Cipher.getInstance("AES");
byte key[] = Base64.decode("CWTr 45Qg eHhy n23d YPC3 DjRi IxUe bt77 TVzQ NtSh HEc=", Base64.DEFAULT);
SecretKey skey = new SecretKeySpec(key, 0, key.length, "AES");
decipher.init(Cipher.DECRYPT_MODE, skey);
CipherOutputStream cos = new CipherOutputStream(decfos, decipher);
while ((read = encfis.read()) != -1) {
cos.write(read);
cos.flush();
}
cos.close();
Utils.logDebug(TAG, "Done decrypting!");
} catch (Exception e) {
Utils.logError(TAG, "TESTING error: " + e.getMessage());
}
AxCrypt encrypts in CBC mode, as well as compresses, MACs and a number of other details. To decrypt this you'll need to review http://www.axantum.com/AxCrypt/faq.html and their published source code here.
http://www.axantum.com/AxCrypt/SourceCode.html

Create a java zip FileSystem from an encrypted zip

I discovered that Java 7 introduced a zip FileSystem. Currently I have a encrypted zip files, that I'm decrypting with the following code
InputStream in = new FileInputStream(inFile);
Crypto algo = new Crypto();
algo.initV1();
in = new CipherInputStream(in, algo.getCiphertoDec(in, pass));
ZipInputStream zipInput = new ZipInputStream(in);
ZipEntry ze = zipInput.getNextEntry();
....
and the method getCiphertoDec is like this
public Cipher getCiphertoDec (InputStream in, String password) throws Exception {
byte[] salt = new byte[SALT_SIZE_BYTE];
if (in.read(salt) < SALT_SIZE_BYTE) {
throw new IllegalArgumentException("Invalid file length (needs a full block for salt)");
};
key = CoreCryptoV1.PBKDF2.pbkdf2(password, salt, 1000);
ivBytes = new byte[IV_LENGTH_BYTE];
if (in.read(ivBytes) < IV_LENGTH_BYTE) {
throw new IllegalArgumentException("Invalid file length (needs a full block for iv)");
};
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivBytes));
return cipher;
}
I wonder if there is any way to treat encrypted zip file as a file system.
I appreciate any advice.
I would like a solution that is compatible with android.

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.

Encrypt a folder in android from SDcard

How to encrypt a folder from android sdcard and the encrypted folder should be in filename.des. Is it possible?. I am using below code to encrypt a folder
try {
File root_sd = Environment.getExternalStorageDirectory();
//original is a folder to encrypt
file = new File(root_sd + "/myfile/original");
String filename = file.getAbsolutePath();
System.out.println("name of file for encryption ===>"+file.toString());
fis = new FileInputStream(filename);
//encrypted folder should be in filename.des
fos = new FileOutputStream("/mnt/sdcard/myfile/filename" + ".des");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("Encrypt ACtivity", "file io exception");
}
// Use PBEKeySpec to create a key based on a password.
// The password is passed as a character array
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFactory;
try {
keyFactory = SecretKeyFactory
.getInstance("PBEWithMD5AndDES");
SecretKey passwordKey = keyFactory.generateSecret(keySpec);
// PBE = hashing + symmetric encryption. A 64 bit random
// number (the salt) is added to the password and hashed
// using a Message Digest Algorithm (MD5 in this example.).
// The number of times the password is hashed is determined
// by the interation count. Adding a random number and
// hashing multiple times enlarges the key space.
byte[] salt = new byte[8];
Random rnd = new Random();
rnd.nextBytes(salt);
int iterations = 100;
// Create the parameter spec for this salt and interation
// count
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt,iterations);
// Create the cipher and initialize it for encryption.
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(Cipher.ENCRYPT_MODE, passwordKey, parameterSpec);
// Need to write the salt to the (encrypted) file. The
// salt is needed when reconstructing the key for
// decryption.
fos.write(salt);
// Read the file and encrypt its bytes.
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = fis.read(input)) != -1) {
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null)
fos.write(output);
}
byte[] output = cipher.doFinal();
if (output != null)
fos.write(output);
fis.close();
fos.flush();
but it is giving me FileNotFoundException. open failed : EISDIR (Is a directory). Cany anyone tell me how to ecrypt a folder. I am able to encrypt a file but not folder.
Thanks

Android exception java.io.IOException: last block incomplete

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.

Categories