项目中加密存储密码的工具类---PasswordUtil类

PBE——Password-based encryption(基于密码加密)。其特点在于口令由用户自己掌管,不借助任何物理媒体;采用随机数(这里我们叫做盐)杂凑多重加密等方法保证数据的安全性。是一种简便的加密方式。

本类运用了Java 6所支持的PBE对称加密算法到Android环境里,实现密码的安全存储.

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class PasswordUtil {

	/** 
     * JAVA6支持以下任意一种算法 
     * PBEWITHMD5ANDDES 
     * PBEWITHMD5ANDTRIPLEDES 
     * PBEWITHSHAANDDESEDE 
     * PBEWITHSHA1ANDRC2_40 
     * PBKDF2WITHHMACSHA1 
     * */ 

	/**
	 * 定义使用的算法为:PBEWITHMD5andDES算法
	 */
	public static final String ALGORITHM = "PBEWithMD5AndDES";

	/**
	 * 定义迭代次数为1000次
	 */
	private static final int ITERATIONCOUNT = 1000;

	/**
	 * 获取加密算法中使用的盐值,解密中使用的盐值必须与加密中使用的相同才能完成操作.
	 * 盐长度必须为8字节 
	 * 
	 * @return byte[] 盐值
	 * */
	public static byte[] getSalt() throws Exception {
		//实例化安全随机数
		SecureRandom random = new SecureRandom();
		//产出盐
		return random.generateSeed(8);
	}

	/**
	 * 根据PBE密码生成一把密钥
	 * 
	 * @param password
	 *            生成密钥时所使用的密码
	 * @return Key PBE算法密钥
	 * */
	private static Key getPBEKey(String password) throws Exception {
		// 实例化使用的算法
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
		// 设置PBE密钥参数  
		PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
		// 生成密钥
		SecretKey secretKey = keyFactory.generateSecret(keySpec);

		return secretKey;
	}

	/**
	 * 加密明文字符串
	 * 
	 * @param plaintext
	 *            待加密的明文字符串
	 * @param password
	 *            生成密钥时所使用的密码
	 * @param salt
	 *            盐值
	 * @return 加密后的密文字符串
	 * @throws Exception
	 */
	public static String encrypt(String plaintext, String password, byte[] salt) throws Exception {

		Key key = getPBEKey(password);

		PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, ITERATIONCOUNT);

		Cipher cipher = Cipher.getInstance(ALGORITHM);

		cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);

		byte encipheredData[] = cipher.doFinal(plaintext.getBytes());

		return bytesToHexString(encipheredData);
	}

	/**
	 * 解密密文字符串
	 * 
	 * @param ciphertext
	 *           待解密的密文字符串
	 * @param password
	 *            生成密钥时所使用的密码(如需解密,该参数需要与加密时使用的一致)
	 * @param salt
	 *            盐值(如需解密,该参数需要与加密时使用的一致)
	 * @return 解密后的明文字符串
	 * @throws Exception
	 */
	public static String decrypt(String ciphertext, String password, byte[] salt) throws Exception {

		Key key = getPBEKey(password);

		PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, ITERATIONCOUNT);

		Cipher cipher = Cipher.getInstance(ALGORITHM);

		cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);

		byte[] passDec = cipher.doFinal(hexStringToBytes(ciphertext));

		return new String(passDec);
	}

	/**
	 * 将字节数组转换为十六进制字符串
	 * @param src 字节数组
	 * @return
	 */
	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	/**
	 * 将十六进制字符串转换为字节数组
	 * 
	 * @param hexString 十六进制字符串
	 * @return
	 */
	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}
}

代码的使用:

public static void main(String[] args) {
		String str = "PBE";
		String password = "123";

		System.out.println("明文:" + str);
		System.out.println("密码:" + password);

		try {
			byte[] salt = PasswordUtil.getSalt();
			String ciphertext = PasswordUtil.encrypt(str, password, salt);
			System.out.println("密文:" + ciphertext);
			String plaintext = PasswordUtil.decrypt(ciphertext, password, salt);
			System.out.println("明文:" + plaintext);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


运行的效果:



可以使用该工具类,把密码和盐值都固定在工具类里,将用户输入的密码,加密后保存在SharePreference里面.已达到安全存储密码的需求.



------------------------分割线---------------------------



以下是SHA1安全哈希算法的使用工具,在常见的登录操作中,服务器采用的验证方式为:MD5(username+SHA1(password)+时间戳+APP_KEY)


public class SHA1Util {
	private static final boolean hexcase = false;
	private static final String b64pad = "=";
	private static final int chrsz = 8;

	// 得到字符串SHA-1值的方法
	public static String hex_sha1(String s) {
		s = (s == null) ? "" : s;
		return binb2hex(core_sha1(str2binb(s), s.length() * chrsz));
	}

	public static String b64_hmac_sha1(String key, String data) {
		return binb2b64(core_hmac_sha1(key, data));
	}

	public static String b64_sha1(String s) {
		s = (s == null) ? "" : s;
		return binb2b64(core_sha1(str2binb(s), s.length() * chrsz));
	}

	private static String binb2b64(int[] binarray) {
		String tab = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/";
		String str = "";
		binarray = strechbinarray(binarray, binarray.length * 4);

		for (int i = 0; i < binarray.length * 4; i += 3) {
			int triplet = (((binarray[i >> 2] >> 8 * (3 - i % 4)) & 0xff) << 16)
					| (((binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xff) << ((binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xff));

			for (int j = 0; j < 4; j++) {
				if (i * 8 + j * 6 > binarray.length * 32) {
					str += b64pad;
				} else {
					str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3f);
				}
			}
		}

		return cleanb64str(str);
	}

	private static String binb2hex(int[] binarray) {
		String hex_tab = hexcase ? "0123456789abcdef" : "0123456789abcdef";
		String str = "";

		for (int i = 0; i < binarray.length * 4; i++) {
			char a = (char) hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xf);
			char b = (char) hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xf);
			str += (new Character(a).toString() + new Character(b).toString());
		}

		return str;
	}

	private static String binb2str(int[] bin) {
		String str = "";
		int mask = (1 << chrsz) - 1;

		for (int i = 0; i < bin.length * 32; i += chrsz) {
			str += (char) ((bin[i >> 5] >>> (24 - i % 32)) & mask);
		}

		return str;
	}

	private static int bit_rol(int num, int cnt) {
		return (num << cnt) | (num >>> (32 - cnt));
	}

	private static String cleanb64str(String str) {
		str = (str == null) ? "" : str;
		int len = str.length();

		if (len <= 1) {
			return str;
		}

		char trailchar = str.charAt(len - 1);
		String trailstr = "";

		for (int i = len - 1; i >= 0 && str.charAt(i) == trailchar; i--) {
			trailstr += str.charAt(i);
		}

		return str.substring(0, str.indexOf(trailstr));
	}

	private static int[] complete216(int[] oldbin) {
		if (oldbin.length >= 16) {
			return oldbin;
		}

		int[] newbin = new int[16 - oldbin.length];

		for (int i = 0; i < newbin.length; newbin[i] = 0, i++)
			;

		return concat(oldbin, newbin);
	}

	private static int[] concat(int[] oldbin, int[] newbin) {
		int[] retval = new int[oldbin.length + newbin.length];

		for (int i = 0; i < (oldbin.length + newbin.length); i++) {
			if (i < oldbin.length) {
				retval[i] = oldbin[i];
			} else {
				retval[i] = newbin[i - oldbin.length];
			}
		}

		return retval;
	}

	private static int[] core_hmac_sha1(String key, String data) {
		key = (key == null) ? "" : key;
		data = (data == null) ? "" : data;
		int[] bkey = complete216(str2binb(key));

		if (bkey.length > 16) {
			bkey = core_sha1(bkey, key.length() * chrsz);
		}

		int[] ipad = new int[16];
		int[] opad = new int[16];

		for (int i = 0; i < 16; ipad[i] = 0, opad[i] = 0, i++)
			;

		for (int i = 0; i < 16; i++) {
			ipad[i] = bkey[i] ^ 0x36363636;
			opad[i] = bkey[i] ^ 0x5c5c5c5c;
		}

		int[] hash = core_sha1(concat(ipad, str2binb(data)), 512 + data.length() * chrsz);

		return core_sha1(concat(opad, hash), 512 + 160);
	}

	private static int[] core_sha1(int[] x, int len) {
		int size = (len >> 5);
		x = strechbinarray(x, size);
		x[len >> 5] |= 0x80 << (24 - len % 32);
		size = ((len + 64 >> 9) << 4) + 15;
		x = strechbinarray(x, size);
		x[((len + 64 >> 9) << 4) + 15] = len;

		int[] w = new int[80];
		int a = 1732584193;
		int b = -271733879;
		int c = -1732584194;
		int d = 271733878;
		int e = -1009589776;

		for (int i = 0; i < x.length; i += 16) {
			int olda = a;
			int oldb = b;
			int oldc = c;
			int oldd = d;
			int olde = e;

			for (int j = 0; j < 80; j++) {
				if (j < 16) {
					w[j] = x[i + j];
				} else {
					w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
				}

				int t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));

				e = d;
				d = c;
				c = rol(b, 30);
				b = a;
				a = t;
			}

			a = safe_add(a, olda);
			b = safe_add(b, oldb);
			c = safe_add(c, oldc);
			d = safe_add(d, oldd);
			e = safe_add(e, olde);
		}

		int[] retval = new int[5];

		retval[0] = a;
		retval[1] = b;
		retval[2] = c;
		retval[3] = d;
		retval[4] = e;

		return retval;
	}

	private static void dotest() {
		String key = "key";
		String data = "data";
		System.out.println("hex_sha1(" + data + ")=" + hex_sha1(data));
		System.out.println("b64_sha1(" + data + ")=" + b64_sha1(data));
		System.out.println("str_sha1(" + data + ")=" + str_sha1(data));
		System.out.println("hex_hmac_sha1(" + key + "," + data + ")=" + hex_hmac_sha1(key, data));
		System.out.println("b64_hmac_sha1(" + key + "," + data + ")=" + b64_hmac_sha1(key, data));
		System.out.println("str_hmac_sha1(" + key + "," + data + ")=" + str_hmac_sha1(key, data));
	}

	public static String hex_hmac_sha1(String key, String data) {
		return binb2hex(core_hmac_sha1(key, data));
	}

	private static int rol(int num, int cnt) {
		return (num << cnt) | (num >>> (32 - cnt));
	}

	private static int safe_add(int x, int y) {
		int lsw = (int) (x & 0xffff) + (int) (y & 0xffff);
		int msw = (x >> 16) + (y >> 16) + (lsw >> 16);

		return (msw << 16) | (lsw & 0xffff);
	}

	private static int sha1_ft(int t, int b, int c, int d) {
		if (t < 20)
			return (b & c) | ((~b) & d);

		if (t < 40)
			return b ^ c ^ d;

		if (t < 60)
			return (b & c) | (b & d) | (c & d);

		return b ^ c ^ d;
	}

	private static int sha1_kt(int t) {
		return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
	}

	private static boolean sha1_vm_test() {
		return hexcase ? hex_sha1("abc").equals("a9993e364706816aba3e25717850c26c9cd0d89d") : hex_sha1("abc").equals("a9993e364706816aba3e25717850c26c9cd0d89d");
	}

	public static String str_hmac_sha1(String key, String data) {
		return binb2str(core_hmac_sha1(key, data));
	}

	public static String str_sha1(String s) {
		s = (s == null) ? "" : s;

		return binb2str(core_sha1(str2binb(s), s.length() * chrsz));
	}

	private static int[] str2binb(String str) {
		str = (str == null) ? "" : str;

		int[] tmp = new int[str.length() * chrsz];
		int mask = (1 << chrsz) - 1;

		for (int i = 0; i < str.length() * chrsz; i += chrsz) {
			tmp[i >> 5] |= ((int) (str.charAt(i / chrsz)) & mask) << (24 - i % 32);
		}

		int len = 0;
		for (int i = 0; i < tmp.length && tmp[i] != 0; i++, len++)
			;

		int[] bin = new int[len];

		for (int i = 0; i < len; i++) {
			bin[i] = tmp[i];
		}

		return bin;
	}

	private static int[] strechbinarray(int[] oldbin, int size) {
		int currlen = oldbin.length;

		if (currlen >= size + 1) {
			return oldbin;
		}

		int[] newbin = new int[size + 1];
		for (int i = 0; i < size; newbin[i] = 0, i++)
			;

		for (int i = 0; i < currlen; i++) {
			newbin[i] = oldbin[i];
		}

		return newbin;
	}
}



你可能感兴趣的:(项目中加密存储密码的工具类---PasswordUtil类)