在Android中字符串加密 [英] String Encryption in Android

查看:138
本文介绍了在Android中字符串加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是code加密和加密。它不给字符串结果。该字节数组不转换为字符串。我什么都试过几乎到了字节数组为char转换,但它不是给人造成的。

 公共类EncryptionTest延伸活动{EditText上输入,输出,outputDecrypt;
串plain_text;
字节[]键,encrypted_bytes,keyStart,byte_char_text,decrpyted_bytes;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_encryption_test);    输入=(EditText上)findViewById(R.id.text_inputText);
    输出=(EditText上)findViewById(R.id.text_Result);
    outputDecrypt =(EditText上)findViewById(R.id.text_decrypt_Result);
    按钮encrypt_btn =(按钮)findViewById(R.id.btn_encrpyt);
    按钮decrypt_btn =(按钮)findViewById(R.id.btn_Decrypt);    plain_text = input.getText()的toString()。
    keyStart =Supriyo.getBytes();
    byte_char_text = plain_text.getBytes();    encrypt_btn.setOnClickListener(新OnClickListener(){        @覆盖
        公共无效的onClick(视图v){
            尝试{            的KeyGenerator凯基= KeyGenerator.getInstance(AES);
            SecureRandom的SR = SecureRandom.getInstance(SHA1PRNG);
                sr.setSeed(keyStart);
                keygen.init(128,SR);
                SecretKey的SKEY = keygen.generateKey();
                关键= skey.getEn codeD();                encrypted_bytes =加密(键,byte_char_text);
                串inputResult = encrypted_bytes.toString();
                output.setText(inputResult);
        decrpyted_bytes =解密(键,encrypted_bytes);
                     的System.out.println(DECR+ Arrays.toString(decrpyted_bytes));
            字符串outputResult =新的String(decrpyted_bytes,UTF-8);
                的System.out.println( - >>>中+ outputResult);
                outputDecrypt.setText(outputResult);            }赶上(抛出:NoSuchAlgorithmException E){                e.printStackTrace();
            }赶上(InvalidKeyException将E){
                // TODO自动生成catch块
                e.printStackTrace();
            }赶上(NoSuchPaddingException E){
                // TODO自动生成catch块
                e.printStackTrace();
            }赶上(IllegalBlockSizeException E){
                // TODO自动生成catch块
                e.printStackTrace();
            }赶上(BadPaddingException E){
                // TODO自动生成catch块
                e.printStackTrace();
            }赶上(例外五){
                // TODO自动生成catch块
                e.printStackTrace();
            }        }
    });
        }公共静态的byte []解密(字节[]生,字节[] encrypteds)
        抛出异常{    SecretKeySpec SKEY =新SecretKeySpec(生,AES);
    密密码= Cipher.getInstance(AES);
    cipher.init(Cipher.DECRYPT_MODE,SKEY);
    字节[]解密= cipher.doFinal(encrypteds);
    返回解密;
}公共静态的byte []加密(字节[]生,字节[]清)
        抛出异常{    SecretKeySpec skeySpec =新SecretKeySpec(生,AES);
    密密码= Cipher.getInstance(AES);
    cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
    字节的加密[] = cipher.doFinal(清晰);    返回加密;
}     @覆盖
      公共布尔onCreateOptionsMenu(菜单菜单){
    //充气菜单;如果是present这增加了项目操作栏。
    。getMenuInflater()膨胀(R.menu.encryption_test,菜单);
    返回true;
}    }


解决方案

在code被成功加密的字符串以及从资产产生文件夹中的XML文件。

 进口java.io.BufferedReader中;
 进口的java.io.File;
     进口java.io.FileInputStream中;
     进口java.io.FileOutputStream中;
     进口java.io.FilterWriter中;
     进口的java.io.InputStream;
     进口java.io.InputStreamReader中;     进口javax.crypto.Cipher中;
     进口javax.crypto.CipherInputStream中;
     进口javax.crypto.KeyGenerator;
     进口javax.crypto.SecretKey; 进口android.os.Bundle;
 进口android.app.Activity;
 进口android.view.Menu;
 进口android.view.View;
 进口android.view.View.OnClickListener;
 进口android.widget.Button;
 进口android.widget.EditText;
 进口org.apache.commons codec.binary.Base64。  公共类EncryptionTest1延伸活动{
输出的EditText,outputDecrypt;
的EditText输入;
串plainData =;
串密文,decryptedText;
注册机的KeyGenerator;
SecretKey的SecretKey的;密码aesCipher;
FileOutputStream中FOS;字节[] byteDataToEncrypt,byteCipherText,byteDecryptedText;
字节[] xmlStream;@覆盖
   保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_encryption_test1);
    输入=(EditText上)findViewById(R.id.text_inputText1);
    输出=(EditText上)findViewById(R.id.text_Result1);
    outputDecrypt =(EditText上)findViewById(R.id.text_decrypt_Result1);    按钮btn_encrypt =(按钮)findViewById(R.id.btn_encrpyt1);    btn_encrypt.setOnClickListener(新OnClickListener(){        @覆盖
        公共无效的onClick(视图v){            尝试{
                plainData = input.getText()的toString()。
                的System.out.println(输入==>>中+ plainData);
                字节[] =文件流fileOpening(SaleReport.xml);
                字节[] = DataEncrypt加密(文件流);
                字符串DataDecrypt =解密(DataEncrypt);            的System.out.println(解密文本:===>>中+ DataDecrypt);
                outputDecrypt.setText(DataDecrypt);
            }赶上(例外五){
                e.printStackTrace();
            }
        }    });
  }私人字节[] fileOpening(字符串文件名)抛出异常{
    InputStream为= getAssets()打开(文件名)。
    INT大小= is.​​available();
    xmlStream =新的字节[大小]
    is.read(xmlStream);
    的System.out.println(xmlstream长度==>>中+ xmlStream.length);
    返回xmlStream;
}私人字节[]加密(字节[] xmlStream)抛出异常{    凯基= 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);
    密文=新的String(新的Base64()带codeBase64(byteCipherText));
    output.setText(密文);
    的System.out.println(密文);    返回byteCipherText;}公共字符串解密(字节[] DataEncrypt)抛出异常{
    aesCipher.init(Cipher.DECRYPT_MODE,SecretKey的,
    aesCipher.getParameters());
    byteDecryptedText = aesCipher.doFinal(DataEncrypt);
    decryptedText =新的String(byteDecryptedText);
    返回decryptedText;
  }@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
    //充气菜单;如果是present这增加了项目操作栏。
    。getMenuInflater()膨胀(R.menu.encryption_test1,菜单);
    返回true;
}   }

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

    }

解决方案

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

   }

这篇关于在Android中字符串加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆