JAVA RSA加密AES加密

RSA加密:java

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiang.li on 2015/3/3.
 * RSA 加解密工具類
 */
public class RSAEncrypt {
    /**
     * 定義加密方式
     */
    private final static String KEY_RSA = "RSA";
    /**
     * 定義簽名算法
     */
    private final static String KEY_RSA_SIGNATURE = "MD5withRSA";
    /**
     * 定義公鑰算法
     */
    private final static String KEY_RSA_PUBLICKEY = "RSAPublicKey";
    /**
     * 定義私鑰算法
     */
    private final static String KEY_RSA_PRIVATEKEY = "RSAPrivateKey";

    /**
     * 初始化密鑰
     * @return
     */
    public static Map<String, Object> init() {
        Map<String, Object> map = null;
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_RSA);
            generator.initialize(1024);
            KeyPair keyPair = generator.generateKeyPair();
            // 公鑰
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            // 私鑰
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            // 將密鑰封裝爲map
            map = new HashMap();
            map.put(KEY_RSA_PUBLICKEY, publicKey);
            map.put(KEY_RSA_PRIVATEKEY, privateKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 用私鑰對信息生成數字簽名
     * @param data 加密數據
     * @param privateKey 私鑰
     * @return
     */
    public static String sign(byte[] data, String privateKey) {
        String str = "";
        try {
            // 解密由base64編碼的私鑰
            byte[] bytes = decryptBase64(privateKey);
            // 構造PKCS8EncodedKeySpec對象
            PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(bytes);
            // 指定的加密算法
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            // 取私鑰對象
            PrivateKey key = factory.generatePrivate(pkcs);
            // 用私鑰對信息生成數字簽名
            Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);
            signature.initSign(key);
            signature.update(data);
            str = encryptBase64(signature.sign());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 校驗數字簽名
     * @param data 加密數據
     * @param publicKey 公鑰
     * @param sign 數字簽名
     * @return 校驗成功返回true,失敗返回false
     */
    public static boolean verify(byte[] data, String publicKey, String sign) {
        boolean flag = false;
        try {
            // 解密由base64編碼的公鑰
            byte[] bytes = decryptBase64(publicKey);
            // 構造X509EncodedKeySpec對象
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
            // 指定的加密算法
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            // 取公鑰對象
            PublicKey key = factory.generatePublic(keySpec);
            // 用公鑰驗證數字簽名
            Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);
            signature.initVerify(key);
            signature.update(data);
            flag = signature.verify(decryptBase64(sign));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 私鑰解密
     * @param data 加密數據
     * @param key 私鑰
     * @return
     */
    public static byte[] decryptByPrivateKey(byte[] data, String key) {
        byte[] result = null;
        try {
            // 對私鑰解密
            byte[] bytes = decryptBase64(key);
            // 取得私鑰
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            PrivateKey privateKey = factory.generatePrivate(keySpec);
            // 對數據解密
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            result = cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 私鑰解密
     * @param source
     * @param privateKey
     * @return
     */
    public static String decryptByPublicKey(String source,String privateKey) throws Exception{
        byte[] word=decryptBase64(source);
        String decWord = new String(decryptByPrivateKey(word, privateKey));
        return decWord;
    }

    /**
     * 私鑰解密
     * @param data 加密數據
     * @param key 公鑰
     * @return
     */
    public static byte[] decryptByPublicKey(byte[] data, String key) {
        byte[] result = null;
        try {
            // 對公鑰解密
            byte[] bytes = decryptBase64(key);
            // 取得公鑰
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            PublicKey publicKey = factory.generatePublic(keySpec);
            // 對數據解密
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            result = cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 公鑰加密
     * @param data 待加密數據
     * @param key 公鑰
     * @return
     */
    public static byte[] encryptByPublicKey(byte[] data, String key) {
        byte[] result = null;
        try {
            byte[] bytes = decryptBase64(key);
            // 取得公鑰
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            PublicKey publicKey = factory.generatePublic(keySpec);
            // 對數據加密
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            result = cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 私鑰加密
     * @param data 待加密數據
     * @param key 私鑰
     * @return
     */
    public static byte[] encryptByPrivateKey(byte[] data, String key) {
        byte[] result = null;
        try {
            byte[] bytes = decryptBase64(key);
            // 取得私鑰
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            PrivateKey privateKey = factory.generatePrivate(keySpec);
            // 對數據加密
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            result = cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 獲取公鑰
     * @param map
     * @return
     */
    public static String getPublicKey(Map<String, Object> map) {
        String str = "";
        try {
            Key key = (Key) map.get(KEY_RSA_PUBLICKEY);
            str = encryptBase64(key.getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 獲取私鑰
     * @param map
     * @return
     */
    public static String getPrivateKey(Map<String, Object> map) {
        String str = "";
        try {
            Key key = (Key) map.get(KEY_RSA_PRIVATEKEY);
            str = encryptBase64(key.getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * BASE64 解密
     * @param key 須要解密的字符串
     * @return 字節數組
     * @throws Exception
     */
    public static byte[] decryptBase64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }

    /**
     * BASE64 加密
     * @param key 須要加密的字節數組
     * @return 字符串
     * @throws Exception
     */
    public static String encryptBase64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }


    public static String privateKey= "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKcsdtVapeDOkxJX\n" +
            "D8QxweV+R9Vt1mDMs44vS4zDa3cr/DVEvvecHAjc6jdpgwQ6k+H5Dx54JlHOk463\n" +
            "3YLI9Iy+1+opy13GXeQ2vdV95B7UQKxPhzcf092H0uA4RKelTYaYCghNLH7xflPB\n" +
            "lFM1le7KrLHEc4xngpUWx9Us8ETVAgMBAAECgYAxVJqgbMZkJzEZCV3arEAmQ3RZ\n" +
            "E7deCym0/FnT6NquaOlcorOjh4pyRxZKUbVaqxp2ZTND73qHS2kZhUI1VK1s3M9y\n" +
            "i7HuOKncuDp4W96CwI6owoDlAiGcvDXAuptMauXzvh3Woww7VrJ0xvSHwOMCPFxj\n" +
            "DN2nqDD7a+jjNVANZQJBAM1CjzizQn/M69ERkSSlbvJIXYNjdj1oYBOVINt2+Jjn\n" +
            "kZDuF7vqX+ycKB7XZDmX4rLvbLB8wI73vdaID+KlsGsCQQDQf7Goo5dXxiCE0XhG\n" +
            "W0/ARmsH5fefBQHRdAWmHMOoF8SapYiWnweyDyUrnBT4b0QVHC1hJ+Mh9lkBobM7\n" +
            "Si+/AkEAxOD72SnwNf9Ljaxo6JqZsWEB+T2Us1ADH6Vh77/MsXUkZbxKHZ+wRJZ/\n" +
            "0R1OcAOkmXcXbK0sUbWFbFnzyrScYwJAL8jUQr4bdXZnBYmscxOCV6LL7Od7tOpE\n" +
            "3Ggm00dMYD3yRS8i+sI/1UM7VZ9T/wwhImVu0RF/MM1w4LrahQAfqQJBAJo5L4IV\n" +
            "mQdbs6D3wflp4/lI4DTCM7fBISrT2j3nR/RMhTd4pcY62qADbGWjE6jEZWk/yQZV\n" +
            "ug8HHCCjeRVf6U4=\n";
    public static String publicKey= "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnLHbVWqXgzpMSVw/EMcHlfkfV\n" +
            "bdZgzLOOL0uMw2t3K/w1RL73nBwI3Oo3aYMEOpPh+Q8eeCZRzpOOt92CyPSMvtfq\n" +
            "Kctdxl3kNr3VfeQe1ECsT4c3H9Pdh9LgOESnpU2GmAoITSx+8X5TwZRTNZXuyqyx\n" +
            "xHOMZ4KVFsfVLPBE1QIDAQAB\n";

}

AES加密:算法

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

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class AesEncodeUtil {

    //初始向量
    public static final String VIPARA = "0102030405060708";   //AES 爲16bytes. DES 爲8bytes

    //編碼方式
    public static final String bm = "UTF-8";

    //私鑰
    private static final String ASE_KEY="abc";   //AES固定格式爲128/192/256 bits.即:16/24/32bytes。DES固定格式爲128bits,即8bytes。

    /**
     * 加密
     *
     * @param cleartext
     * @return
     */
    public static String encrypt(String cleartext) {
        //加密方式: AES128(CBC/PKCS5Padding) + Base64, 私鑰:aabbccddeeffgghh
        try {
            IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
            //兩個參數,第一個爲私鑰字節數組, 第二個爲加密方式 AES或者DES
            SecretKeySpec key = new SecretKeySpec(ASE_KEY.getBytes(), "AES");
            //實例化加密類,參數爲加密方式,要寫全
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //PKCS5Padding比PKCS7Padding效率高,PKCS7Padding可支持IOS加解密
            //初始化,此方法能夠採用三種方式,按加密算法要求來添加。(1)無第三個參數(2)第三個參數爲SecureRandom random = new SecureRandom();中random對象,隨機數。(AES不可採用這種方法)(3)採用此代碼中的IVParameterSpec
            cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
            //加密操做,返回加密後的字節數組,而後須要編碼。主要編解碼方式有Base64, HEX, UUE,7bit等等。此處看服務器須要什麼編碼方式
            byte[] encryptedData = cipher.doFinal(cleartext.getBytes(bm));

            return new BASE64Encoder().encode(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 解密
     *
     * @param encrypted
     * @return
     */
    public static String decrypt(String encrypted) {
        try {
            byte[] byteMi = new BASE64Decoder().decodeBuffer(encrypted);
            IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
            SecretKeySpec key = new SecretKeySpec(
                    ASE_KEY.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            //與加密時不一樣MODE:Cipher.DECRYPT_MODE
            cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
            byte[] decryptedData = cipher.doFinal(byteMi);
            return new String(decryptedData, bm);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 測試
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {


        String content = "test";
        // 加密
        System.out.println("加密前:" + content);
        String encryptResult = encrypt(content);

        System.out.println("加密後:" + new String(encryptResult));
        // 解密
        String decryptResult = decrypt(encryptResult);
        System.out.println("解密後:" + new String(decryptResult));


    }
}
相關文章
相關標籤/搜索