4

I am using the code for encryption and encryption. Its not giving the string result. The byte array is not converting to string. I tried everything almost to convert the byte array to char but its not giving the 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;
}

    }
5
  • Not sure if that is what you are referring to but System.out.println("decryption-->>" + decrpyted_bytes); should probably be System.out.println("decryption-->>" + Arrays.toString(decrpyted_bytes));. Commented Dec 29, 2013 at 11:37
  • Well, you appear to have overlooked new String(bytes[])... Commented Dec 29, 2013 at 11:37
  • i tried it ....new String(decrpyted_bytes) Commented Dec 29, 2013 at 11:42
  • OK, so always extract the encryption/decryption code from your GUI code. Then test separately. Using defaults is not a good idea, especially Cipher.getInstance("AES") will default to ECB mode encryption. You should use at least "AES/CBC/PKCS5Padding" mode for strings. Commented Dec 29, 2013 at 12:14
  • nosuchalgorithm exception:keygenerator Commented Dec 29, 2013 at 12:29

2 Answers 2

5

The Code is successfully Encrypting the String As well as the Xml file from 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;
}

   }
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is that plain_text will always be equals to "", since you initialize it in onCreate, and thus your EditText is empty at that moment.

Move this in your onClick method :

plain_text = input.getText().toString();
byte_char_text = plain_text.getBytes();


Also as pointed out in comments :

  1. System.out.println("decryption-->>" + decrpyted_bytes); won't give you much informations about the content of your array. So use Arrays.toString to see its content.
  2. new String(bytes[]) will be useful to create the String using the decrpyted_bytes array, to see if the encryption/decryption has worked.

5 Comments

i made some changes in the code according to your suggestions..but still not showing the result.i am editing with the new code.plz help
I would never rely on the default character encoding unless it is required for interoperability with the rest of the system (and even then it is probably best to just use UTF-8). Try and use StandardCharsets.UTF_8
@user3099258 What's the difference between the original post ?
System.out.println("decr"+Arrays.toString(decrpyted_bytes)); String outputResult = new String(decrpyted_bytes,"UTF-8");
the problem is solved.the string as well as i am able to encrypt as well as decrypt the string as well as my android file.Should i post the new code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.