一、demo
package com.example.logindemo;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class User {
private String mId;
private String mPwd;
private static final String masterPassword = "FORYOU"; // AES加密算法的种子
private static final String JSON_ID = "user_id";
private static final String JSON_PWD = "user_pwd";
private static final String TAG = "User";
public User(String id, String pwd) {
this.mId = id;
this.mPwd = pwd;
}
public User(JSONObject json) throws Exception {
if (json.has(JSON_ID)) {
String id = json.getString(JSON_ID);
String pwd = json.getString(JSON_PWD);
// 解密后存放
mId = AESUtils.decrypt(masterPassword, id);
mPwd = AESUtils.decrypt(masterPassword, pwd);
}
}
public JSONObject toJSON() throws Exception {
// 使用AES加密算法加密后保存
String id = AESUtils.encrypt(masterPassword, mId);
String pwd = AESUtils.encrypt(masterPassword, mPwd);
Log.i(TAG, "加密后:" + id + " " + pwd);
JSONObject json = new JSONObject();
try {
json.put(JSON_ID, id);
json.put(JSON_PWD, pwd);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
public String getId() {
return mId;
}
public String getPwd() {
return mPwd;
}
}
二、加密与解密
加密:
public static String encrypt(String text) throws Exception {
// 私钥 AES固定格式为128/192/256bits.即:16/24/32bytes。DES固定格式为128bits,即8bytes。
String key = "aaaaaaaaaaaaaaaa";
// 初始化向量参数,AES 为16bytes. DES 为8bytes
String iv ="bbbbbbbbbbbbbbbb";
// 两个参数,第一个为私钥字节数组, 第二个为加密方式AES或者DES
Key keySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
// 实例化加密类,参数为加密方式,要写全
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// 初始化,此方法可以采用三种方式,按服务器要求来添加。(1)无第三个参数(2)第三个参数为SecureRandom
//(3)采用此代码中的IVParameterSpec
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
// random = new SecureRandom();中random对象,随机数。(AES不可采用这种方法)
// cipher.init(Cipher.ENCRYPT_MODE, keySpec);
// SecureRandom random = new SecureRandom();
// cipher.init(Cipher.ENCRYPT_MODE, keySpec, random);
byte[] bytes = cipher.doFinal(text.getBytes());// 加密操作,返回加密后的字节数组,然后需要编码。主要编解码方式有Base64, HEX, UUE,
// 7bit等等。此处看服务器需要什么编码方式
String result = Base64.encodeToString(bytes, Base64.DEFAULT);
return result;
}
解密:
public static String decrypt(String text) throws Exception {
String keySpec = "aaaaaaaaaaaaaaaa";
String iv = "bbbbbbbbbbbbbbbb";
byte[] textBytes = Base64.decode(text.getBytes(), Base64.DEFAULT);
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
Key key = new SecretKeySpec(keySpec.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); // 与加密时不同MODE:Cipher.DECRYPT_MODE
String result = cipher.doFinal(textBytes);
return result;
}