I am encrypting my videos using this link and store it in my application folder. But for large videos say, 2GB, it takes much time to decrypt and then play. so user has to wait for 1.5-2 minutes to decrypt selected video and then play it.
For that, I searched for offline video streaming. And I found this. I have same scenario but instead of downloading, I am encrypting videos from gallery. and I have used different encryption alogithm.
When I tried above link, my connection is lost everytime it goes in while loop. In catch, I get Connection is reset error. Also I didn't get some variables there. like, total, readbyte and pos variables. can anybody please explain?
I really want to decrypt and play videos at the same time. so user experience will be good.
Thank you.
EDIT
Here is my sample code :
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Support.V7.App;
using Java.IO;
using Javax.Crypto;
using Javax.Crypto.Spec;
using System;
using System.IO;
using Java.Net;
using System.Threading.Tasks;
namespace SecretCalc
{
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme",
MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
VideoView video;
Button encrypt, decrypt;
private string sKey = "0123456789abcdef";//key,
private string ivParameter = "1020304050607080";
string path = "/sdcard/Download/";
string destpath = "/sdcard/test/";
string filename = "video1.mp4";
Stream outputStream;
string date = "20180922153533.mp4"; // Already Encrypted File Name
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
video = FindViewById<VideoView>(Resource.Id.videoView);
encrypt = FindViewById<Button>(Resource.Id.btnEncrypt);
decrypt = FindViewById<Button>(Resource.Id.btnDecrypt);
encrypt.Click += Encrypt_Click;
decrypt.Click += Decrypt_ClickAsync;
}
private async void Decrypt_ClickAsync(object sender, EventArgs e)
{
video.SetVideoPath("http://0.0.0.0:9990/");
video.Prepared += Video_Prepared;
await Task.Run(() =>
{
try
{
ServerSocket serverSocket = new ServerSocket();
serverSocket.Bind(new InetSocketAddress("0.0.0.0", 9990));
// this is a blocking call, control will be blocked until client sends the request
Socket finalAccept = serverSocket.Accept();
outputStream = finalAccept.OutputStream;
}
catch (Exception ex)
{
}
});
await Task.Run(() => DecryptThroughSocket());
}
private void Video_Prepared(object sender, EventArgs e)
{
video.Start();
}
private bool DecryptThroughSocket()
{
try
{
byte[] raw = System.Text.Encoding.Default.GetBytes(sKey);
byte[] iv = System.Text.Encoding.Default.GetBytes(ivParameter);
int count = 0, pos = 0, total = 0, readbyte;
byte[] data = new byte[1024 * 1024];
readbyte = data.Length;
long lenghtOfFile = new Java.IO.File(Path.Combine(path, date)).Length();
FileInputStream inputStream = new FileInputStream(Path.Combine(destpath, date));
while ((count = inputStream.Read(data, 0, readbyte)) != -1)
{
if (count < readbyte)
{
if ((lenghtOfFile - total) > readbyte)
{
while (true)
{
int seccount = inputStream.Read(data, pos, (readbyte - pos));
pos = pos + seccount;
if (pos == readbyte)
{
break;
}
}
}
}
// encrypt data read before writing to output stream
byte[] decryptedData = decryptFun(raw, iv, data);
outputStream.Write(decryptedData,0,decryptedData.Length);
}
}
catch (Exception ex)
{
return false;
}
return true;
}
private void Encrypt_Click(object sender, EventArgs e)
{
try
{
FileInputStream inputStream = new FileInputStream(System.IO.Path.Combine(path, filename));
date = DateTime.Now.ToString("yyyyMMddHHmmss") + ".mp4";
DirectoryInfo dir = new DirectoryInfo(destpath);
if (!dir.Exists)
{
Directory.CreateDirectory(destpath);
}
FileOutputStream outputStream = new FileOutputStream(System.IO.Path.Combine(destpath, date));
byte[] raw = System.Text.Encoding.Default.GetBytes(sKey);
byte[] iv = System.Text.Encoding.Default.GetBytes(ivParameter);
int count = 0, pos = 0, total = 0, readbyte;
byte[] data = new byte[1024 * 1024];
readbyte = data.Length;
long lenghtOfFile = new Java.IO.File(Path.Combine(path, filename)).Length();
while ((count = inputStream.Read(data, 0, readbyte)) != -1)
{
if (count < readbyte)
{
if ((lenghtOfFile - total) > readbyte)
{
while (true)
{
int seccount = inputStream.Read(data, pos, (readbyte - pos));
pos = pos + seccount;
if (pos == readbyte)
{
break;
}
}
}
}
total += count;
// encrypt data read before writing to output stream
byte[] encryptedData = encryptFun(raw, iv, data);
outputStream.Write(encryptedData);
}
}
catch (Exception ex)
{
}
}
public static byte[] encryptFun(byte[] key, byte[] iv, byte[] clear)
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.GetInstance("AES/CTR/NoPadding");
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.Init(CipherMode.EncryptMode, skeySpec, ivspec);
byte[] encrypted = cipher.DoFinal(clear);
return encrypted;
}
public static byte[] decryptFun(byte[] key, byte[] iv, byte[] encrypted)
{
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.GetInstance("AES/CTR/NoPadding");
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.Init(CipherMode.DecryptMode, skeySpec, ivspec);
byte[] decrypted = cipher.DoFinal(encrypted);
return decrypted;
}
}
}
Related
I am trying to get File Decryption working in Android. The file i have has been encrypted from python using Crypto.Cipher AES: full code:
import os, binascii, struct
from Crypto.Cipher import AES
def encrypt_file():
chunksize=64*1024
iv = "96889af65c391c69"
k1 = "cb3a44cf3cb120cc7b8b3ab777f2d912"
file = "tick.png"
out_filename = "entick.png"
dir = os.path.dirname(__file__)+"\\"
print(iv)
encryptor = AES.new(key, AES.MODE_CBC, iv)
in_filename = dir+file
filesize = os.path.getsize(in_filename)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
outfile.write(struct.pack('<Q', filesize))
outfile.write(iv)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += ' ' * (16 - len(chunk) % 16)
outfile.write(encryptor.encrypt(chunk))
if __name__ == "__main__":
encrypt_file()
Android Decryption function (main):
private static File main(String fname, File enfile, String IV, String key) {
try {
byte[] bkey = key.getBytes("UTF-8");
byte[] bIV = IV.getBytes("UTF-8");
Log.d("ByteLen","bkey:"+Integer.toString(bkey.length));
Log.d("ByteLen","bIV:"+ Integer.toString(bIV.length));
File aesFile;
aesFile = enfile;
Log.d("AESFILELENGTH", "aes length: " + aesFile.length());
File aesFileBis = new File(String.valueOf(Environment.getExternalStorageDirectory().toPath()), "tick.png"); //to be replaced with fname
FileInputStream fis;
FileOutputStream fos;
CipherInputStream cis;
SecretKeySpec secretKey = new SecretKeySpec(bkey, "AES");
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(bIV);
decrypt.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
fis = new FileInputStream(aesFile);
cis = new CipherInputStream(fis, decrypt);
fos = new FileOutputStream(aesFileBis);
try {
byte[] mByte = new byte[8];
int i = cis.read(mByte);
Log.i("MBYTE", "mbyte i: " + i);
while (i != -1) {
fos.write(mByte, 0, i);
i = cis.read(mByte);
}
} catch (IOException e) {
e.printStackTrace();
}
fos.flush();
fos.close();
cis.close();
fis.close();
return aesFileBis;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
The Crypto.Cipher module inserts the IV into the file as bytes 8-24 so i created this method to extract them:
private String IV(File enfile) throws UnsupportedEncodingException, FileNotFoundException {
int size = 24;
byte bytes[] = new byte[size];
byte tmpBuff[] = new byte[size];
if(enfile.canRead()){
//run decryption code
FileInputStream fis= new FileInputStream(enfile);
try {
int read = fis.read(bytes, 0, size);
if (read < size) {
int remain = size - read;
while (remain > 0) {
read = fis.read(tmpBuff, 0, remain);
System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
remain -= read;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
String IV = new String(bytes, "US-ASCII");
IV = IV.substring(8,24);
return IV;
}
From the Decrypt function i have checked and verified the key is 32 bytes long and the iv is 16 bytes long and both are the correct IV and Key. I know I am switching from a byte array to string and back again but that's just for testing.
I have looked at a few posts regarding this issue and so far have only found posts relating to the key being the wrong byte size or for decrpyting Strings and not files and therefor switching base64 encoding doesn't seem to apply. I think the issue is to do with the way Crypto.Cipher is padding the files as the first 8 byes look like junk (SO and NULL bytes) then there are 16 bytes of IV.
Thanks to the comment i added the Padding module from crypto: https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/Padding.py
im my python code i added:
from Crypto.Util.py3compat import * #solves bchr error
i also copied the pad() function from the Padding.py to the end of my code.
in the file writing function:
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
outfile.write(iv) ##IV becomes the first 16 bytes, not using struct.pack() anymore
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += ' ' * (16 - len(chunk) % 16)
outfile.write(encryptor.encrypt(pad(chunk, 16))) ##added padding here
Finally in the Java code i removed the IV finder function and updated the main function:
private static File main(String fname, File enfile, String key) {
try {
FileInputStream fis;
File aesFile;
aesFile = enfile;
byte[] bkey = key.getBytes("UTF-8");
fis = new FileInputStream(aesFile);
byte[] IV = new byte[16];
for(Integer i =0; i < 16; i++){
IV[i] = (byte) fis.read();
}
Log.e("IV:",""+new String(IV, "US-ASCII"));
Log.d("ByteLen","bkey:"+Integer.toString(bkey.length));
Log.d("ByteLen","bIV:"+ Integer.toString(IV.length));
aesFile = enfile;
Log.d("AESFILELENGTH", "aes length: " + aesFile.length());
File aesFileBis = new File(String.valueOf(Environment.getExternalStorageDirectory().toPath()), "file.png"); //to be replaced with fname
FileOutputStream fos;
CipherInputStream cis;
SecretKeySpec secretKey = new SecretKeySpec(bkey, "AES");
Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(IV);
decrypt.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
cis = new CipherInputStream(fis, decrypt);
fos = new FileOutputStream(aesFileBis);
try {
byte[] mByte = new byte[8];
int i = cis.read(mByte);
Log.i("MBYTE", "mbyte i: " + i);
while (i != -1) {
fos.write(mByte, 0, i);
i = cis.read(mByte);
}
} catch (IOException e) { e.printStackTrace();}
fos.flush();
fos.close();
cis.close();
fis.close();
return aesFileBis;
}catch(Exception e) {e.printStackTrace(); }
return null;
}
The new parts of the code take the first 16 bytes from the FileInputStream and puts them into a byte array to be used as the IV, the rest are then decrypted using CBC/PKCS5Padding.
Hope this answer can be useful for anyone else.
I wanna encrypt the string with secret key and Iv. But i am not getting correct encryption. can any one tell me how to do this.
My string is abc but when decrypt the string it is contain special charaters in this.
i followed this link:
https://www.cuelogic.com/blog/using-cipher-to-implement-cryptography-in-android/
package com.reshhhjuuitos.mhhhkoiyrestos.footer;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MCrypt {
private String iv = "1234567890123456"; // Dummy iv (CHANGE IT!)
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;
private String SecretKey = "1&BZ6pqSu1w2%7!8w0oQHJ7FF79%+MO2";
public MCrypt() {
ivspec = new IvParameterSpec(iv.getBytes());
keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
try {
//cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
public byte[] encrypt(String text) throws Exception {
if (text == null || text.length() == 0)
throw new Exception("Empty string");
byte[] encrypted = null;
try {
// Cipher.ENCRYPT_MODE = Constant for encryption operation mode.
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
encrypted = cipher.doFinal(padString(text).getBytes("UTF-8"));
} catch (Exception e) {
throw new Exception("[encrypt] " + e.getMessage());
}
return encrypted;
}
private static String padString(String source) {
char paddingChar = 0;
int size = 16;
int x = source.length() % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++) {
source += paddingChar;
}
return source;
}
public static byte[] hexToBytes(String str) {
if (str == null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i = 0; i < len; i++) {
buffer[i] = (byte) Integer.parseInt(
str.substring(i * 2, i * 2 + 2), 16);
}
return buffer;
}
}
public static String byteArrayToHexString(byte[] array) {
StringBuffer hexString = new StringBuffer();
for (byte b : array) {
int intVal = b & 0xff;
if (intVal < 0x10)
hexString.append("0");
hexString.append(Integer.toHexString(intVal));
}
return hexString.toString();
}
public byte[] decrypt(String text) throws Exception {
if (text == null || text.length() == 0)
throw new Exception("Empty string");
byte[] decrypted = null;
try {
// Cipher.DECRYPT_MODE = Constant for decryption operation mode.
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
decrypted = cipher.doFinal(hexToBytes(text));
} catch (Exception e) {
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}
}
MainACTVITIY.JAVA
MCrypt mycrypt = new MCrypt();
String dummyStr = "abc";
try {
String encryptedStr = mycrypt.byteArrayToHexString(mycrypt.encrypt(dummyStr));
String decryptedStr = new String(mycrypt.decrypt(encryptedStr));
Log.v("Tag_en",""+encryptedStr);
Log.v("Tag_de",""+decryptedStr);
} catch (Exception e) {
e.printStackTrace();
}
output:Tag_en:5b49ac218b93ee5315c25a0e40b3e9de42e6ecadf0827062b22d4421da99dc5a
Tag_de: abc��������������������������
Okay, I thought it might be your hex encode/decode, but they work. So I wrote some quick encryption and tested it against your class.
The problem is your padding. I don't understand why you are padding your string to length 16, but it is the null characters you have appended to your string that are unprintable. So either don't pad the string, or strip the padding nulls during decryption to rebuild the exact string you encrypted.
For clarity, maintainability and re-usability, you should really do just one clear logical operation in each of your methods, i.e. padding should be done before you pass the string to the encryption method, so the encryption method just encrypts.
You could use functions like these:
private static 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 static 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;
}
And invoke them like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object
byte[] b = baos.toByteArray();
byte[] keyStart = "this is a key".getBytes();
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(keyStart);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();
// encrypt
byte[] encryptedData = encrypt(key,b);
// decrypt
byte[] decryptedData = decrypt(key,encryptedData);
This should work, I use similar code in a project right now.
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();
}
}
}
Hi I am getting the following exception, when decrypting a file on Android based on user supplied password:
Caused by: java.lang.ArrayIndexOutOfBoundsException: src.length=1024 srcPos=1008 dst.length=16 dstPos=16 length=16
at java.lang.System.arraycopy(Native Method)
at com.android.org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.processBytes(PaddedBufferedBlockCipher.java:221)
at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$BufferedGenericBlockCipher.processBytes(BaseBlockCipher.java:882)
at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineUpdate(BaseBlockCipher.java:674)
at javax.crypto.Cipher.update(Cipher.java:893)
at javax.crypto.CipherOutputStream.write(CipherOutputStream.java:95)
It happens randomly and from the crash reports on Google Play Store only on Android 4+. It used to work on older versions.
My Crypto wrapper:
private static final String KEY_FACTORY_ALGORITHM = "PBEWITHSHAAND128BITAES-CBC-BC";
private static final String KEY_ALGORITHM = "AES";
private static final String CIPHER_PROVIDER = "AES";
public Crypto(String password, byte[] salt) {
if (TextUtils.isEmpty(password)) {
throw new IllegalArgumentException(
"password cannot be null or empty.");
}
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 20,
128);
SecretKeyFactory factory;
try {
factory = SecretKeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
PBEKey key = (PBEKey) factory.generateSecret(keySpec);
this.createKeyAndCipher(key.getEncoded());
} catch (Exception e) {
Log.e(this.getClass().getName(), Log.getStackTraceString(e));
throw new RuntimeException(e);
}
}
private void createKeyAndCipher(byte[] keyData)
throws NoSuchAlgorithmException, NoSuchPaddingException {
_secretKey = new SecretKeySpec(keyData, KEY_ALGORITHM);
_cipher = Cipher.getInstance(CIPHER_PROVIDER);
}
And the function that does decryption:
public void decrypt(InputStream input, OutputStream output)
throws Throwable {
_cipher.init(Cipher.DECRYPT_MODE, _secretKey);
this.encryptDecrypt(input, output);
}
public void encryptDecrypt(InputStream input, OutputStream output) throws Throwable {
final int BUFFER_SIZE = 1024;
CipherOutputStream cipherStream = new CipherOutputStream(output,
_cipher);
byte[] buffer = new byte[BUFFER_SIZE];
int count = -1;
while ((count = input.read(buffer)) != -1) {
cipherStream.write(buffer, 0, count);
}
input.close();
cipherStream.close();
}
Did something change in Android 4 version of Boucycastle?
Any hints greatly appreciated.
Thank you.
UPDATE:
Changed the code to this:
public void encryptDecrypt(InputStream input, OutputStream output) {
final int BUFFER_SIZE = 1024;
try {
byte[] buffer = new byte[BUFFER_SIZE];
int count = -1;
while ((count = input.read(buffer)) != -1) {
byte[] result = null;
if (count == BUFFER_SIZE) {
result = _cipher.update(buffer, 0, count);
} else {
result = _cipher.doFinal(buffer, 0, count);
}
if (result != null) {
output.write(result);
}
}
input.close();
output.close();
} catch (Exception e) {
Log.e(this.getClass().getName(), Log.getStackTraceString(e));
throw new RuntimeException(e);
}
}
Now I'm getting
javax.crypto.BadPaddingException: pad block corrupted
One thing should be noted: This ONLY happens when I try to decrypt the file. Short byte[] from sqlite decrypted by _cipher.doFinal(arra) works fine with the same key.
Also, in the original error at the beginning of the post,
dst.length=16 dstPos=16 length=16
I have read something somewhere about AES and data being shorter then 16.
I want to encrypt / decrypt files ( of reasonable size ). I have my code working corrects using AES/CBC/PKCS5Padding . The problem is that it takes really long time to encrypt big files. SO now I am planning to use openSSL.
Is there a link that explains how to use openssl from a java app? How can I integrate it to my java app?
Thanks a lot for any links / points in this regard.
Thanks for your help and time
My code using BC:
public class BouncyCastleProvider_AES_CBC {
public Cipher encryptcipher, decryptCipher;
String TAG = "DataEncryptDecrypt";
private static final String RANDOM_ALGORITHM = "SHA1PRNG";
// The default block size
public static int blockSize = 16;
// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[blockSize]; //input buffer
byte[] obuf = new byte[512]; //output buffer
// The key
byte[] key = null;
// The initialization vector needed by the CBC mode
byte[] IV = null;
public BouncyCastleProvider_AES_CBC(String passwd){
//for a 192 key you must install the unrestricted policy files
// from the JCE/JDK downloads page
key =passwd.getBytes();
key = "SECRETSECRET_1SE".getBytes();
Log.i( "SECRETSECRET_1SECRET_2", "length"+ key.length);
//default IV value initialized with 0
IV = new byte[blockSize];
InitCiphers();
}
public BouncyCastleProvider_AES_CBC(String pass, byte[] iv){
//get the key and the IV
IV = new byte[blockSize];
System.arraycopy(iv, 0 , IV, 0, iv.length);
}
public BouncyCastleProvider_AES_CBC(byte[] pass, byte[]iv){
//get the key and the IV
key = new byte[pass.length];
System.arraycopy(pass, 0 , key, 0, pass.length);
IV = new byte[blockSize];
System.arraycopy(iv, 0 , IV, 0, iv.length);
}
public void InitCiphers()
{
try {
//1. create the cipher using Bouncy Castle Provider
encryptcipher =
Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
//2. create the key
SecretKey keyValue = new SecretKeySpec(key,"AES");
//3. create the IV
AlgorithmParameterSpec IVspec = new IvParameterSpec(IV);
//4. init the cipher
encryptcipher.init(Cipher.ENCRYPT_MODE, keyValue, IVspec);
encryptcipher.getOutputSize(100);
//1 create the cipher
decryptCipher =
Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
//2. the key is already created
//3. the IV is already created
//4. init the cipher
decryptCipher.init(Cipher.DECRYPT_MODE, keyValue, IVspec);
}
catch(Exception ex) {
ex.printStackTrace();
}
}
public String encryptData(String inputFileName) {
String outFilename = null;
File inputFile = new File(inputFileName);
try {
// step 3 - not needed, as we have all the blocks on hand
// step 4 - call doFinal()
outFilename = ".".concat(CommonUtils.getHash(inputFile.getName()));
InputStream fis;
OutputStream fos;
fis = new BufferedInputStream(new FileInputStream(inputFileName));
fos = new BufferedOutputStream(new FileOutputStream(
inputFile.getParent() + "/" + outFilename));
Log.i(TAG, "Output path:" + inputFile.getParent() + "/" + outFilename);
int bufferLength = (inputFile.length()>10000000?10000000:1000);
byte[] buffer = new byte[bufferLength];
int noBytes = 0;
byte[] cipherBlock = new byte[encryptcipher
.getOutputSize(buffer.length)];
int cipherBytes;
while ((noBytes = fis.read(buffer)) != -1) {
cipherBytes = encryptcipher.update(buffer, 0, noBytes,
cipherBlock);
fos.write(cipherBlock, 0, cipherBytes);
}
// always call doFinal
cipherBytes = encryptcipher.doFinal(cipherBlock, 0);
fos.write(cipherBlock, 0, cipherBytes);
// close the files
fos.close();
fis.close();
Log.i("encrpty", "done");
inputFile.delete();
}
catch (Exception ex) {
ex.printStackTrace();
}
return inputFile.getParent() + "/" + outFilename;
}
public void decryptData(String inputFileName, String outputFileName) {
InputStream fis;
OutputStream fos;
try {
fis = new BufferedInputStream(new FileInputStream(
inputFileName));
fos = new BufferedOutputStream(new FileOutputStream(
outputFileName));
byte[] buffer = new byte[blockSize*100];
int noBytes = 0;
byte[] cipherBlock = new byte[decryptCipher
.getOutputSize(buffer.length)];
int cipherBytes;
while ((noBytes = fis.read(buffer)) != -1) {
cipherBytes = decryptCipher.update(buffer, 0, noBytes,
cipherBlock);
fos.write(cipherBlock, 0, cipherBytes);
}
// allways call doFinal
cipherBytes = decryptCipher.doFinal(cipherBlock, 0);
fos.write(cipherBlock, 0, cipherBytes);
// close the files
fos.close();
fis.close();
new File(inputFileName).delete();
Log.i("decrypt", "done");
} catch (Exception ex) {
ex.printStackTrace();
}
}
public byte[] generateSalt() {
byte[] salt = new byte[16];
try {
SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM);
random.nextBytes(salt);
}
catch(Exception ex) {
ex.printStackTrace();
}
return salt;
}
}
The Guardian Project has build files for Android. Once you build it, you need write a simple JNI wrapper that does the encryption/decryption using OpenSSL APIs (EVP, etc), then call this from your app. You need to include he openssl and your JNI wrapper in the app and load them on startup using System.loadLibrary().
https://github.com/guardianproject/openssl-android
Additionally:
don't derive a password from a string directly, use a proper derivation algorithm.
don't use a fixed IV, especially all zeros