RSA和AES 组合

1、RSA和AES的区别:
总结于:http://www.360doc.com/content/16/0606/15/12385684_565529546.shtml#

RSA:

是公开**系统的代表;

安全性:建立在具有大素数因子的合数,其因子分解困难这一法则之上;

处理速度慢;

**管理:加解密过程中不必网络传输保密的**;**管理优于AES算法;

RSA加解密速度慢,不适合大量数据文件加密;

AES:

Rijndael算法是新一代的高级加密标准,运行时不需计算机有非常高的处理能力和大的内存;

操作可以很容易的抵御时间和空间的攻击,在不同的运行环境下始终保持良好的性能;

AES**长度:最长只有256bit,可用软件和硬件实现高速处理;

**管理:要求在通信前对**进行秘密分配,解密的私钥必须通过网络传送至加密数据接收方;

AES加密速度很快;

AES+RSA:

使用AES对称密码*对传输数据加密,同时使用RSA不对称密码*来传送AES的**,就可以综合发挥AES和RSA的优点同时

避免它们缺点来实现一种新的数据加密方案

2、RSA签名和验签的流程图:
特点:只需交换公钥;公/秘钥机制,公钥加密,私钥解密;(或者私钥加密,公钥解密);公钥负责加密,私钥负责解密;私钥负责签名,公钥负责验证。

缺点:加解密速度慢,特别是解密

RSA和AES 组合

3、AES框图:
特点:加解密用同一秘钥

优点:速度快,效率高;

存在的问题:秘钥交换问题

RSA和AES 组合

4、AES+RSA=数据加密方案:RSA和AES 组合

流程:

接收方创建RSA秘钥对,

发送RSA公钥给发送方,自己保留RSA私钥

发送方创建AES**,加密待传送的明文,之后用RSA公钥加密该**,

RSA公钥加密AES的**+AES**加密明文的密文----通过Internet发给---->接收方

接收方用RSA私钥解密加密的**,之后再用解密后的AES**解密数据密文,得到明文。
 

示例代码:AES

public class AESUtil {

    private static final String KEY = "zxcvbnmqwertyu12341";
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";


    /**
     * 加密
     * @param content 要加密数据
     * @param encryptKey 加密秘钥
     * @return
     */
    public static String AESEncode(String encryptKey,String content){
        try {
            return aesEncrypt(encryptKey,content);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 解密
     * @param content 要解密数据
     * @param decryptKey 解密秘钥
     * @return
     */
    public static String AESDncode(String decryptKey, String content){
        try {
            return aesDecrypt(decryptKey,content);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取加密字符串
     * @param encryptKey 秘钥
     * @param content 要加密数据
     * @return
     * @throws Exception
     */
    private static String aesEncrypt(String encryptKey, String content) throws Exception {
        //10.将加密后的数据转换为字符串
        //这里用Base64Encoder中会找不到包
        //解决办法:
        //在项目的Build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。
        return base64Encode(aesEncryptToBytes(encryptKey, content));
    }

    /**
     * 将加密数据进行base64解密
     * @param encryptData
     * @param decryptKey
     * @return
     * @throws Exception
     */
    private static String aesDecrypt(String decryptKey, String encryptData) throws Exception {
        //将加密并编码后的内容解码成字节数组
        return StringUtils.isEmpty(encryptData) ? null : aesDecryptByBytes(decryptKey,base64Decode(encryptData));
    }

    /**
     *  获取加密数据
     * 1.构造**生成器
     * 2.根据encryptKey规则初始化**生成器
     * 3.产生**
     * 4.创建和初始化密码器
     * 5.内容加密
     * 6.返回字符串
     * @param encryptKey 秘钥
     * @param content 要加密数据
     * @return
     * @throws Exception
     */
    private static byte[] aesEncryptToBytes(String encryptKey,String content)  throws Exception {
        try {
            //1.构造**生成器,指定为AES算法,不区分大小写
            KeyGenerator ******=KeyGenerator.getInstance("AES");
            //2.根据ecnodeRules规则初始化**生成器
            //生成一个128位的随机源,根据传入的字节数组
            ******.init(128, new SecureRandom(encryptKey.getBytes()));
            //3.产生原始对称**
            SecretKey original_key=******.generateKey();
            //4.获得原始对称**的字节数组
            byte [] raw=original_key.getEncoded();
            //5.根据字节数组生成AES**
            SecretKey secretKey=new SecretKeySpec(raw, "AES");
            //6.根据指定算法AES自成密码器
            Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
            //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            //8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
            byte [] byte_encode=content.getBytes("utf-8");
            //9.根据密码器的初始化方式--加密:将数据加密
            byte [] byte_AES=cipher.doFinal(byte_encode);

            return byte_AES;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e);
        }
    }

    /*
     * 解密
     * 解密过程:
     * 1.同加密1-4步
     * 2.将加密后的字符串反纺成byte[]数组
     * 3.将加密内容解密
     */
    private static String aesDecryptByBytes(String decryptKey,byte[] encryptBytes) throws Exception{
        try {
            //1.构造**生成器,指定为AES算法,不区分大小写
            KeyGenerator ******=KeyGenerator.getInstance("AES");
            //2.根据ecnodeRules规则初始化**生成器
            //生成一个128位的随机源,根据传入的字节数组
            ******.init(128, new SecureRandom(decryptKey.getBytes()));
            //3.产生原始对称**
            SecretKey original_key=******.generateKey();
            //4.获得原始对称**的字节数组
            byte [] raw=original_key.getEncoded();
            //5.根据字节数组生成AES**
            SecretKey key=new SecretKeySpec(raw, "AES");
            //6.根据指定算法AES自成密码器
            Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
            //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
            cipher.init(Cipher.DECRYPT_MODE, key);

            // 解密
            byte [] byte_decode=cipher.doFinal(encryptBytes);
            String AES_decode=new String(byte_decode,"utf-8");
            return AES_decode;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e);
        }
    }

    private static String base64Encode(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    private static byte[] base64Decode(String base64Code) throws Exception {
        return StringUtils.isEmpty(base64Code) ? null : (new BASE64Decoder()).decodeBuffer(base64Code);
    }

    public static void main(String[] args) {
        //加密
        String aesEncode = AESUtil.AESEncode(KEY, "NNNNNNNNNNNNNNNNaaaaaaaaaaaaaa123123");
        System.out.println(aesEncode);

        //解密
        String dncode = AESUtil.AESDncode(KEY, aesEncode);
        System.out.println(dncode);

    }


}
示例代码:RSA
public class RsaUtil {

    public RsaUtil() { }

    public static final String CHARSET = "UTF-8";
    public static final String RSA_ALGORITHM = "RSA";

    public static Map<String, String> createKeys(int keySize){
        //为RSA算法创建一个KeyPairGenerator对象
        KeyPairGenerator kpg;
        try{
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        }catch(NoSuchAlgorithmException e){
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
        }

        //初始化KeyPairGenerator对象,**长度
        kpg.initialize(keySize);
        //生成密匙对
        KeyPair keyPair = kpg.generateKeyPair();
        //得到公钥
        Key publicKey = keyPair.getPublic();
        String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
        //得到私钥
        Key privateKey = keyPair.getPrivate();
        String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
        Map<String, String> keyPairMap = new HashMap<String, String>();
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);

        return keyPairMap;
    }

    /**
     * 得到公钥
     * @param publicKey **字符串(经过base64编码)
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        return key;
    }

    /**
     * 得到私钥
     * @param privateKey **字符串(经过base64编码)
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        //通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        return key;
    }

    /**
     * 公钥加密
     * @param data
     * @param publicKey
     * @return
     */
    public static String publicEncrypt(String data, RSAPublicKey publicKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
        }catch(Exception e){
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateDecrypt(String data, String privateKey){
        try{
            RSAPrivateKey privateKeyRSA = RsaUtil.getPrivateKey(privateKey);

            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKeyRSA);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKeyRSA.getModulus().bitLength()), CHARSET);
        }catch(Exception e){
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize){
        int maxBlock = 0;
        if(opmode == Cipher.DECRYPT_MODE){
            maxBlock = keySize / 8;
        }else{
            maxBlock = keySize / 8 - 11;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try{
            while(datas.length > offSet){
                if(datas.length-offSet > maxBlock){
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                }else{
                    buff = cipher.doFinal(datas, offSet, datas.length-offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        }catch(Exception e){
            throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发生异常", e);
        }
        byte[] resultDatas = out.toByteArray();
        IOUtils.closeQuietly(out);
        return resultDatas;
    }


    public static void main(String[] args) throws Exception {

        String str = "123456advvd";
        //加密
        String aesEncode = AESUtil.AESEncode(str, "NNNNNNNNNNNNNNNNaaaaaaaaaaaaaa123123");
        System.out.println("要加密明文数据:" + aesEncode);

        Map<String, String> keyMap = RsaUtil.createKeys(1024);
        String  publicKey =  keyMap.get("publicKey");
        String  privateKey = keyMap.get("privateKey");
        System.out.println("公钥: \n\r" + publicKey);
        System.out.println("私钥: \n\r" + privateKey);

        System.out.println("公钥加密——私钥解密");

        System.out.println("\r明文:\r\n" + str);
        System.out.println("\r明文大小:\r\n" + str.getBytes().length);
        String encodedData = RsaUtil.publicEncrypt(str, RsaUtil.getPublicKey(publicKey));
        System.out.println("秘钥密文:\r\n" + encodedData);
        String decodedData = RsaUtil.privateDecrypt(encodedData, privateKey);
        System.out.println("解密后秘钥: \r\n" + decodedData);

        //解密
        String dncode = AESUtil.AESDncode(decodedData, aesEncode);
        System.out.println("解密后数据" + dncode);

    }
}