Java – String encryption in Android

String encryption in Android… here is a solution to the problem.

String encryption in Android

I encrypted with code encryption. It does not give a string result. Byte arrays are not converted to strings. I tried almost all methods to convert byte array to char but gave no result.

   public class EncryptionTest extends Activity {

EditText input, output, outputDecrypt;
String plain_text;
byte[] key, encrypted_bytes,keyStart,byte_char_text,decrpyted_bytes ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_encryption_test);

input = (EditText) findViewById(R.id.text_inputText);
    output = (EditText) findViewById(R.id.text_Result);
    outputDecrypt = (EditText) findViewById(R.id.text_decrypt_Result);
    Button encrypt_btn = (Button) findViewById(R.id.btn_encrpyt);
    Button decrypt_btn = (Button) findViewById(R.id.btn_Decrypt);

plain_text = input.getText().toString();
    keyStart = "Supriyo".getBytes();
    byte_char_text = plain_text.getBytes();

encrypt_btn.setOnClickListener(new OnClickListener() {

@Override
        public void onClick(View v) {

try {

KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
                sr.setSeed(keyStart);
                keygen.init(128, sr);
                SecretKey skey = keygen.generateKey();
                key = skey.getEncoded();

encrypted_bytes = encrypt(key, byte_char_text);
                String inputResult = encrypted_bytes.toString();
                output.setText(inputResult);
        decrpyted_bytes = decrypt(key, encrypted_bytes);
                     System.out.println("decr"+Arrays.toString(decrpyted_bytes));                                               
            String outputResult = new String(decrpyted_bytes,"UTF-8");
                System.out.println("-->>>"+outputResult);
                outputDecrypt.setText(outputResult);

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();
            } catch (InvalidKeyException e) {
                 TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                 TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                 TODO Auto-generated catch block
                e.printStackTrace();
            } catch (BadPaddingException e) {
                 TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                 TODO Auto-generated catch block
                e.printStackTrace();
            }

}
    });
        }

public static byte[] decrypt(byte[] raw, byte[] encrypteds)
        throws Exception          {

SecretKeySpec skey = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skey);
    byte[] decrypted = cipher.doFinal(encrypteds);
    return decrypted;
}

public 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;
}

@Override
      public boolean onCreateOptionsMenu(Menu menu) {
     Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.encryption_test, menu);
    return true;
}

}

Solution

The code successfully encrypts the string and the XML file in the assests folder.

  import java.io.BufferedReader;
 import java.io.File;
     import java.io.FileInputStream;
     import java.io.FileOutputStream;
     import java.io.FilterWriter;
     import java.io.InputStream;
     import java.io.InputStreamReader;

import javax.crypto.Cipher;
     import javax.crypto.CipherInputStream;
     import javax.crypto.KeyGenerator;
     import javax.crypto.SecretKey;

import android.os.Bundle;
 import android.app.Activity;
 import android.view.Menu;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.EditText;
 import org.apache.commons.codec.binary.Base64;

public class EncryptionTest1 extends Activity {
EditText output, outputDecrypt;
EditText input;
String plainData = "";
String cipherText, decryptedText;
KeyGenerator keyGen;
SecretKey secretKey;

Cipher aesCipher;
FileOutputStream fos;

byte[] byteDataToEncrypt, byteCipherText, byteDecryptedText;
byte[] xmlStream;

@Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_encryption_test1);
    input = (EditText) findViewById(R.id.text_inputText1);
    output = (EditText) findViewById(R.id.text_Result1);
    outputDecrypt = (EditText) findViewById(R.id.text_decrypt_Result1);

Button btn_encrypt = (Button) findViewById(R.id.btn_encrpyt1);

btn_encrypt.setOnClickListener(new OnClickListener() {

@Override
        public void onClick(View v) {

try {
                plainData = input.getText().toString();
                System.out.println("input==>>" + plainData);
                byte[] fileStreams = fileOpening("SaleReport.xml");
                byte[] DataEncrypt = encrypt(fileStreams);
                String DataDecrypt = decrypt(DataEncrypt);

System.out.println("Decrypted Text:===>>" + DataDecrypt);
                outputDecrypt.setText(DataDecrypt);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

});
  }

private byte[] fileOpening(String fileName) throws Exception {
    InputStream is = getAssets().open(fileName);
    int size = is.available();
    xmlStream = new byte[size];
    is.read(xmlStream);
    System.out.println("xmlstream length==>>" + xmlStream.length);
    return xmlStream;
}

private byte[] encrypt(byte[] xmlStream) throws Exception {

keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    secretKey = keyGen.generateKey();
    aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
     byteDataToEncrypt = plainData.getBytes();

byteCipherText = aesCipher.doFinal(xmlStream);
    cipherText = new String(new Base64().encodeBase64(byteCipherText));
    output.setText(cipherText);
    System.out.println(cipherText);

return byteCipherText;

}

public String decrypt(byte[] DataEncrypt) throws Exception {
    aesCipher.init(Cipher.DECRYPT_MODE, secretKey,
    aesCipher.getParameters());
    byteDecryptedText = aesCipher.doFinal(DataEncrypt);
    decryptedText = new String(byteDecryptedText);
    return decryptedText;
  }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
     Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.encryption_test1, menu);
    return true;
}

}

Related Problems and Solutions