Java加密跟解密

具体事项请直接看代码:

public static final String KEY_MD5 = "MD5";
	
	public static byte[] encryptMD5(byte[] input) throws Exception {
		MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
		BASE64Encoder  encoder = new BASE64Encoder();
		return md5.digest(input);
	}
	
	public static String encryptMD5ByBase64(byte[] input) throws Exception {
		MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
		BASE64Encoder  encoder = new BASE64Encoder();
		return encoder.encode(md5.digest(input));
	}
	
	public static void main(String[] args) {
		try{
			String str = "abc";
			//通过 MD5加密
			String md5Str = addSecurity(str);
			System.out.println("MD5加密前的字符串:" + str);
			System.out.println("MD5加密后的字符串:" + md5Str);
			
			//通过MD5加密后再用Base64加密
			String md5Str_1 = addSecurityByBase64(str);
			System.out.println("MD5 And Base64加密前的字符串:" + str);
			System.out.println("MD5 And Base64加密后的字符串:" + md5Str_1);
			
			//通过 MD5加密
			String normalStr = addNormalSecurity(str);
			System.out.println("正常加密前的字符串:" + str);
			System.out.println("正常加密前的后字符串:" + normalStr);
			
			//把正常加密后的字符解密
			String normalStr_1 = unAddNormalSecurity(normalStr);
			System.out.println("正常加密前的后字符串:" + str);
			System.out.println("正常加密前的后解密的字符串:" + normalStr);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 通过 MD5加密
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static String addSecurity(String str) throws Exception{
		String result = "";
		BigInteger md5 =  new BigInteger(JavaSecurityApp.encryptMD5(str.getBytes()));
		result = md5.toString(16);
		return result;
	}
	
	/**
	 * 通过MD5加密后再用Base64加密
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static String addSecurityByBase64(String str) throws Exception{
		String result = "";
		BigInteger md5 =  new BigInteger(JavaSecurityApp.encryptMD5(str.getBytes()));
		result = JavaSecurityApp.encryptMD5ByBase64(str.getBytes());
		return result;
	}
	
	/**
	 * 普通方法加密
	 * @return
	 */
	public static String addNormalSecurity(String str){
		String result = "";
		char[] arr = str.toCharArray();
		for(int i =0; i < arr.length; i ++){
			arr[i] = (char) (arr[i] ^ 't'); 
		}
		result = new String(arr);
		return result;
	}
	
	/**
	 * 解密普通方法的加密
	 * @return
	 */
	public static String unAddNormalSecurity(String str){
		String result = "";
		char[] arr = str.toCharArray();
		for(int i =0; i < arr.length; i ++){
			arr[i] = (char) (arr[i] ^ 't'); 
		}
		result = new String(arr);
		return result;
	}


该代码的运行结果:

MD5加密前的字符串:abc
MD5加密后的字符串:-6ffeaf67c32db04f2969c082d71e808e
MD5 And Base64加密前的字符串:abc
MD5 And Base64加密后的字符串:kAFQmDzST7DWlj99KOF/cg==
正常加密前的字符串:abc
正常加密前的后字符串:
正常加密前的后字符串:abc
正常加密前的后解密的字符串:

你可能感兴趣的:(Java加密跟解密)