现在的位置: 首页 > 综合 > 正文

Java_encode加密处理(md5,base64,aes256,sha1)

2017年12月27日 ⁄ 综合 ⁄ 共 4374字 ⁄ 字号 评论关闭

链接:http://blog.csdn.net/jbxiaozi/article/details/7351768

---md5与base64

	/**
	 * md5和base64混合加密
	 * @author mao
	 */
	private static String md5AndBase64Encode(String userName, String pwd) {
		if(userName == null || pwd == null){
			return null;
		}
		String str = "";
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");//md5
			md5.update((userName + "+" + pwd).getBytes());
			str = new String(Base64.encode(md5.digest()));//base64
			//http://blog.csdn.net/jbxiaozi/article/details/7351768
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
		return str;
	}

---aes128, 256

/**
 * Java实现AES加密和解密算法 说明如下:
 *  1、在demo中使用了两个转换方法,及二进制转化成十六进制,和十六进制转化成二进制;
 *  2、我们在AES加密的时候需要使用一个加密算的公共密钥来实现加密和解密;
 *  3、加密后的字节数组不能直接转化为字符串,需要我们通过给出的两个方法转化;
 *  
 *  	http://www.mbaike.net/java/1957.html
 * 		http://blog.csdn.net/hbcui1984/article/details/5201247 
 * 
 * @author csdn
 * @date 2013-11-05
 */
public class AESTest{
	
	private static String code = "1234567890";//公共密钥:128,256
	
	/**
	 * 测试AES加密和解密
	 */
	public static void main(String[] args) {
		
		String content = "你好1测a>b<a\\试1加密";
		String content2 = "{\"Result\":\"OK\",\"Messages\":\"测试\"}";
		System.out.println("加密前:" + content);
		
		byte[] encryptResult = encrypt(content, code);
		String encryptResultStr = parseByte2HexStr(encryptResult);
		System.out.println("加密后:" + encryptResultStr);
		
		byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
		byte[] decryptResult = decrypt(decryptFrom, code);
		System.out.println("解密后:" + new String(decryptResult));
	}

	/**
	 * AES加密
	 * 
	 * @param content
	 *            需要加密的内容
	 * @param code
	 *            加密密码
	 * @return
	 */
	public static byte[] encrypt(String content, String code) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(256, new SecureRandom(code.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			/** 创建密码器 **/
			Cipher cipher = Cipher.getInstance("AES");
			byte[] byteContent = content.getBytes("GBK");//utf-8
			/** 初始化密码器 **/
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] result = cipher.doFinal(byteContent);
			return result;
		} catch (Exception e) {
			System.out.println("出错了:" + e.getMessage());
		}
		return null;
	}

	/**
	 * AES解密
	 * 
	 * @param content
	 *            待解密内容
	 * @param code
	 *            解密密钥
	 * @return
	 */
	public static byte[] decrypt(byte[] content, String code) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(256, new SecureRandom(code.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			/** 创建密码器 **/
			Cipher cipher = Cipher.getInstance("AES");
			/** 初始化密码器 **/
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] result = cipher.doFinal(content);
			return result;
		} catch (Exception e) {
			System.out.println("出错了:" + e.getMessage());
		}
		return null;
	}

	/**
	 * 将二进制转换成十六进制
	 */
	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将十六进制转换为二进制
	 */
	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1) {
			return null;
		} else {
			byte[] result = new byte[hexStr.length() / 2];
			for (int i = 0; i < hexStr.length() / 2; i++) {
				int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
				int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
				result[i] = (byte) (high * 16 + low);
			}
			return result;
		}
	}


}

---sha1

/**
 * sh1加密
 * 
 * @author mao
 * @since 2014-4-8
 * 
 */
public class SHA1Test {
	
	public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		String strSrc = "123456";
		System.out.println("加密前: " + strSrc);
		System.out.println("SHA-1加密1: " + encrypt(strSrc).toUpperCase());
		
		System.out.println("SHA-1加密2: " + encode_sha1(strSrc).toLowerCase());
	}

	/**
	 * SHA1加密(1)
	 * @author wzmmao@163.com
	 */
	public static String encrypt(String strSrc) {
		MessageDigest md = null;
		String strDes = null;

		byte[] bt = strSrc.getBytes();
		try {

			md = MessageDigest.getInstance("SHA-1");
			md.update(bt);
			strDes = bytes2Hex(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}

	public static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}

	
	/**
	 * SHA1加密(2)
	 * @author wzmmao@163.com
	 */
	public static String encode_sha1(String str){
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(str.getBytes("UTF-8"));
			byte[] result = md.digest();

			StringBuffer sb = new StringBuffer();

			for (byte b : result) {
				int i = b & 0xff;
				if (i < 0xf) {
					sb.append(0);
				}
				sb.append(Integer.toHexString(i));
			}
			return sb.toString().toUpperCase();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}	
	}

}

抱歉!评论已关闭.