天天看點

AES和RAS加密方法的工具類實作

AES加密方法

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/** 
 * 編碼工具類 
 * 1.将byte[]轉為各種進制的字元串 
 * 7.AES加密 
 * 8.AES加密為base 64 code 
 * 9.AES解密 
 * 10.将base 64 code AES解密 
 * @author LiuDingchao 
 */

public class AESUtil {
	public static final String KEY = "8HGUkCAUtzBwDHgN";

    /** 
     * AES加密
     * @param content 待加密的内容 
     * @param encryptKey 加密密鑰 
     * @return 加密後的base 64 code 
     * @throws Exception 
     */  
    public static String aesEncrypt(String content, String encryptKey) throws Exception {  
        return parseByte2HexStr(aesEncryptToBytes(content, encryptKey));  
    } 
    
    /** 
     * AES解密 
     * @param encryptStr 待解密的base 64 code 
     * @param decryptKey 解密密鑰 
     * @return 解密後的string 
     * @throws Exception 
     */  
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {  
        return aesDecryptByBytes(parseHexStr2Byte(encryptStr), decryptKey);  
    }  
   
    /** 
     * AES加密 ECB加密
     * @param encryptStr 待加密的base 64 code 
     * @param decryptKey 加密密鑰 
     * @return 加密後的string 
     * @throws Exception 
     */  
    public static String aesEncryptC(String encryptStr, String decryptKey) throws Exception {  
    	byte[] str = aesEncryptToBytesC(encryptStr, decryptKey);
        return (str == null || str.length == 0)?"":parseByte2HexStr(str);  
    } 
    
    /** 
     * AES解密 ECB解密
     * @param encryptStr 待解密的base 64 code 
     * @param decryptKey 解密密鑰 
     * @return 解密後的string 
     * @throws Exception 
     */  
    public static String aesDecryptC(String encryptStr, String decryptKey) throws Exception {  
        return aesDecryptByBytesC(parseHexStr2Byte(encryptStr), decryptKey);  
    } 
   
    /** 
     * AES加密  
     * @param content 待加密的内容 
     * @param encryptKey 加密密鑰 
     * @return 加密後的byte[] 
     * @throws Exception 
     */  
    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {  
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(encryptKey.getBytes());
        kgen.init(128, random);
  
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));  
          
        return cipher.doFinal(content.getBytes("utf-8"));  
    }
    
    /**将二進制轉換成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();  
    }  
      
    /** 
     * AES解密 
     * @param encryptBytes 待解密的byte[] 
     * @param decryptKey 解密密鑰 
     * @return 解密後的String 
     * @throws Exception 
     */  
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {  
        KeyGenerator kgen = KeyGenerator.getInstance("AES");  
        SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(decryptKey.getBytes());
        kgen.init(128, random); 
          
        Cipher cipher = Cipher.getInstance("AES");  
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));  
        byte[] decryptBytes = cipher.doFinal(encryptBytes);  
          
        return new String(decryptBytes);  
    }  
    
    /**将16進制轉換成2進制 
     * @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;  
}
    
    /** 
     * AES加密 ECB
     * @param content 待加密的内容 
     * @param encryptKey 加密密鑰 
     * @return 加密後的byte[] 
     * @throws Exception 
     */ 
    public static byte[] aesEncryptToBytesC(String content, String encryptKey) {
        try {
            Cipher aesECB = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "AES");
            aesECB.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = aesECB.doFinal(content.getBytes("UTF-8"));
            return result;
        } 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();
        } catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        return null;
    }

      
    /** 
     * AES解密ECB
     * @param encryptBytes 待解密的byte[] 
     * @param decryptKey 解密密鑰 
     * @return 解密後的String 
     * @throws Exception 
     */ 
    public static String aesDecryptByBytesC(byte[] encryptBytes, String decryptKey) {
            try {
				Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 建立密碼器
				SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "AES");
				cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
				//byte[] result = parseHexStr2Byte(content);
				return new String(cipher.doFinal(encryptBytes),"utf-8"); // 解密
			} catch (InvalidKeyException e) {
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (NoSuchPaddingException e) {
				e.printStackTrace();
			} catch (IllegalBlockSizeException e) {
				e.printStackTrace();
			} catch (BadPaddingException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        return null;
    }

    /** 
     * AES加密 CBC加密
     * @param encryptStr 待加密的base 64 code 
     * @param decryptKey 加密密鑰 
     * @return 加密後的string 
     * @throws Exception 
     */  
	public static String aesEncryptCBC(String encryptStr, String decryptKey) {
		try {
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			int blockSize = cipher.getBlockSize();
			byte[] dataBytes = encryptStr.getBytes();
			int plaintextLength = dataBytes.length;
			if (plaintextLength % blockSize != 0) {
				plaintextLength = plaintextLength
						+ (blockSize - (plaintextLength % blockSize));
			}
			byte[] plaintext = new byte[plaintextLength];
			System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

			SecretKeySpec keyspec = new SecretKeySpec(decryptKey.getBytes(),
					"AES");
			IvParameterSpec ivspec = new IvParameterSpec(decryptKey.getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
			byte[] encrypted = cipher.doFinal(plaintext);

			return parseByte2HexStr(encrypted);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}



    /**
     * DES加密
     *
     * @param data 加密資料
     * @param key  密鑰
     * @return 傳回加密後的資料
     */
    public static byte[] desEncrypt(byte[] data, String key,String iv, String charset) {
        try {
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            byte[] i = charset == null || charset.trim().isEmpty() ? iv.getBytes() : iv.getBytes(charset);
            byte[] k = charset == null || charset.trim().isEmpty() ? key.getBytes() : key.getBytes(charset);
            SecretKey secretKey = SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(k));
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(i));
            return cipher.doFinal(data);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * DES解密
     *
     * @param data 解密資料
     * @param key  密鑰
     * @return 傳回解密後的資料
     */
    public static String desDecrypt(byte[] data, String key, String iv,String charset) {
        try {
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            byte[] i = charset == null || charset.trim().isEmpty() ? iv.getBytes() : iv.getBytes(charset);
            byte[] k = charset == null || charset.trim().isEmpty() ? key.getBytes() : key.getBytes(charset);
            cipher.init(Cipher.DECRYPT_MODE, SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(k)), new IvParameterSpec(i));
            if (charset == null || charset.trim().isEmpty()) {
                return new String(cipher.doFinal(data));
            }
            return new String(cipher.doFinal(data), charset);
        } catch (Exception e) {
            return null;
        }
    }


    public static void main(String[] args) {
        String key="12345678abcdefgh";
        String data="{'fpqqlsh':'19042015143601000043'}";
        System.out.println(Byte2Hex.byte2Hex(desEncrypt(data.getBytes(),key.substring(0,8),key.substring(key.length()-8),"UTF-8")));
    }
}
           

RSA加密

import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;

public class RSAUtil {

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 擷取密鑰對
     *
     * @return 密鑰對
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(1024);
        return generator.generateKeyPair();
    }

    /**
     * 擷取私鑰
     *
     * @param privateKey 私鑰字元串
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 擷取公鑰
     *
     * @param publicKey 公鑰字元串
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * RSA加密
     *
     * @param data 待加密資料
     * @param publicKey 公鑰
     * @return
     */
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 對資料分段加密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 擷取加密内容使用base64進行編碼,并以UTF-8為标準轉化成字元串
        // 加密後的字元串
        return new String(Base64.encodeBase64String(encryptedData));
    }

    /**
     * RSA解密
     *
     * @param data 待解密資料
     * @param privateKey 私鑰
     * @return
     */
    public static String decrypt(String data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 對資料分段解密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密後的内容
        return new String(decryptedData, "UTF-8");
    }

    /**
     * 簽名
     *
     * @param data 待簽名資料
     * @param privateKey 私鑰
     * @return 簽名
     */
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(key);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }

    /**
     * 驗簽
     *
     * @param srcData 原始字元串
     * @param publicKey 公鑰
     * @param sign 簽名
     * @return 是否驗簽通過
     */
    public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(key);
        signature.update(srcData.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }

    public static void main(String[] args) {
        try {
            // 生成密鑰對
            KeyPair keyPair = getKeyPair();
            String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
            String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
            System.out.println("私鑰:" + privateKey);
            System.out.println("公鑰:" + publicKey);
            // RSA加密
            String data = "待加密的文字内容";
            String encryptData = encrypt(data, getPublicKey(publicKey));
            System.out.println("加密後内容:" + encryptData);
            // RSA解密
            String decryptData = decrypt(encryptData, getPrivateKey(privateKey));
            System.out.println("解密後内容:" + decryptData);

            // RSA簽名
            String sign = sign(data, getPrivateKey(privateKey));
            // RSA驗簽
            boolean result = verify(data, getPublicKey(publicKey), sign);
            System.out.print("驗簽結果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("加解密異常");
        }
    }
}