本文介绍了AES 128位加密不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现Android的AES 128位加密。在cipher.doFinal过程被停止。它不进入catch块也。已附上code。

 公共类MainActivity延伸活动{  的EditText encryptText;
  按钮encryptButton;
  字符串键=16bitkey;
  字符串的RequestData;  @覆盖
  保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    initViews();
  }  公共无效initViews(){    encryptText =(EditText上)findViewById(R.id.encryptText);
    encryptButton =(按钮)findViewById(R.id.encryptButton);
    encryptButton.setOnClickListener(新OnClickListener(){      @覆盖
      公共无效的onClick(查看为arg0){
        // TODO自动生成方法存根
        新event_background()执行();
      }
    });
  }
  @覆盖
  公共布尔onCreateOptionsMenu(菜单菜单){
    //充气菜单;如果是present这增加了项目操作栏。
    。getMenuInflater()膨胀(R.menu.main,菜单);
    返回true;
  }  公共无效performSocketRequest(){
    尝试{
      。=的RequestData encryptText.getText()的toString();
      字节[] = keyInBytes convertToByteArray(键);
      字节[] = requestInBytes convertToByteArray(的RequestData);
      字节[] = aesEncryptedData aesEncryption(keyInBytes,requestInBytes);
    }
    赶上(例外五){
    }
  }  公众的byte [] convertToByteArray(字符串数据){    字节[]字节= NULL;
    尝试{
      字节= data.getBytes(UTF8);
    }赶上(例外五){    }
    返回字节;
  }  公众的byte [] aesEncryption(字节[]生,字节[]清)抛出异常{    尝试{      的KeyGenerator kgen = KeyGenerator.getInstance(AES);
      SecureRandom的SR = SecureRandom.getInstance(SHA1PRNG);
      sr.setSeed(生);
      kgen.init(128,SR);
      SecretKey的SKEY = kgen.generateKey();
      字节[] = keyTemp skey.getEn codeD();
      字节[] IV = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
      IvParameterSpec ivspec =新IvParameterSpec(IV);      SecretKeySpec skeySpec =新SecretKeySpec(keyTemp,AES);
      密密码= Cipher.getInstance(AES / CBC / PKCS5Padding);
      cipher.init(Cipher.ENCRYPT_MODE,skeySpec,ivspec);
      返回cipher.doFinal(清晰);    }赶上(IllegalBlockSizeException E){
      Log.e(*********** IllegalBlockSizeException错误**************,e.getMessage());
    }赶上(BadPaddingException E){
      Log.e(*********** BadPaddingException错误**************,e.getMessage());
    }赶上(例外五){
      Log.e(***********错误**************,e.getMessage());
    }    返回null;
  }  类event_background扩展的AsyncTask<无效,字符串,太虚> {    @覆盖
    在preExecute保护无效(){
      super.on preExecute();
    }    @覆盖
    保护无效onPostExecute(虚空未使用){
    }    @覆盖
    保护无效doInBackground(虚空...... PARAMS){
      // TODO自动生成方法存根
      performSocketRequest();
      返回null;
    }
  }
}


解决方案

这是另一种方式来归档加密/解密:

用法

加密:

 的mcrypt的mcrypt =新的mcrypt();
 字符串加密= MCrypt.bytesToHex(mcrypt.encrypt(文本加密));

解密:

 的mcrypt的mcrypt =新的mcrypt();
字符串解密=新的String(mcrypt.decrypt(加密));

类code:的(测试和工程上的2.1+的设备4+未经测试,但应该工作)

 进口java.security.NoSuchAlgorithmException;进口javax.crypto.Cipher中;
进口javax.crypto.NoSuchPaddingException;
进口javax.crypto.spec.IvParameterSpec;
进口javax.crypto.spec.SecretKeySpec;
公共类mcrypt的{    私人字符串IV =fedcba9876543210; //虚拟IV(改变它!)
    私人IvParameterSpec ivspec;
    私人SecretKeySpec keyspec;
    私人密码的密码;
    私人字符串SecretKey的=0123456789ABCDEF; //虚拟SecretKey的(改变它!)    公众的mcrypt(){
        ivspec =新IvParameterSpec(iv.getBytes());        keyspec =新SecretKeySpec(SecretKey.getBytes(),AES);        尝试{
            密= Cipher.getInstance(AES / CBC / NoPadding);
        }赶上(抛出:NoSuchAlgorithmException E){
            e.printStackTrace();
        }赶上(NoSuchPaddingException E){
            e.printStackTrace();
        }
    }    公众的byte []加密(字符串文本)抛出异常{
        如果(文字== NULL || text.length()== 0)抛出新的异常(空字符串);        字节]加密= NULL;        cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);        加密= cipher.doFinal(padString(文本).getBytes());
        尝试{//为OS 2.2+版本
            加密= android.util.Base64.en code(加密,android.util.Base64.NO_PADDING);
        }赶上(NoClassDefFoundError的E){
            加密= org.apache.commons codec.binary.Base64.en codeBase64(加密)。
        }        返回加密;
    }    公共字节[]解密(字符串code)抛出异常{
        如果(code == NULL || code.length()== 0)抛出新的异常(空字符串);        字节[]解密= NULL;        cipher.init(Cipher.DECRYPT_MODE,keyspec,ivspec);        尝试{//为OS 2.2+版本
            解密= cipher.doFinal(android.util.Base64.de code(code,android.util.Base64.NO_PADDING));
        }赶上(NoClassDefFoundError的E){
            解密= cipher.doFinal(org.apache.commons codec.binary.Base64.de codeBase64(code.getBytes(UTF-8)));
        }
        返回解密;
    }    私有静态字符串padString(字符串源){
        焦炭paddingChar ='';
        INT大小= 16;
        INT X = source.length()%的大小;
        INT padLength =大小 - X;        的for(int i = 0; I< padLength;我++){
            源+ = paddingChar;
        }        返回源;
    }
}

相关链接:

I am trying to implement AES 128 bit encryption for android. On cipher.doFinal the process gets stopped. Its not going into the catch block also. Have attached the code.

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;
    }
  }
}
解决方案

An other way to archive encryption/decryption:

Usage

Encrypt:

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

Decrypt:

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

Class Code: (tested and works on 2.1+ devices. Not tested at 4+ but supposed to work)

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

related link : http://www.androidsnippets.com/encrypt-decrypt-between-android-and-php

这篇关于AES 128位加密不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:42