Aes加密和Des加密

Aes加密工具类



import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AESUtil {
	 
		public static String urlSafeEncode(String str){
			str =  str.replace('/', '_').replace('+', '-');
			int len = str.length();
			if (str.charAt(len - 2) == '=') {
				str = str.substring(0, len - 2);
			} else if (str.charAt(len - 1) == '=') {
				str = str.substring(0, len - 1);
			}
			return str;
		}
		
		public static String urlSafeDecode(String str){
			str =   str.replace('_', '/').replace('-', '+');
			
			int len = str.length() % 3;

			if (len == 1) {
				str += "==";
			} else if (len == 2) {
				str += "==";
			}
			return str;
		}
		    
	    public static String encrypt(String sSrc, String sKey) throws Exception {  
	        if (sKey == null) {  
	            System.out.print("Key为空null");  
	            return null;  
	        }  
	        // 判断Key是否为16位  
	        if (sKey.length() != 16) {  
	            System.out.print("Key长度不是16位");  
	            return null;  
	        }  
	        byte[] raw = sKey.getBytes();  
	        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");  
	        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/补码方式"  
	        IvParameterSpec iv = new IvParameterSpec(sKey.getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度  
	        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);  
	       
	        byte[] srawt = sSrc.getBytes("utf-8");
	        int len = srawt.length;
	        /* 计算补0后的长度 */
	        while(len % 16 != 0) len ++;
	        byte[] sraw = new byte[len];
	        /* 在最后补0 */
	        for (int i = 0; i < len; ++i) {
	            if (i < srawt.length) {
	                sraw[i] = srawt[i];
	            } else {
	                sraw[i] = 0;
	            }
	        }
	        byte[] encrypted = cipher.doFinal(sraw);  
	  
	        return urlSafeEncode(Base64.encodeBase64String(encrypted));  
	    }  
	  
	    // 解密  
	    public static String decrypt(String sSrc, String sKey) throws Exception {  
	        try {  
	            // 判断Key是否正确  
	            if (sKey == null) {  
	                System.out.print("Key为空null");  
	                return null;  
	            }  
	            // 判断Key是否为16位  
	            if (sKey.length() != 16) {  
	                System.out.print("Key长度不是16位");  
	                return null;  
	            }  
	            sSrc = urlSafeDecode(sSrc);
	            
	            byte[] raw = sKey.getBytes();  
	            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");  
	            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");  
	            IvParameterSpec iv = new IvParameterSpec(sKey.getBytes());  
	            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);  
	            byte[] encrypted1 = Base64.decodeBase64(sSrc);//先用base64解密  
	            try {  
	                byte[] original = cipher.doFinal(encrypted1);  
	                String originalString = new String(original,"utf-8");  
	                System.out.println(originalString);
	                return originalString.trim();  
	            } catch (Exception e) {  
	                System.out.println(e.toString());  
	                return null;  
	            }  
	        } catch (Exception ex) {  
	            System.out.println(ex.toString());  
	            return null;  
	        }  
	    } 
	    
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		String key = "eo9klprmiowqe0jd0001";
//		String text1 = "{\"ts\":\"1343961025\",\"uid\":\"xu31\",\"email\":\"[email protected]\",\"name\":\"张三\",\"companyName\":\"xxx科技公司\",\"phone\":\"13511028285\"}";
//		String text2 = "007;[email protected];1234;1";
//		String miwen = encrypt(text2, key);
//		System.out.println(miwen);
		String mingwen = decrypt("7OhAQLH+ZGj5DtG66Imcyyhdx7iKfnS04upZ6fb7mvRZdAtUTfcNa8mdh4smI38C0001", key);
		System.out.println(mingwen);
		
	}

}

Des工具类




import java.io.IOException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;

 
public class DesUtil {
 
    private final static String DES = "DES";
 
    public static void main(String[] args) throws Exception {
        String data = "";
        String key = "zhoujl*&^%$#@!";
        System.err.println(encrypt(data, key));
        System.err.println(decrypt(encrypt(data, key), key));
 
    }
     
    /**
     * Description 根据键值进行加密
     * @param data 
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
        byte[] bt = encrypt(data.getBytes(), key.getBytes());
        String strs = Base64.encodeBase64String(bt);
        return strs;
    }
 
    /**
     * Description 根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data, String key) throws IOException,
            Exception {
        if (data == null)
            return null;
        byte[] buf = Base64.decodeBase64(data);
        byte[] bt = decrypt(buf,key.getBytes());
        return new String(bt);
    }
 
    /**
     * Description 根据键值进行加密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
 
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
 
        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
 
        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);
 
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
 
        return cipher.doFinal(data);
    }
     
     
    /**
     * Description 根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
 
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
 
        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
 
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);
 
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
 
        return cipher.doFinal(data);
    }
}
发布了171 篇原创文章 · 获赞 214 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/mrlin6688/article/details/100763216