Android实用框架(二)

继Android实用框架(一):点击打开链接

今天继续根据昨天的文章推出第二篇

我们昨天完成了Log类的书写,日后方便的管理log的开关 今天分享一下user包 顾名思义是用户登录相关的工具类,我们对其进行加密和保存,以方便用户下次直接使用。

提供User类放在user包下:

public class User {
	private String mId;
	private static final String masterPassword = "FORYOU"; 
	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) {
		this.mId = id;
	}

	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 + "  " );
		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;
//	}
}
这里保存了用户的用户名,密码我给注释了 可以另行添加  再者给用户进行加密 提供AESUtils:

/**
 * 用与用户账号密码加密的工具类
 *
 */
@SuppressLint("TrulyRandom")
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);
		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;
	}

	@SuppressWarnings("unused")
	private static String toHex(String txt) {
		return toHex(txt.getBytes());
	}

	@SuppressWarnings("unused")
	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));
	}
}


我们对用户的账号密码进行加密,保护用户的安全信息  现在我们就要对外提供方法了,让外部调用~ UserUtils(相同放在user包下)

public class UserUtils {
	private static final String FILENAME = "userinfo.json"; // 用户保存文件名
	private static final String TAG = "Utils";

	/* 保存用户登录信息列表 */
	public static void saveUserList(Context context, ArrayList<User> users)
			throws Exception {
		/* 保存 */
		Log.i(TAG, "正在保存");
		Writer writer = null;
		OutputStream out = null;
		JSONArray array = new JSONArray();
		for (User user : users) {
			array.put(user.toJSON());
		}
		try {
			out = context.openFileOutput(FILENAME, Context.MODE_PRIVATE); // 覆盖
			writer = new OutputStreamWriter(out);
			Log.i(TAG, "json的值:" + array.toString());
			writer.write(array.toString());
		} finally {
			if (writer != null)
				writer.close();
		}

	}

	/* 获取用户登录信息列表 */
	public static ArrayList<User> getUserList(Context context) {
		/* 加载 */
		FileInputStream in = null;
		ArrayList<User> users = new ArrayList<User>();
		try {

			in = context.openFileInput(FILENAME);
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder jsonString = new StringBuilder();
			JSONArray jsonArray = new JSONArray();
			String line;
			while ((line = reader.readLine()) != null) {
				jsonString.append(line);
			}
			Log.i(TAG, jsonString.toString());
			jsonArray = (JSONArray) new JSONTokener(jsonString.toString())
					.nextValue(); // 把字符串转换成JSONArray对象
			for (int i = 0; i < jsonArray.length(); i++) {
				User user = new User(jsonArray.getJSONObject(i));
				users.add(user);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return users;
	}
}

user包下暂时就放这些东西,接下来如何调用呢?(模拟)

如何保存?

1:获取集合  

ArrayList<User> mUser=UserUtils.getUserList(LoginActivity.this);
2:  存入对象(这里只保存账号)

User user = new User(mIdString);//用户名
mUsers.add(user);
3:  将保存的用户名显示    布局EditText

if (mUsers.size() > 0) {
			mIdEditText.setText(mUsers.get(0).getId());
			// mPwdEditText.setText(mUsers.get(0).getPwd());
		}
判断集合是否有保存的  显示入输入框。

???这里又涉及到一个问题  在什么时候存呢?如果已经保存的就不再保存 进行判断

boolean mIsSave = true;
try {
		for (User user : mUsers) { // 判断本地文档是否有此ID用户
			if (user.getId().equals(mIdString)) {
				mIsSave = false;
			break;
			}
			}
			if (mIsSave) { // 将新用户加入users
			User user = new User(mIdString);//用户名
			mUsers.add(user);
			}

			} catch (Exception e) {
						e.printStackTrace();
			}

今天就分享到这吧,明天继续。

转载请注明出处:http://blog.csdn.net/hao54216/article/category/6533929






  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值