AES 128位加密无法正常工作

时间:2013-03-12 09:00:16

标签: android encryption aes

我正在尝试为Android实施AES 128位加密。在cipher.doFinal上,进程停止。它也没有进入catch区块。附上了代码。

public class MainActivity extends Activity {

  EditText encryptText;
  Button encryptButton;
  String key = "16bitkey";
  String requestData;

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

  public void initViews(){

    encryptText = (EditText) findViewById(R.id.encryptText);
    encryptButton = (Button) findViewById(R.id.encryptButton);
    encryptButton.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View arg0) {
        // TODO Auto-generated method stub
        new event_background().execute();
      }
    });
  }


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

  public void performSocketRequest(){
    try{
      requestData = encryptText.getText().toString();
      byte[] keyInBytes = convertToByteArray(key);
      byte[] requestInBytes = convertToByteArray(requestData);
      byte[] aesEncryptedData = aesEncryption(keyInBytes, requestInBytes);
    }
    catch(Exception e){
    }
  }

  public byte[] convertToByteArray(String data){

    byte[] bytes = null;
    try{
      bytes = data.getBytes("UTF8");
    }catch(Exception e){

    }
    return bytes;
  }

  public byte[] aesEncryption(byte[] raw, byte[] clear) throws Exception{

    try{

      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
      sr.setSeed(raw);
      kgen.init(128, sr);
      SecretKey skey = kgen.generateKey();
      byte[] keyTemp = skey.getEncoded(); 
      byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
      IvParameterSpec ivspec = new IvParameterSpec(iv);

      SecretKeySpec skeySpec = new SecretKeySpec(keyTemp, "AES");
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
      return cipher.doFinal(clear);

    }catch(IllegalBlockSizeException e){
      Log.e("*********** IllegalBlockSizeException error **************", e.getMessage());
    }catch(BadPaddingException e){          
      Log.e("*********** BadPaddingException error **************", e.getMessage());          
    }catch(Exception e){          
      Log.e("*********** error **************", e.getMessage());
    }

    return null;
  }

  class event_background extends AsyncTask<Void, String, Void> {

    @Override
    protected void onPreExecute() {
      super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Void unused) {
    }

    @Override
    protected Void doInBackground(Void... params) {
      // TODO Auto-generated method stub
      performSocketRequest();
      return null;
    }
  }
}

1 个答案:

答案 0 :(得分:0)

归档加密/解密的另一种方法:

用法

加密:

 MCrypt mcrypt = new MCrypt();
 String encrypted = MCrypt.bytesToHex(mcrypt.encrypt("Text to Encrypt"));

解密:

MCrypt mcrypt = new MCrypt();
String decrypted = new String(mcrypt.decrypt(encrypted));

类代码:(在2.1+设备上测试并运行。未在4+以上测试但应该可以工作)

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 = "fedcba9876543210";//Dummy iv (CHANGE IT!)
    private IvParameterSpec ivspec;
    private SecretKeySpec keyspec;
    private Cipher cipher;
    private String SecretKey = "0123456789abcdef";//Dummy secretKey (CHANGE IT!)

    public MCrypt() {
        ivspec = new IvParameterSpec(iv.getBytes());

        keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");

        try {
            cipher = Cipher.getInstance("AES/CBC/NoPadding");
        } 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;

        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

        encrypted = cipher.doFinal(padString(text).getBytes());
        try { //  for OS version 2.2+
            encrypted = android.util.Base64.encode(encrypted, android.util.Base64.NO_PADDING);
        } catch (NoClassDefFoundError e) {
            encrypted = org.apache.commons.codec.binary.Base64.encodeBase64(encrypted);
        }

        return encrypted;
    }

    public byte[] decrypt(String code) throws Exception {
        if (code == null || code.length() == 0) throw new Exception("Empty string");

        byte[] decrypted = null;

        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

        try { // for OS version 2.2+
            decrypted = cipher.doFinal(android.util.Base64.decode(code, android.util.Base64.NO_PADDING));
        } catch (NoClassDefFoundError e) {
            decrypted = cipher.doFinal(org.apache.commons.codec.binary.Base64.decodeBase64(code.getBytes("UTF-8")));
        }
        return decrypted;
    }



    private static String padString(String source) {
        char paddingChar = ' ';
        int size = 16;
        int x = source.length() % size;
        int padLength = size - x;

        for (int i = 0; i < padLength; i++) {
            source += paddingChar;
        }

        return source;
    }
}

相关链接:http://www.androidsnippets.com/encrypt-decrypt-between-android-and-php