密码加密

  1.简单的md5加密
	/**
	 * 简单的md5加密
	 * */
	public String md5s(String plainText) {
		String str = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			str = buf.toString();
//			//System.out.println("result: " + buf.toString());// 32位的加密
//			//System.out.println("result: " + buf.toString().substring(8, 24));// 16位的加密			
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}


  2.生成加密密码
	/**
	 * 生成加密密码
	 * 
	 * @param password
	 *            需要加密的字符串
	 */
 private int SALT_ORIGINAL_LEN=8;         

	public String digestPassword(String password) {
		try {
			SecureRandom random = new SecureRandom();
			byte[] salt = new byte[SALT_ORIGINAL_LEN];
			random.nextBytes(salt);
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(salt);
			md.update(password.getBytes());
			//System.out.println(salt);
			byte[] digest = md.digest();
			// BASE64Encoder encoder = new BASE64Encoder();
			// return encoder.encode(salt) + encoder.encode(digest);
			return Base64.encode(salt) + Base64.encode(digest);
		} catch (NoSuchAlgorithmException ne) {
			//System.out.println(ne.toString());
			return null;
		} catch (Exception e) {
			//System.out.println(e.toString());
			return null;
		}
	}


  3.验证一个明文密码和一个密文密码是否相等
/**
	 * 验证一个明文密码和一个密文密码是否相等
	 * 
	 * @param password
	 *            用户输入的明文密码,如:123456
	 * @param digest
	 *            目标密码,即数据库存放的已经加密的密码
	 * @return true:密码相同 false:密码不同
	 */
    private int SALT_ENCODED_LEN=12;
	public  boolean validatePassword(String password, String digest) {
		boolean label = false;
		try {
			String salt_str = digest.substring(0, SALT_ENCODED_LEN);
			String digest_str = digest.substring(SALT_ENCODED_LEN, digest.length());
			// Base64 decoder = new BASE64Decoder();
			byte[] salt = Base64.decode(salt_str);
			byte[] digest_old = Base64.decode(digest_str);

			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(salt);
			md.update(password.getBytes());
			byte[] digest_new = md.digest();
			label = Arrays.equals(digest_old, digest_new);
		} catch (NoSuchAlgorithmException ne) {
			//System.out.println(ne.toString());
		} catch (Exception e) {
			//System.out.println(e.toString());
		}
		return label;
	}


  过程中base64报了一个错:Access restriction:The type JPEGCodec is not accessible due to restriction on required library D:\Java\jre7\lib\rt.jar(you's rt.jar address)
  解决方法:
  Project -> Properties -> libraries,
  先 remove 掉 JRE System Library,然后再 Add Library 重新加入。

你可能感兴趣的:(MD5)