android base64 和 aes 加密 解密

package pioneerbarcode.ccw.com.encryptanddecode;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import pioneerbarcode.ccw.com.encryptanddecode.utils.AesUtils;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button btnBase64New;
private Button btnBase64Older;
private TextView tvOlder;
private String strOlderData;
private TextView tvJiaMiData;
private TextView tvJieMiData;
private Button btnAesJiaMi;
private Button btnAesjieMi;
private TextView tvAesJiaMiData;
private TextView tvAesJieMiData;
    private static String AESPASSWORD = "hehehe";

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

private void setListener() {
btnBase64New.setOnClickListener(this);
btnBase64Older.setOnClickListener(this);
btnAesJiaMi.setOnClickListener(this);
btnAesjieMi.setOnClickListener(this);
}

private void setView() {
btnBase64New = (Button) findViewById(R.id.btn_base64_jiemi);
btnBase64Older = (Button) findViewById(R.id.btn_base64_jiami);
tvOlder = (TextView) findViewById(R.id.tv_older);
tvJiaMiData = (TextView) findViewById(R.id.tv_jiami_data);
tvJieMiData = (TextView) findViewById(R.id.tv_jiemi_data);

btnAesJiaMi = (Button) findViewById(R.id.btn_Aes_jiami);
btnAesjieMi = (Button) findViewById(R.id.btn_Aes_jiemi);
tvAesJiaMiData = (TextView) findViewById(R.id.tv_Aes_jiami_data);
tvAesJieMiData = (TextView) findViewById(R.id.tv_Aes_jiemi_data);

strOlderData = tvOlder.getText().toString().trim();
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_base64_jiemi:
//base64 解密
base64Decode();
break;
case R.id.btn_base64_jiami:
//Base64加密
base64Encrypt();
break;
case R.id.btn_Aes_jiami:
//Aes 加密
aesEncrypt();
break;
case R.id.btn_Aes_jiemi:
//Aes 解密
aesDecode();
break;
default:
break;
}
}

/**
* Aes 解密
*/
private void aesDecode() {
try {
if (!TextUtils.isEmpty(tvAesJiaMiData.getText().toString().toString().trim())) {
// Aes 解密後的數據
String data = AesUtils.decrypt(AESPASSWORD, tvAesJiaMiData.getText().toString().trim());
tvAesJieMiData.setText(data);
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* Aes 加密
*/
private void aesEncrypt() {
try {
String data = AesUtils.encrypt(AESPASSWORD, strOlderData);
//加密後的串
tvAesJiaMiData.setText(data);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* base64解密
*/
private void base64Decode() {
if (!TextUtils.isEmpty(tvJiaMiData.getText().toString().trim())) {
String data = new String(Base64.decode(tvJiaMiData.getText().toString().trim().getBytes(), Base64.DEFAULT));
tvJieMiData.setText(data);
}
}

/**
* base64加密
*/
private void base64Encrypt() {
//下面是兩種方式 加密
//// 在這裏使用的是encode方式,返回的是byte類型加密數據,可以使用new String轉爲String類型
// String olderData_base64 = new String(Base64.encode(strOlderData.getBytes(), Base64.DEFAULT));
//// 加密傳入的數據是byte類型的,並不是使用decode方法將原始數據轉二進制,String類型的數據 使用 str.getBytes()便可
String olderData_base64 = Base64.encodeToString(strOlderData.getBytes(), Base64.DEFAULT);
tvJiaMiData.setText(olderData_base64);
}

}

public class AesUtils {    public static String encrypt(String seed, String cleartext) throws Exception {        byte[] rawKey = getRawKey(seed.getBytes());        byte[] result = encrypt(rawKey, cleartext.getBytes());        return toHex(result);    }    public static String decrypt(String seed, String encrypted) throws Exception {        byte[] rawKey = getRawKey(seed.getBytes());        byte[] enc = toByte(encrypted);        byte[] result = decrypt(rawKey, enc);        return new String(result);    }    private static byte[] getRawKey(byte[] seed) throws Exception {        KeyGenerator kgen = KeyGenerator.getInstance("AES");        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");        sr.setSeed(seed);        kgen.init(128, sr); // 192 and 256 bits may not be available        SecretKey skey = kgen.generateKey();        byte[] raw = skey.getEncoded();        return raw;    }    private 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,new IvParameterSpec(new byte[cipher.getBlockSize()]));        byte[] encrypted = cipher.doFinal(clear);        return encrypted;    }    private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");        Cipher cipher = Cipher.getInstance("AES");        cipher.init(Cipher.DECRYPT_MODE, skeySpec,new IvParameterSpec(new byte[cipher.getBlockSize()]));        byte[] decrypted = cipher.doFinal(encrypted);        return decrypted;    }    private static String toHex(String txt) {        return toHex(txt.getBytes());    }    private static String fromHex(String hex) {        return new String(toByte(hex));    }    private static byte[] toByte(String hexString) {        int len = hexString.length()/2;        byte[] result = new byte[len];        for (int i = 0; i < len; i++)            result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();        return result;    }    private static String toHex(byte[] buf) {        if (buf == null)            return "";        StringBuffer result = new StringBuffer(2*buf.length);        for (int i = 0; i < buf.length; i++) {            appendHex(result, buf[i]);        }        return result.toString();    }    private final static String HEX = "0123456789ABCDEF";    private static void appendHex(StringBuffer sb, byte b) {        sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));    }}通過驗證可用
相關文章
相關標籤/搜索