AES Padding issue Android - android

When I run the following code in Java the output is a multiple of 128 bits (16 bytes).
The exact same code in Android is no longer a multiple of 16 bytes suggesting that the padding has failed.
Any ideas?
//Compress, Encrypt, Decrypt, Decompress variables
public final static String Secretkey = "###hidden######";
public final static String VectorInitializationKey = "###hidden###";
public final static String transformation = "AES/CFB8/PKCS5Padding";
public static byte[] encryptandCompress(byte[] input)
{
ByteArrayOutputStream ms = new ByteArrayOutputStream();
GZIPOutputStream gos = null; // Added
CipherOutputStream cos= null; // Added
SecretKeySpec skeySpec = new SecretKeySpec(Secretkey.getBytes(), "AES");
Cipher cipher;
try {
cipher = Cipher.getInstance(transformation);
IvParameterSpec iv = new IvParameterSpec(VectorInitializationKey.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
cos = new CipherOutputStream(ms, cipher );
gos= new GZIPOutputStream (cos);
gos.write(input);
gos.close(); // Must be called before we return bytes from ms
cos.close();
byte[] toReturn = ms.toByteArray();
Log.d("FileWriter", "Encrypted and compressed " + input.length + " bytes to " + toReturn.length + " bytes");
Log.d("FileWriter", "Encrypted and compressed " + toReturn.length/16.0 + " blocks written");
return toReturn;
} catch (Exception e) {
Log.e("FileWriter", "Compression failed: " + e.getMessage());
return null;
}
finally
{
try
{
if (gos != null)
{
gos.close();
}
if (cos != null)
{
cos.close();
}
if (ms != null)
{
ms.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Related

Android Passing IV parameters Encryption /Decryption text

I Hope that you can help me related my code.
Im trying to pass parameters IV to Encrypt/ Decryt
Encrypt Funcion:
I try to concatenate text; IV
encryptedText.setText(Base64.encodeToString(vals, Base64.DEFAULT) + ";" + (Base64.encodeToString(encryptionIv, Base64.DEFAULT)));
I think that is working fine , as the image represents.
public void encryptString(String alias) {
try {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
SecretKey secretKey = (SecretKey) keyStore.getKey(alias, null);
String initialText = startText.getText().toString();
if(initialText.isEmpty()) {
Toast.makeText(this, "Enter text in the 'Initial Text'", Toast.LENGTH_LONG).show();
return;
}
Cipher inCipher = Cipher.getInstance("AES/GCM/NoPadding");
inCipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] src= initialText.getBytes("UTF-8");
byte[] iv = inCipher.getIV();
assert iv.length == 12;
byte[] cipherText = inCipher.doFinal(src);
assert cipherText.length == src.length + 16;
byte[] message = new byte[12 + src.length + 16];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(
outputStream, inCipher);
cipherOutputStream.write(src);
cipherOutputStream.close();
byte [] vals = outputStream.toByteArray();
encryptedText.setText(Base64.encodeToString(vals, Base64.DEFAULT));
} catch (Exception e) {
Toast.makeText(this, "Exception " + e.getMessage() + " occurred", Toast.LENGTH_LONG).show();
Log.e(TAG, Log.getStackTraceString(e));
}
}
[![enter image description here][1]][1]
Could you helpme with an example to get decryption works fine?
Thanks for youl help
Updated: Hello , Im trying to pass the IV as the example:
My code here:
public void encryptString(String alias) {
try {
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(alias, null);
RSAPublicKey publicKey = (RSAPublicKey) privateKeyEntry.getCertificate().getPublicKey();
String initialText = startText.getText().toString();
if(initialText.isEmpty()) {
Toast.makeText(this, "Enter text in the 'Initial Text' widget", Toast.LENGTH_LONG).show();
return;
}
Cipher inCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
inCipher.init(Cipher.ENCRYPT_MODE, publicKey);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(
outputStream, inCipher);
cipherOutputStream.write(initialText.getBytes("UTF-8"));
cipherOutputStream.close();
byte [] vals = outputStream.toByteArray();
encryptedText.setText(Base64.encodeToString(vals, Base64.DEFAULT));
} catch (Exception e) {
Toast.makeText(this, "Exception " + e.getMessage() + " occurred", Toast.LENGTH_LONG).show();
Log.e(TAG, Log.getStackTraceString(e));
}
}
[![enter image description here][2]][2]
NEW Updated:
Encryption code
public void encryptString(String alias) {
try {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
SecretKey secretKey = (SecretKey) keyStore.getKey(alias, null);
String initialText = startText.getText().toString();
if(initialText.isEmpty()) {
Toast.makeText(this, "Enter text in the 'Initial Text'", Toast.LENGTH_LONG).show();
return;
}
Cipher inCipher = Cipher.getInstance("AES/GCM/NoPadding");
inCipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] src= initialText.getBytes("UTF-8");
byte[] iv = inCipher.getIV();
assert iv.length == 12;
byte[] cipherText = inCipher.doFinal(src);
assert cipherText.length == src.length + 16;
byte[] message = new byte[12 + src.length + 16];
System.arraycopy(iv, 0, message, 0, 12);
System.arraycopy(cipherText, 0, message, 12, cipherText.length);
//ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//CipherOutputStream cipherOutputStream = new CipherOutputStream(
// outputStream, inCipher);
//cipherOutputStream.write(message);
//cipherOutputStream.close();
//byte [] vals = outputStream.toByteArray();
encryptedText.setText(Base64.encodeToString(message, Base64.DEFAULT));
} catch (Exception e) {
Toast.makeText(this, "Exception " + e.getMessage() + " occurred", Toast.LENGTH_LONG).show();
Log.e(TAG, Log.getStackTraceString(e));
}
}
Decryption code: ( Not working)
public void decryptString(String alias) {
try {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
SecretKey secretKey = (SecretKey) keyStore.getKey(alias, null);
String cipherText = encryptedText.getText().toString();
byte[] src = cipherText.getBytes();
byte[] message = new byte[12 + src.length + 16];
Cipher output = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec params = new GCMParameterSpec(128, message, 0, 12);
output.init(Cipher.DECRYPT_MODE, secretKey, params);
// output.doFinal(message, 12, message.length - 12);
CipherInputStream cipherInputStream = new CipherInputStream(
new ByteArrayInputStream(Base64.decode(cipherText, Base64.DEFAULT)), output);
ArrayList<Byte> values = new ArrayList<>();
int nextByte;
while ((nextByte = cipherInputStream.read()) != -1) {
values.add((byte)nextByte);
}
byte[] bytes = new byte[values.size()];
for(int i = 0; i < bytes.length; i++) {
bytes[i] = values.get(i).byteValue();
}
String finalText = new String(bytes, 0, bytes.length, "UTF-8");
decryptedText.setText(finalText);
} catch (Exception e) {
Toast.makeText(this, "Exception " + e.getMessage() + " occurred", Toast.LENGTH_LONG).show();
Log.e(TAG, Log.getStackTraceString(e));
}
}
Could you help me with the error shows in the image?
[![enter image description here][3]][3]
<<---UPDATED SOLUTION-->
Encript function:
public void encryptString(String alias) {
try {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
SecretKey secretKey = (SecretKey) keyStore.getKey(alias, null);
String initialText = startText.getText().toString();
if(initialText.isEmpty()) {
Toast.makeText(this, "Enter text in the 'Initial Text'", Toast.LENGTH_LONG).show();
return;
}
Cipher inCipher = Cipher.getInstance("AES/GCM/NoPadding");
inCipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] src= initialText.getBytes("UTF-8");
byte[] iv = inCipher.getIV();
assert iv.length == 12;
byte[] cipherText = inCipher.doFinal(src);
assert cipherText.length == src.length + 16;
byte[] message = new byte[12 + src.length + 16];
System.arraycopy(iv, 0, message, 0, 12);
System.arraycopy(cipherText, 0, message, 12, cipherText.length);
encryptedText.setText(Base64.encodeToString(message, Base64.DEFAULT));
} catch (Exception e) {
Toast.makeText(this, "Exception " + e.getMessage() + " occurred", Toast.LENGTH_LONG).show();
Log.e(TAG, Log.getStackTraceString(e));
}
}
Decrypt Function:
public void decryptString(String alias) {
try {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
SecretKey secretKey = (SecretKey) keyStore.getKey(alias, null);
String cipherText = encryptedText.getText().toString();
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
byte[] nonceCiphertextTag = Base64.decode(cipherText, Base64.DEFAULT);
GCMParameterSpec params = new GCMParameterSpec(128, nonceCiphertextTag, 0, 12);
cipher.init(Cipher.DECRYPT_MODE, secretKey, params);
byte[] decrypted = cipher.doFinal(nonceCiphertextTag, 12, nonceCiphertextTag.length - 12);
String finalText = new String(decrypted, 0, decrypted.length, "UTF-8");
decryptedText.setText(finalText);
} catch (Exception e) {
Toast.makeText(this, "Exception " + e.getMessage() + " occurred", Toast.LENGTH_LONG).show();
Log.e(TAG, Log.getStackTraceString(e));
}
}
Thanks a lot for the help #Topaco
In the latest posted encryption code, nonce, ciphertext and tag are concatenated and Base64 encoded, in the following called nonceCiphertextTagB64.
When decrypting
nonceCiphertextTagB64 must first be Base64 decoded to nonceCiphertextTag,
the nonce must be encapsulated in a GCMParameterSpec instance; the nonce are the first 12 bytes of nonceCiphertextTag,
a cipher instance for AES/GCM/NoPadding must be created, which is initialized with the key and the GCMParameterSpec instance in decryption mode,
the concatenation of ciphertext and tag is decrypted; the concatenation of ciphertext and tag is the data after the nonce.
In the following example implementation, with respect to a repro, the 32 bytes key 01234567890123456789012345678901 is used (instead of a key from the key store). The ciphertext was created with the posted code for encryption using the same key and the plaintext The quick brown fox jumps over the lazy dog:
...
String nonceCiphertextTagB64 =
"UpyxMnzPrw+zJGANL4wBbaC+UX5KnMKYwhR0u2iF/GDCcU38YKWlvJp1zJ+mrN0POP7lz9y+eweH\n" +
"vIxAH4R4U3At8T0fVe0=";
SecretKeySpec secretKey = new SecretKeySpec("01234567890123456789012345678901".getBytes(StandardCharsets.UTF_8),"AES");
byte[] nonceCiphertextTag = Base64.decode(nonceCiphertextTagB64, Base64.DEFAULT);
GCMParameterSpec params = new GCMParameterSpec(128, nonceCiphertextTag, 0, 12);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, params);
byte[] decrypted = cipher.doFinal(nonceCiphertextTag, 12, nonceCiphertextTag.length - 12);
System.out.println(new String(decrypted, StandardCharsets.UTF_8)); // The quick brown fox jumps over the lazy dog
...
The output is:
The quick brown fox jumps over the lazy dog

android AES decrypt files: BadPaddingException: EVP_CipherFinal_ex

I am recently working on file encryption / decryption.
BadPaddingException: EVP_CipherFinal_ex: always occurs when I try to decrypt the file with the same key.
Code snippets will be posted below.
Am I doing something wrong?
thank you for your helps.
Encrypt
public static void encryptFile() {
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + TARGET_FILE);
FileInputStream fileInputStream;
FileOutputStream fileOutputStream;
byte[] buffer = new byte[1024 * 8];
IvParameterSpec ivParameterSpec = new IvParameterSpec("1234567890123456".getBytes());
byte[] key = "only for testing".getBytes();
MessageDigest sha;
try {
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
try {
fileInputStream = new FileInputStream(file);
fileOutputStream = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/" + ENCRYPT_FILE);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
//CipherOutputStream cipherOutputStream = new CipherOutputStream(fileOutputStream, cipher);
int read;
while ((read = fileInputStream.read(buffer)) > 0) {
Log.i(TAG, "encrypt read= " + read);
byte[] encryptedData = cipher.doFinal(buffer);
if (encryptedData != null) {
Log.i(TAG, "encrypted size= " + encryptedData.length);
fileOutputStream.write(encryptedData, 0, read);
}
//cipherOutputStream.write(buffer, 0, buffer.length);
}
//cipherOutputStream.flush();
//cipherOutputStream.close();
fileInputStream.close();
fileOutputStream.close();
} catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException
| IllegalBlockSizeException | BadPaddingException
| InvalidAlgorithmParameterException | InvalidKeyException e) {
e.printStackTrace();
}
}
Decrypt
public static void decryptFile() {
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + ENCRYPT_FILE);
FileInputStream fileInputStream;
FileOutputStream fileOutputStream;
byte[] buffer = new byte[1024 * 8];
IvParameterSpec ivParameterSpec = new IvParameterSpec("1234567890123456".getBytes());
byte[] key = "only for testing".getBytes();
MessageDigest sha;
try {
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
key = Arrays.copyOf(key, 16); // use only first 128 bit
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
try {
fileInputStream = new FileInputStream(file);
fileOutputStream = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/" + DECRYPT_FILE);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
//CipherInputStream cipherInputStream = new CipherInputStream(fileInputStream, cipher);
int read;
while ((read = fileInputStream.read(buffer)) > 0) {
Log.i(TAG, "decrypt read= " + read);
byte[] decryptedData = cipher.doFinal(buffer);
if (decryptedData != null) {
Log.i(TAG, "decrypted size= " + decryptedData.length);
fileOutputStream.write(decryptedData, 0, read);
}
//fileOutputStream.write(buffer, 0, buffer.length);
}
fileOutputStream.flush();
fileOutputStream.close();
//cipherInputStream.close();
fileInputStream.close();
} catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException
| IllegalBlockSizeException | BadPaddingException
| InvalidAlgorithmParameterException | InvalidKeyException e) {
e.printStackTrace();
}
}
btw: It will work properly when I use CipherInputStream / CipherOutStream. I want to know if it is possible to use just FileInputStream / FileOutputStream only? thank you.
Edited:
Encrypt function will enlarge byte array about 16 bytes, I've tried increase the buffer size of decryption and still can't get it work.
byte[] buffer = new byte[1024 * 8 + 16];
Log:
I/#_: decrypt read= 8208
javax.crypto.BadPaddingException: EVP_CipherFinal_ex
at com.android.org.conscrypt.NativeCrypto.EVP_CipherFinal_ex(Native Method)
at com.android.org.conscrypt.OpenSSLCipher.doFinalInternal(OpenSSLCipher.java:430)
at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:466)
at javax.crypto.Cipher.doFinal(Cipher.java:1340)
at CryptoHelper.decryptFile(CryptoHelper.java:128)
Edited Update code here based on #Robert's answer for anyone who encountered the same problems like I did.
Encrypt:
int read;
while ((read = fileInputStream.read(buffer)) > 0) {
Log.i(TAG, "encrypt read= " + read);
byte[] encryptedData = cipher.update(buffer, 0, read);
//byte[] encryptedData = cipher.doFinal(buffer);
if (encryptedData != null) {
Log.i(TAG, "encrypted size= " + encryptedData.length);
fileOutputStream.write(encryptedData, 0, encryptedData.length);
}
//cipherOutputStream.write(buffer, 0, buffer.length);
}
byte[] finals = cipher.doFinal();
Log.i(TAG, "encrypted finals = " + finals.length);
fileOutputStream.write(finals, 0, finals.length);
Decrypt:
int read;
while ((read = fileInputStream.read(buffer)) > 0) {
Log.i(TAG, "decrypt read= " + read);
//byte[] decryptedData = cipher.doFinal(buffer);
byte[] decryptedData = cipher.update(buffer, 0, read);
if (decryptedData != null) {
Log.i(TAG, "decrypted size= " + decryptedData.length);
fileOutputStream.write(decryptedData, 0, decryptedData.length);
}
//fileOutputStream.write(buffer, 0, buffer.length);
}
byte[] finals = cipher.doFinal();
Log.i(TAG, "decrypted finals = " + finals.length);
fileOutputStream.write(finals, 0, finals.length);
Thanks again for Robert's help.
You problem is that you are always calling cipher.doFinal() for each block of data which is wrong as each block will be padded.
If you are en/decrypting data block-wise use cipher.update(...) and after the last block has been processed only call cipher.doFinal() once.
The easier way would be to use a CipherInputStream/CipherOutputStream - it does exactly what I have described for you (doFinal is called when you close the stream).

How to set user avatar on openfire user smack api

I am creating a chat application but I could not understand how to set user avatar on openfire server using smack api. i am the below code to set user avatar.
public boolean changeImage(File file) {
if (mConnection == null)
return false;
try {
VCard vcard = new VCard();
String userJID = prefs.getString(Prefrences.xmpp_jid, null);
System.out.println("user:- "+userJID);
vcard.load(mConnection, userJID);
byte[] bytes;
bytes = getFileBytes(file);
String encodedImage = StringUtils.encodeHex(bytes);
vcard.setAvatar(bytes, encodedImage);
vcard.setEncodedImage(encodedImage);
vcard.setField("PHOTO", "<TYPE>image/jpg</TYPE><BINVAL>"
+ encodedImage + "</BINVAL>", true);
System.out.println("Encoded image "+encodedImage);
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++");
ByteArrayInputStream bais = new ByteArrayInputStream(
vcard.getAvatar());
FormatTools.getInstance().InputStream2Bitmap(bais);
vcard.save(mConnection);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* File to byte
*
* #param file
* #return
* #throws java.io.IOException
*/
private byte[] getFileBytes(File file) throws IOException {
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
int bytes = (int) file.length();
byte[] buffer = new byte[bytes];
int readBytes = bis.read(buffer);
if (readBytes != buffer.length) {
throw new IOException("Entire file not read");
}
return buffer;
} finally {
if (bis != null) {
bis.close();
}
}
}
Please Help.
use this code:it might be helpful to you:)
private void loadVCard(XMPPConnection conn, String username) {
VCard vcard = new VCard();
//ProviderManager.addIQProvider("vCard", "vcard-temp", new VCardProvider());
vcard.load(conn, username);
vcard.setFirstName("" + username);
vcard.setEmailHome("" + email);
vcard.setMiddleName("" + middleName);
vcard.setNickName("" + nickName);
vcard.setPhoneHome("Voice", "" + phoneNumber);
vcard.setLastName("" + lastName);
vcard.setOrganization("" + orginiZation);
vcard.setAvatar("" + image_path); //Image Path should be URL or Can be Byte Array etc.
vcard.save(conn);
}

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();
}
}
}

Cipher AES, no error exception, but init not works

i try to cipher but my outputs after "cipher.init" won't output. Also no exceptions..and I don't know why...(new on android)
public void login() {
LoginData loginData = this.fragmentBox.getUpdatedLoginData();
String finishString = new String();
try {
Cipher cipher = Cipher.getInstance("AES");
byte[] output = null;
SecretKeySpec secretKey = new SecretKeySpec(
Globals.ENCRYPTPW.getBytes(), "AES");
System.out.println(secretKey.getEncoded().toString() + "----" + Globals.ENCRYPTPW);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
output = cipher.doFinal(loginData.getPassword().getBytes());
byte[] encryptedUsernameString = Base64.encode(output, 0);
finishString = new String(encryptedUsernameString, "UTF-8");
} catch (InvalidKeyException e) {
e.getStackTrace();
Log.v("Fehler im Code","");
} catch(Exception e){}
System.out.println("Code: " + finishString);
}
any idea?

Categories

Resources