关键(二):数据加密机制

一些说明:

    加密,是以某种特殊的算法改变原有的信息数据,使得未授权的用户即使获得了已加密的信息,但因不知解密的方法,仍然无法了解信息的内容。从而对一些敏感的数据,如账号,密码等信息起到保密的作用,提高数据的安全。

   下面的第一部分,是一个现有项目的加密方式,主要是将一个String类型的数据使用DES的方式加密,解密。
   第二部分,主要功能和第一个一样,但是差别是使用AES的方式加密。

第一部分 一个现有项目使用的加密方式


1.关键类-----加密解密字符串工具类

import java.security.Key;
import java.security.MessageDigest;
import java.security.Security;
import javax.crypto.Cipher;


/**
 * @
 * 加密解密字符串工具类
 */
public class EncryptUtil {
	/** 字符串默认键值 */
	private static final String DEFAULT_KEY = "wawa_team";
	/** 加密工具 */
	private static Cipher encryptCipher = null;
	/** 解密工具 */
	private static Cipher decryptCipher = null;

	/**
	 * 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[]
	 * hexStr2ByteArr(String strIn) 互为可逆的转换过程
	 * 
	 * @param arrB
	 *            需要转换的byte数组
	 * @return 转换后的字符串
	 * @throws Exception
	 *             本方法不处理任何异常,所有异常全部抛出
	 */
	public static String byteArr2HexStr(byte[] arrB) {
		int iLen = arrB.length;
		// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = arrB[i];
			// 把负数转换为正数
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			// 小于0F的数需要在前面补0
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16));
		}
		return sb.toString();
	}

	/**
	 * 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB)
	 * 互为可逆的转换过程
	 * 
	 * @param strIn
	 *            需要转换的字符串
	 * @return 转换后的byte数组
	 * @throws Exception
	 *             本方法不处理任何异常,所有异常全部抛出
	 * @author <a href="mailto:leo841001@163.com">LiGuoQing</a>
	 */
	public static byte[] hexStr2ByteArr(String strIn) {
		byte[] arrB = strIn.getBytes();
		int iLen = arrB.length;

		// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}

	/**
	 * 加密字节数组
	 * 
	 * @param arrB
	 *            需加密的字节数组
	 * @return 加密后的字节数组
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] arrB) {
		if(arrB == null || arrB.length == 0){
			return new byte[]{};
		}
		Security.addProvider(new com.sun.crypto.provider.SunJCE());
		try {
			Key key = getKey(DEFAULT_KEY.getBytes());
			encryptCipher = Cipher.getInstance("DES");
			encryptCipher.init(Cipher.ENCRYPT_MODE, key);
			return encryptCipher.doFinal(arrB);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 加密字符串
	 * 
	 * @param strIn
	 *            需加密的字符串
	 * @return 加密后的字符串
	 * @throws Exception
	 */
	public static String encrypt(String strIn) {
		if(strIn == null || strIn.length() == 0){
			return "";
		}
		return byteArr2HexStr(encrypt(strIn.getBytes()));
	}

	/**
	 * 解密字节数组
	 * 
	 * @param arrB
	 *            需解密的字节数组
	 * @return 解密后的字节数组
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] arrB) {
		if(arrB == null || arrB.length == 0){
			return new byte[]{};
		}
		Security.addProvider(new com.sun.crypto.provider.SunJCE());
		try {
			Key key = getKey(DEFAULT_KEY.getBytes());
			decryptCipher = Cipher.getInstance("DES");
			decryptCipher.init(Cipher.DECRYPT_MODE, key);
			return decryptCipher.doFinal(arrB);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 解密字符串
	 * 
	 * @param strIn
	 *            需解密的字符串
	 * @return 解密后的字符串
	 * @throws Exception
	 */
	public static String decrypt(String strIn) {
		if(strIn == null || strIn.length() == 0){
			return "";
		}
		return new String(decrypt(hexStr2ByteArr(strIn)));
	}

	/**
	 * 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位
	 * 
	 * @param arrBTmp
	 *            构成该字符串的字节数组
	 * @return 生成的密钥
	 * @throws java.lang.Exception
	 */
	private static Key getKey(byte[] arrBTmp) {
		// 创建一个空的8位字节数组(默认值为0)
		byte[] arrB = new byte[8];

		// 将原始字节数组转换为8位
		for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
			arrB[i] = arrBTmp[i];
		}

		// 生成密钥
		Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");

		return key;
	}
	
	/**
	 * 将字符串进行md5加密
	 * @param str
	 * @return
	 */
	public static String md5(String str) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(str.getBytes("UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer buffer = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1){
				buffer.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			}else{
				buffer.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		}
		return buffer.toString();
	}
	
}

2.使用样例:

                String test = "23";
		result = "-----测试的字符串为:"+test;
		Log.i(TAG, result);
		
		String ecnry = null;
		String decrypt = null;
		String md5 = null;		
		
		ecnry = EncryptUtil.encrypt(test);
		Log.i(TAG, "----加密后的字符串:" + ecnry);

                decrypt = EncryptUtil.decrypt(ecnry);
		Log.i(TAG, "----解密后的字符串:" + decrypt);
		
		md5 = EncryptUtil.md5(test);
		Log.i(TAG, "-----md5加密后的字符串:" + md5);

3.结果:

-----测试的字符串为:23
----加密后的字符串:d7f04ca9825bc11d
----解密后的字符串:23
-----md5加密后的字符串:37693cfc748049e45d87b8c7d8b9aacd


4.说明:

这需要添加库-------sunjce_provider.jar

(此方法是我们公司的项目中所用的加密方法,并不是我原创的)!!


第二部分  JAVA实现AES加密

1.关键类:

package com.example.testjiami;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class EncryptHelp {
		
	/** 
	 * 加密 
	 *  
	 * @param content 需要加密的内容 
	 * @param password  加密密码 
	 * @return 
	 */  
	public static String encrypt(String content, String password) {  
		try { 
			String result;
			
	        KeyGenerator kgen = KeyGenerator.getInstance("AES");  
	        kgen.init(128, new SecureRandom(password.getBytes()));  
	        SecretKey secretKey = kgen.generateKey();  
	        byte[] enCodeFormat = secretKey.getEncoded();  
	        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");  
	        Cipher cipher = Cipher.getInstance("AES");// 创建密码器  
	        byte[] byteContent = content.getBytes("utf-8");  
	        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化  	        
	        byte[] resultByte = cipher.doFinal(byteContent);  
	        result = parseByte2HexStr(resultByte);
	        return result; // 加密  
		} catch (NoSuchAlgorithmException e) {  
			e.printStackTrace();  
		} catch (NoSuchPaddingException e) {  
			e.printStackTrace();  
		} catch (InvalidKeyException e) {  
			e.printStackTrace();  
		} catch (UnsupportedEncodingException e) {  
			e.printStackTrace();  
		} catch (IllegalBlockSizeException e) {  
			e.printStackTrace();  
		} catch (BadPaddingException e) {  
			e.printStackTrace();  
		}  
		return null;  
	}  
	
	
	/**解密 
	 * @param content  待解密内容 
	 * @param password 解密密钥 
	 * @return 
	 */  
	public static String decrypt(String contentStr, String password) {
		byte[] content = parseHexStr2Byte(contentStr);
		try {  
			String resultStr;
			KeyGenerator kgen = KeyGenerator.getInstance("AES");  
			kgen.init(128, new SecureRandom(password.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[] resultByte = cipher.doFinal(content);  
			resultStr = new String(resultByte);
			return resultStr; 
		} catch (NoSuchAlgorithmException e) {  
			e.printStackTrace();  
		} catch (NoSuchPaddingException e) {  
			e.printStackTrace();  
		} catch (InvalidKeyException e) {  
			e.printStackTrace();  
		} catch (IllegalBlockSizeException e) {  
			e.printStackTrace();  
		} catch (BadPaddingException e) {  
			e.printStackTrace();  
		}  
		return null;  
	} 
	
    /**将二进制转换成16进制
     * @param buf
     * @return
     */
    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();
    }	

    
    /**将16进制转换为二进制
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		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;
    }	
}

2.使用样例:

String content = "12345";  
		String password = "12345678";  
		//加密   
		Log.i(TAG,"-----测试的字符串为:"+content ); 
		
		String encryptResult = EncryptHelp.encrypt(content, password); 		
		Log.i(TAG,"-----加密后的字符串为:"+encryptResult);
		
		//解密   		
		String decryptResult = EncryptHelp.decrypt(encryptResult,password);
		Log.i(TAG,"-----解密后的字符串为:"+new String(decryptResult));	


3.运行结果:

 -----测试的字符串为:12345
 -----加密后的字符串为:1504463338B7E1E2A191BCE6D0D6148D
 -----解密后的字符串为:12345

参考资料:

(1)(java加密解密)如何实现JCE接口的各种算法??

http://zhidao.baidu.com/link?url=akxyg5AeyT_-eCke6oQtzIIqjzwZ1ose-YDUzjKKS5BsrQWp27vhXoyEZqhXqTEu5YGOFik7LhGC9uofIEAqV_

(2)JAVA实现AES加密

http://www.cnblogs.com/freeliver54/archive/2011/10/08/2202136.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hfreeman2008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值