java 加密之MD示例

MD加密有三种MD2 MD4 MD5


JDK提供了2种MD2 MD5


private static void JDKMD2(){
		try {
			MessageDigest md2 = MessageDigest.getInstance("MD2");
			byte[] md2byte = md2.digest(src.getBytes());
			System.out.println("JDK MD2:"+Hex.encodeHexString(md2byte));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

private static void JDKMD5(){
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] md5byte = md5.digest(src.getBytes());
			System.out.println("JDK MD5:"+Hex.encodeHexString(md5byte));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

Bouncy Castle

private static void BCMD2(){
		Digest digest = new MD2Digest();
		digest.update(src.getBytes(),0,src.getBytes().length);
		byte[] md2byte = new byte[digest.getDigestSize()];
		digest.doFinal(md2byte, 0);
		System.out.println("BC MD2:"+org.bouncycastle.util.encoders.Hex.toHexString(md2byte));
	}

private static void BCMD5(){
		Digest digest = new MD5Digest();
		digest.update(src.getBytes(),0,src.getBytes().length);
		byte[] md5byte = new byte[digest.getDigestSize()];
		digest.doFinal(md5byte, 0);
		System.out.println("BC MD5:"+org.bouncycastle.util.encoders.Hex.toHexString(md5byte));
	}
注释的是两种不同的方式
private static void BCMD4(){
		try {
			Security.addProvider(new BouncyCastleProvider());
			MessageDigest md4 = MessageDigest.getInstance("MD4");
			byte[] md4byte = md4.digest(src.getBytes());
			System.out.println("BC MD4:"+Hex.encodeHexString(md4byte));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
//		Digest digest = new MD4Digest();
//		digest.update(src.getBytes(),0,src.getBytes().length);
//		byte[] md4byte = new byte[digest.getDigestSize()];
//		digest.doFinal(md4byte, 0);
//		System.out.println("BC MD4:"+org.bouncycastle.util.encoders.Hex.toHexString(md4byte));
	}

Commons Codec

	public static void CCMD5(){
		System.out.println("CCMD5:"+DigestUtils.md5Hex(src));
	}
	
	public static void CCMD2(){
		System.out.println("CCMD2:"+DigestUtils.md2Hex(src));
	}

commons codec 仅仅对JDk做了一点改造 使用起来更方便

你可能感兴趣的:(java)