MD5加密方式

MD5加密的核心代码:

/**
	 * MD5加密
	 * 
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static byte[] encryptMD5(byte[] data) {

		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance(KEY_MD5);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return data;
		}
		md5.update(data);

		return md5.digest();

	}
	
	public static String encryptMD5(String data) {
		return byte2hex(encryptMD5(data.getBytes()));
	}

public static String byte2hex(byte[] b) {
		StringBuffer stmp = new StringBuffer();
		for (int n = 0; n < b.length; n++) {
			if ((b[n] & 0XFF)<16) //小于16则代表只有一位16进制数
				stmp.append("0");
			else
				stmp.append(Long.toString(b[n] & 0XFF, 16));
		}
		return stmp.toString().toUpperCase();
	}

	public static byte[] hex2byte(byte[] b) {
		if ((b.length % 2) != 0)
			throw new IllegalArgumentException("长度不是偶数");
		byte[] b2 = new byte[b.length / 2];
		for (int n = 0; n < b.length; n += 2) {
			String item = new String(b, n, 2);
			b2[n / 2] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}


你可能感兴趣的:(java,android,MD5,加密)