Android Lollipop Decryption using AES is not working properly - android

Till kitkat, encryption/decryption is working good but in lollipop it decrypts only partial data.
I don't have problem with encryption because I encrypted a file with lollipop and decrypts it with kitkat it works fine but not vice versa.
Here is the code.
Encryption code
Encrypt(BufferedInputStream is, File destfile, String passcode) {
bis = is;
try {
fos = new FileOutputStream(destfile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dest = new BufferedOutputStream(fos, 1024);
this.passcode = passcode;
}
static void encrypt() throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
// Length is 16 byte
SecretKeySpec sks = new SecretKeySpec(passcode.getBytes(), "AES");
// Create cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
// Wrap the output stream
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
// Write bytes
int b;
byte[] d = new byte[1024];
while ((b = bis.read(d)) != -1) {
cos.write(d, 0, b);
}
// Flush and close streams.
cos.flush();
cos.close();
bis.close();
}
Decryption code
public Decrypt(String path, String pathcode) {
// TODO Auto-generated constructor stub
filepath = path;
try {
fis = new FileInputStream(new File(path));
this.passcode = pathcode;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static String decrypt() throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
SecretKeySpec sks = new SecretKeySpec(passcode.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
int size = fis.available();
byte[] resdata = new byte[size];
cis.read(resdata, 0, size);
String newres = new String(resdata, "UTF-8").trim();
//write("decrypted_file.xhtml",newres);
if(fis!=null)
{
fis.close();
}
if(cis!=null)
cis.close();
return newres;
}
What's the problem in this code? Do I need to do anything more?

available() doesn't necessarily return the length of the entire stream, just the estimated number of bytes that can be read without blocking. So, use a ByteArrayOutputStream to store the bytes and then covert to a byte array:
CipherInputStream cis = new CipherInputStream(fis, cipher);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int bytesRead;
byte[] data = new byte[1024];
while ((bytesRead = cis.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytesRead);
}
buffer.flush();
byte[] resdata = buffer.toByteArray();
String newres = new String(resdata, "UTF-8").trim();

Related

how to encrypt and decrypt audio file android

I am trying to encrypt and then decrypt audio file . Everything goes right but when I try to decrypt the encrypted audio , everytime I got this exception
javax.crypto.BadPaddingException: pad block corrupted
My MainActivity is like this: I want to decrypt and play the song side by side
public class MainActivity extends Activity{
private final String KEY = "abc";
Button btn_Dec, btn_In;
byte[] incrept;
byte[] decrpt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx = this;
btn_Dec = (Button) findViewById(R.id.button2);
btn_In = (Button) findViewById(R.id.button1);
btn_Dec.setOnClickListener(btnDecListner);
btn_In.setOnClickListener(btnInListner);
}
public OnClickListener btnDecListner = new OnClickListener() {
public void onClick(View v) {
VincentFileCrypto simpleCrypto = new VincentFileCrypto();
try {
// decrypt the file here first argument is key and second is encrypted file which we get from SD card.
decrpt = simpleCrypto.decrypt(KEY, getAudioFileFromSdCard());
//play decrypted audio file.
playMp3(decrpt);
} catch (Exception e) {
e.printStackTrace();
}
}
};
Context ctx;
public OnClickListener btnInListner = new OnClickListener() {
public void onClick(View v) {
VincentFileCrypto simpleCrypto = new VincentFileCrypto();
try {
// encrypt audio file send as second argument and corresponding key in first argument.
incrept = simpleCrypto.encrypt(KEY, getAudioFile());
//Store encrypted file in SD card of your mobile with name vincent.mp3.
FileOutputStream fos = new FileOutputStream(new File("/sdcard/vincent.mp3"));
fos.write(incrept);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
/**
* #return byte array for encryption.
* #throws FileNotFoundException
*/
public byte[] getAudioFile() throws FileNotFoundException
{
byte[] audio_data = null;
byte[] inarry = null;
AssetManager am = ctx.getAssets();
try {
InputStream is = am.open("Sleep Away.mp3"); // use recorded file instead of getting file from assets folder.
int length = is.available();
audio_data = new byte[length];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(audio_data)) != -1)
{
output.write(audio_data, 0, bytesRead);
}
inarry = output.toByteArray();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inarry;
}
/**
* This method fetch encrypted file which is save in sd card and convert it in byte array after that this file will be decrept.
*
* #return byte array of encrypted data for decription.
* #throws FileNotFoundException
*/
public byte[] getAudioFileFromSdCard() throws FileNotFoundException
{
byte[] inarry = null;
try {
//getting root path where encrypted file is stored.
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "vincent.mp3"); //Creating file object
//Convert file into array of bytes.
FileInputStream fileInputStream = null;
byte[] bFile = new byte[(int) file.length()];
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
inarry = bFile;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inarry;
}
/**
* This Method is used to play audio file after decrepting.
*
* #param mp3SoundByteArray : This is our audio file which will be play and it converted in byte array.
*/
private void playMp3(byte[] mp3SoundByteArray) {
try {
// create temp file that will hold byte array
File tempMp3 = File.createTempFile("kurchina", "mp3", getCacheDir());
tempMp3.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempMp3);
fos.write(mp3SoundByteArray);
fos.close();
// Tried reusing instance of media player
// but that resulted in system crashes...
MediaPlayer mediaPlayer = new MediaPlayer();
FileInputStream fis = new FileInputStream(tempMp3);
mediaPlayer.setDataSource(fis.getFD());
mediaPlayer.prepareAsync();
mediaPlayer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The encryption and decryption methods are mentioned in this class
public class VincentFileCrypto {
public byte[] encrypt(String seed, byte[] cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext);
// return toHex(result);
return result;
}
public byte[] decrypt(String seed, byte[] encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = encrypted;
byte[] result = decrypt(rawKey, enc);
return result;
}
//done
private byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
}
After days of research and hard work I found the solution ,may help and save somebody's else time . Here is my answer. I changed the above code logic like this
now what is happening , I am able to successfully encrypt the file and save it in the sdcard and then decrypt it to play . No body else can play the audio.
here we go : happy coding
public class Main2Activity extends AppCompatActivity {
private String encryptedFileName = "encrypted_Audio.mp3";
private static String algorithm = "AES";
static SecretKey yourKey = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//saveFile("Hello From CoderzHeaven asaksjalksjals");
try {
saveFile(getAudioFile());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
decodeFile();
}
public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
// Number of PBKDF2 hardening rounds to use. Larger values increase
// computation time. You should select a value that causes computation
// to take >100ms.
final int iterations = 1000;
// Generate a 256-bit key
final int outputKeyLength = 256;
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations, outputKeyLength);
SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
return secretKey;
}
public static SecretKey generateKey() throws NoSuchAlgorithmException {
// Generate a 256-bit key
final int outputKeyLength = 256;
SecureRandom secureRandom = new SecureRandom();
// Do *not* seed secureRandom! Automatically seeded from system entropy.
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(outputKeyLength, secureRandom);
yourKey = keyGenerator.generateKey();
return yourKey;
}
public static byte[] encodeFile(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] encrypted = null;
byte[] data = yourKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length, algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(
new byte[cipher.getBlockSize()]));
encrypted = cipher.doFinal(fileData);
return encrypted;
}
public static byte[] decodeFile(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] decrypted = null;
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));
decrypted = cipher.doFinal(fileData);
return decrypted;
}
void saveFile(byte[] stringToSave) {
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator, encryptedFileName);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
yourKey = generateKey();
byte[] filesBytes = encodeFile(yourKey, stringToSave);
bos.write(filesBytes);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
void decodeFile() {
try {
byte[] decodedData = decodeFile(yourKey, readFile());
// String str = new String(decodedData);
//System.out.println("DECODED FILE CONTENTS : " + str);
playMp3(decodedData);
} catch (Exception e) {
e.printStackTrace();
}
}
public byte[] readFile() {
byte[] contents = null;
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator, encryptedFileName);
int size = (int) file.length();
contents = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(
new FileInputStream(file));
try {
buf.read(contents);
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return contents;
}
public byte[] getAudioFile() throws FileNotFoundException
{
byte[] audio_data = null;
byte[] inarry = null;
AssetManager am = getAssets();
try {
InputStream is = am.open("Sleep Away.mp3"); // use recorded file instead of getting file from assets folder.
int length = is.available();
audio_data = new byte[length];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(audio_data)) != -1) {
output.write(audio_data, 0, bytesRead);
}
inarry = output.toByteArray();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inarry;
}
private void playMp3(byte[] mp3SoundByteArray) {
try {
// create temp file that will hold byte array
File tempMp3 = File.createTempFile("kurchina", "mp3", getCacheDir());
tempMp3.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempMp3);
fos.write(mp3SoundByteArray);
fos.close();
// Tried reusing instance of media player
// but that resulted in system crashes...
MediaPlayer mediaPlayer = new MediaPlayer();
FileInputStream fis = new FileInputStream(tempMp3);
mediaPlayer.setDataSource(fis.getFD());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

AES Algorithm for audio files in Android

Hi I am working on AES encryption and decryption in my project.
I have a .mp4 file which is encrypted using "AES/CBC/pkcs5padding".
I have the key and iv values which is used to encrypt the first 256 bytes of the audio file.
I need to decrypt the file's first 256 bytes using the same algorithm , key and iv values.
I have followed some links (link1,link2).
I got a audio player demo and tried to implement my part(AES encryption and decryption) as demo.
Below I explained the code what I have done.
This method reads the data from encrypted file which is under res/raw folder.
private void readFile() throws IOException, InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException,
InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException {
Context context = getApplicationContext();
/*
* InputStream is = getResources().openRawResource(
* getResources().getIdentifier("raw/encrypted", "raw",
* getPackageName())); String text = "";
*
* int size = is.available(); byte[] buffer = new byte[size];
* is.read(buffer);
*/
InputStream inStream = context.getResources().openRawResource(
R.raw.encrypted);
// get string from file
byte[] music = new byte[256];
for (int i = 0; i <= inStream.available(); i = i + 255) {
music = convertStreamToByteArray(inStream, i);
byte[] bytesToWrite = new byte[256];
bytesToWrite = music;
if (i == 0) {
bytesToWrite = AES256Cipher.decrypt(iv.getBytes("UTF-8"),
key.getBytes("UTF-8"), music);
// writeFirstSetOfBytes("decrypted.mp4");
}
writeFirstSetOfBytes(bytesToWrite);
}
}
the decrypt method got from the link1. Here I passed the key and iv values mentioned above.
public static byte[] decrypt(byte[] ivBytes, byte[] keyBytes,
byte[] textBytes) throws java.io.UnsupportedEncodingException,
NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException {
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
// SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE,
new SecretKeySpec(keyBytes, "AES"), ivSpec);
return cipher.doFinal(textBytes);
}
This method used to get the byte array from the input stream.
public static byte[] convertStreamToByteArray(InputStream is, int size)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[256];
int i = Integer.MAX_VALUE;
while ((i = is.read(buff, size, buff.length)) > 0) {
baos.write(buff, 0, i);
}
return baos.toByteArray(); // be sure to close InputStream in calling
// function
}
This method writes the received byte array into a destination file(decrypted.mp4)
private void writeFirstSetOfBytes(byte[] byteToWrite) {
File file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/decrypted.mp4");
FileOutputStream stream = null;
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// writing data into file
try {
stream = new FileOutputStream(file);
stream.write(byteToWrite);
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am getting the following error.
javax.crypto.IllegalBlockSizeException: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
How can I achieve my requirement ?
How do I decrypt the first 256 bytes of data only?
Is there any code behaves wrongly ?
Is there any third party library avilable ?
If need more clarification, kindly let me know.
According to Wikipedia, PKCS#5 is a special variant of PKCS#7 that is defined for exactly 64-bit blocks (while PKCS#7 works for any block size), but AES uses 128-bit blocks only (or larger, but this was not included in the standard), thus the mismatch. Try another padding scheme.

How to encrypt epub file and read without storing in sd card

I Tried following code.
How to read encrypted .epub file (Without saving decrypted file on sd card)
I want to maintain security for .epub file
is it possible to maintain security?
Thanks for Help in prior
static void encrypt() throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
// Here you read the cleartext.
String file_en_path = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Decrypted";
File extStore = new File(file_en_path,"text.epub");
FileInputStream fis = new FileInputStream(extStore);
// This stream write the encrypted text. This stream will be wrapped by
// another stream.
File extStore_enc = new File(file_en_path,"text_enc.epub");
FileOutputStream fos = new FileOutputStream(extStore_enc);
Log.d("encrypt--fis------------->>>>>>",""+fis);
Log.d("encrypt--fos------------->>>>>>",""+fos);
// Length is 16 byte
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),"AES");
// Create cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
// Wrap the output stream
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
// Write bytes
int b;
byte[] d = new byte[8];
while ((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
// Flush and close streams.
cos.flush();
cos.close();
fis.close();
}
static void decrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
String file_de_path = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Decrypted";
File extStore = new File(file_de_path,"text_enc.epub");
//File extStore = Environment.getExternalStorageDirectory();
FileInputStream fis = new FileInputStream(extStore);
File extStore_dec = new File(file_de_path,"text_dec.epub");
FileOutputStream fos = new FileOutputStream(extStore_dec);
//FileOutputStream fos = context.openFileOutput("fontsize_dec.txt",Context.MODE_PRIVATE);
Log.d("decrypt--fis------------->>>>>>",""+fis);
Log.d("decrypt--fos------------->>>>>>",""+fos);
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),"AES");
IvParameterSpec ivSpec = new IvParameterSpec("MyDifficultPassw".getBytes());
Cipher cipher = Cipher.getInstance("AES");
try {
cipher.init(Cipher.DECRYPT_MODE, sks, ivSpec);
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[8];
StringBuilder sb = new StringBuilder();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(cis, "UTF-8"));
/*line = reader.readLine();
sb.append(line);
Log.d("sb.append(line)--------------------------->",""+sb.append(line));*/
while ((line = reader.readLine()) != null) {
sb.append(line);
// Log.d("sb.append(line)--------------------------->",""+sb.append(line));
// Log.d("Line--------------------------->",""+line);
}
Log.d("sb.toSting-------------------->",""+sb.toString());
while ((b = cis.read(d)) != -1) {
//Log.d("cis.read(d)------------------------>>>>>>>",""+cis.read(d));
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
}

Decrypt AES256 encrypted bytes

I've never worked with encryption before. Actually I know nothing about encryption. I have a file encrypted with openssl tool using params:
openssl aes-256-cbc -nosalt -in fileIn -out fileOUT -p -k KEY
I need to decrypt it into memory but I don't know how. Can anyone provide me the code related to encryption?
Here's class I have written to decrypt a string encoded with params above (if I remmeber it correct):
public class CipherUtils {
public static byte[] getKey(String password, byte[] salt) {
try {
byte[] passwordSalt = EncodingUtils.getAsciiBytes(password);
passwordSalt = concatenateByteArrays(passwordSalt, salt);
byte[] hash1 = getHashForHash(null, passwordSalt);
byte[] hash2 = getHashForHash(hash1, passwordSalt);
byte[] key = concatenateByteArrays(hash1, hash2);
return key;
} catch (Exception e) {
return null;
}
}
public static byte[] getIV(String password, byte[] salt) {
try {
byte[] passwordSalt = EncodingUtils.getAsciiBytes(password);
passwordSalt = concatenateByteArrays(passwordSalt, salt);
byte[] hash1 = getHashForHash(null, passwordSalt);
byte[] hash2 = getHashForHash(hash1, passwordSalt);
byte[] hash3 = getHashForHash(hash2, passwordSalt);
return hash3;
} catch (Exception e) {
return null;
}
}
private static byte[] getHashForHash(byte[] hash, byte[] passwordSalt) {
try {
byte[] hashMaterial = concatenateByteArrays(hash, passwordSalt);
MessageDigest md = MessageDigest.getInstance("MD5");
return md.digest(hashMaterial);
} catch (Exception e) {
return null;
}
}
private static byte[] concatenateByteArrays(byte[] a, byte[] b) {
if (a == null)
return b;
if (b == null)
return a;
byte[] result = new byte[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
}
Salt is an empty bytearray in this case. It uses apache-commons-compress.jar.
Here's usage example:
byte[] key = CipherUtils.getKey(password, null);
byte[] IV = CipherUtils.getIV(password, null);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
new IvParameterSpec(IV));
cis = new CipherInputStream(is, cipher);
Where is is an InputStream of encrypted data.
this may helps you
public void encrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
// Here you read the cleartext.
FileInputStream fis = new FileInputStream("data/cleartext");
// This stream write the encrypted text. This stream will be wrapped by
// another stream.
FileOutputStream fos = new FileOutputStream("data/encrypted");
// Length is 16 byte
SecretKeySpec sks = new SecretKeySpec("yourkey".getBytes(), "AES");
// Create cipher
Cipher cipher = Cipher.getInstance("AES/CBC");
cipher.init(Cipher.ENCRYPT_MODE, sks);
// Wrap the output stream
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
// Write bytes
int b;
byte[] d = new byte[8];
while ((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
// Flush and close streams.
cos.flush();
cos.close();
fis.close();
}
Decrypt
public void decrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
FileInputStream fis = new FileInputStream("data/encrypted");
FileOutputStream fos = new FileOutputStream("data/decrypted");
SecretKeySpec sks = new SecretKeySpec("yourkey".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[8];
while((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
}

Encrypt first 1024 bytes of file (zip file) and rest remain the same

I am working on some big files and when I will go for the full file encryption/decryption. It is taking too much of time. Now I want to encrypt only first 1024 bytes of file and the rest of the bytes will remain the same.
Here is my code:
static void encrypt(String inputPath, String outputPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException
{
// Here you read the cleartext.
FileInputStream fis = new FileInputStream(inputPath);
// This stream write the encrypted text. This stream will be wrapped by another stream.
FileOutputStream fos = new FileOutputStream(outputPath);
// Length is 16 byte
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
// Create cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
// Wrap the output stream
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
// Write bytes
int b;
int count = 0;
byte[] d = new byte[1024];
while((b = fis.read(d)) != -1) {
if(count <= 1024){
count += b;
cos.write(d, 0, b);
}else{
cos.write(d, 0, b);
}
// cos.write(d, 0, b);
}
// Flush and close streams.
cos.flush();
cos.close();
fis.close();
}
static byte[] decrypt(String inputPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
FileInputStream fis = new FileInputStream(inputPath);
// FileOutputStream fos = new FileOutputStream(outputPath);
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
int b;
byte[] d = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int count =0;
while((b = cis.read(d)) != -1) {
if(count <= 1024){
count += b;
bos.write(d, 0, b);
}else{
bos.write(d, 0, b);
}
}
byte[] completeBytes = bos.toByteArray();
cis.close();
return completeBytes;
}
Please suggest something..
load the first 1024 bytes from the file, encrypt them then write them back. convert this C# code to java for reading the first 1024 bytes:
byte[] chunkData = new byte[];
int chunkSize = 1024;
using(FileStream fsInput = FileStream(PATH TO FileMode.Read)
fsInput.Read(chunkData, 0, chunkSize);

Categories

Resources