java rsa and aes 双向校验

package com.scoket.RSAANDAESUtil;

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

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;

public class AESUtil {

    //生成AES秘钥,然后Base64编码
    public static String genKeyAES() throws Exception{
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey key = keyGen.generateKey();
        String base64Str = byte2Base64(key.getEncoded());
        return base64Str;
    }

    //将Base64编码后的AES秘钥转换成SecretKey对象
    public static SecretKey loadKeyAES(String base64Key) throws Exception{
        byte[] bytes = base642Byte(base64Key);
        SecretKeySpec key = new SecretKeySpec(bytes, "AES");
        return key;
    }

    //加密
    public static byte[] encryptAES(byte[] source, SecretKey key) throws Exception{
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(source);
    }

    //解密
    public static byte[] decryptAES(byte[] source, SecretKey key) throws Exception{
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(source);
    }

    //字节数组转Base64编码
    public static String byte2Base64(byte[] bytes){
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }

    //Base64编码转字节数组
    public static byte[] base642Byte(String base64Key) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(base64Key);
    }

}
package com.scoket.RSAANDAESUtil;

import com.google.gson.Gson;

import javax.crypto.SecretKey;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

public class HttpEncryptUtil {

    //APP加密请求内容
    public static String appEncrypt(String appPublicKeyStr,String serverPublicKeyStr,String content) throws Exception{
        //将Base64编码后的Server公钥转换成PublicKey对象
        PublicKey serverPublicKey = RSAUtil.string2PublicKey(serverPublicKeyStr);
        //每次都随机生成AES秘钥
        String aesKeyStr = AESUtil.genKeyAES();
        SecretKey aesKey = AESUtil.loadKeyAES(aesKeyStr);
        //用Server公钥加密AES秘钥
        byte[] encryptAesKey = RSAUtil.publicEncrypt(aesKeyStr.getBytes(), serverPublicKey);
        //用AES秘钥加密APP公钥
        byte[] encryptAppPublicKey = AESUtil.encryptAES(appPublicKeyStr.getBytes(), aesKey);
        //用AES秘钥加密请求内容
        byte[] encryptRequest = AESUtil.encryptAES(content.getBytes(), aesKey);

        Map<String,Object> map = new HashMap<>();
        map.put("ak", RSAUtil.byte2Base64(encryptAesKey).replaceAll("\r\n", ""));
        map.put("apk", RSAUtil.byte2Base64(encryptAppPublicKey).replaceAll("\r\n", ""));
        map.put("ct", RSAUtil.byte2Base64(encryptRequest).replaceAll("\r\n", ""));
        return new Gson().toJson(map);
    }

    //APP解密服务器的响应内容
    public static String appDecrypt(String appPrivateKeyStr, String content) throws Exception{
        Map<String,Object> map = new Gson().fromJson(content,Map.class);
        String encryptAesKeyStr = (String) map.get("ak");
        String encryptContent = (String) map.get("ct");
        //将Base64编码后的APP私钥转换成PrivateKey对象
        PrivateKey appPrivateKey = RSAUtil.string2PrivateKey(appPrivateKeyStr);
        //用APP私钥解密AES秘钥
        byte[] aesKeyBytes = RSAUtil.privateDecrypt(RSAUtil.base642Byte(encryptAesKeyStr), appPrivateKey);
        //用AES秘钥解密请求内容
        SecretKey aesKey = AESUtil.loadKeyAES(new String(aesKeyBytes));
        byte[] response = AESUtil.decryptAES(RSAUtil.base642Byte(encryptContent), aesKey);

        return new String(response);
    }

    /**
     * 服务器加密响应给APP的内容
     * @param appPublicKeyStr app公钥
     * @param aesKeyStr aes key
     * @param content 需要加密的内容
     * @return
     */
    public static String serverEncrypt(String appPublicKeyStr, String aesKeyStr, String content) throws Exception{
        //将Base64编码后的APP公钥转换成PublicKey对象
        PublicKey appPublicKey = RSAUtil.string2PublicKey(appPublicKeyStr);
        //将Base64编码后的AES秘钥转换成SecretKey对象
        SecretKey aesKey = AESUtil.loadKeyAES(aesKeyStr);
        //用APP公钥加密AES秘钥
        byte[] encryptAesKey = RSAUtil.publicEncrypt(aesKeyStr.getBytes(), appPublicKey);
        //用AES秘钥加密响应内容
        byte[] encryptContent = AESUtil.encryptAES(content.getBytes(), aesKey);
        Map<String,Object> map = new HashMap<>();
        map.put("ak", RSAUtil.byte2Base64(encryptAesKey).replaceAll("\r\n", ""));
        map.put("ct", RSAUtil.byte2Base64(encryptContent).replaceAll("\r\n", ""));
        return new Gson().toJson(map);
    }

    /**
     * 服务器解密请求内容
     * @param content 请求内容
     * @return
     */
    public static String serverDecrypt(String content) throws Exception{
        Map<String,Object> map = new Gson().fromJson(content,Map.class);
        String encryptAesKeyStr = (String) map.get("ak");
        String encryptAppPublicKeyStr = (String) map.get("apk");
        String encryptContent = (String) map.get("ct");
        //将Base64编码后的Server私钥转换成PrivateKey对象
        PrivateKey serverPrivateKey = RSAUtil.string2PrivateKey(KeyUtil.SERVER_PRIVATE_KEY);
        //用Server私钥解密AES秘钥
        byte[] aesKeyBytes = RSAUtil.privateDecrypt(RSAUtil.base642Byte(encryptAesKeyStr), serverPrivateKey);
        //用AES秘钥解密APP公钥
        SecretKey aesKey = AESUtil.loadKeyAES(new String(aesKeyBytes));
        byte[] appPublicKeyBytes = AESUtil.decryptAES(RSAUtil.base642Byte(encryptAppPublicKeyStr), aesKey);
        //用AES秘钥解密请求内容
        byte[] request = AESUtil.decryptAES(RSAUtil.base642Byte(encryptContent), aesKey);

        Map<String,String> map1 = new HashMap<>();
        map1.put("ak", new String(aesKeyBytes));
        map1.put("apk", new String(appPublicKeyBytes));
        map1.put("ct", new String(request));
        return new String(request);
    }

}
package com.scoket.RSAANDAESUtil;

/**
 * Created by kongweichun on 2018/7/10.
 */
public class KeyUtil {

    //服务端的RSA公钥(Base64编码)
    public final static String SERVER_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmAaaybBOBSLONcHM86xnXDdim7Y3k+XBSEJEXiChWjbzDP8NHxyEL85eltxUPi2nXqlfM+Cec0+/suMrAA4LlNvAUGyZzGiR/jgGdTn/7xG0TsJH2cxuZCNARiWWNUxV9ndHZZh0eoDhwSVJyYLUiHU+bOIdzsZacQoaZC1LTZMg1OgA9tbUZM6eR0nxV1N4YTi5QGBAOk2WhZYPI1x08DuP5mE92JDJIQPW/zfvXMrO5Liis1WDk8/5X7owih9/e0s3pnkoAMAEXqqpFLyO+cRb2zQMS3iwrfRxcxsptWlOM35OvHzDjmtYXiLWruy8N4+BXgctbD9cqXrhBLxbpQIDAQAB";

    //服务端的RSA私钥(Base64编码)
    public final static String SERVER_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCYBprJsE4FIs41wczzrGdcN2KbtjeT5cFIQkReIKFaNvMM/w0fHIQvzl6W3FQ+LadeqV8z4J5zT7+y4ysADguU28BQbJnMaJH+OAZ1Of/vEbROwkfZzG5kI0BGJZY1TFX2d0dlmHR6gOHBJUnJgtSIdT5s4h3OxlpxChpkLUtNkyDU6AD21tRkzp5HSfFXU3hhOLlAYEA6TZaFlg8jXHTwO4/mYT3YkMkhA9b/N+9cys7kuKKzVYOTz/lfujCKH397SzemeSgAwAReqqkUvI75xFvbNAxLeLCt9HFzGym1aU4zfk68fMOOa1heItau7Lw3j4FeBy1sP1ypeuEEvFulAgMBAAECggEBAInXQzWoM7WYb1xykgBGy5jjZvdEanQhF/UKkK6/60y/EfUwtJcG5hvqg/1JXODbyCueaoHBIinvnyL1sqFkGsAn1+GT9odOMUFNTx2vLw13AgN/SGKEZ3tIMxjnL6C3zCGi2QuXBdWlUgwsYRDjHQ11MNrM0rYPRyXDQVafcu2sFfwkCrJ6dS/wPaWUrsVNuxreo8FeLeJ/Ejbq/xUF9iLJxaKGFP/mmYZM/MZY3APFsmVg6SVbTAeERusKbmNOoz+4T13L50533cvsPKi8YPQsRSHKPDEeaMWarOBb89P5Gw1dT6V8h80/+gEfw7R5J4Lr0GOaEBZOGTXXm7QK74ECgYEA40f5MQklLfsJU60E8jxKeoWlNS8S/Q0xEzkJj9oZ8DPMEISVt2M+tKt5Y3qRYjQYT+n7e7eMn1V4GdFKHokWL/d4FWdb8PtQbLkn32mgWlb7CHezpxHsCigqVGmYPr+3S0lgxgEll/eJeEgzwrMFZgUU3W7QfdbSJAUon2y5jdECgYEAqzxK3ZVJDJWARImYcbheBkX2l6tyx/oXBW598bg72C6ca91fKxCbIbc/LtKuhRvMwgS+1IhbvhHUdrCc67s9V58STdhBY+KI4VNjcGPtF8KZ7iV+E+OtKQ9gp+/JvkjLwKlWD8FGwlvnihtsapX1xxr3zePP7/jVILS5KcD/AZUCgYA5hf7Y3VKup4m9xt2onX/QMMEWi9qHd25DSj1UTkQgWku8poHqD1FQktG/Tsc7DqpUl4jR0CvkK9Kg3iqfPd0CuOSIrkdD36eETPx9fBNcqgURKJKsp0mRbIcCJFOnFgjDIkg+9Q1ZwAnoCoYnMf4cyw5z2Ncl8lfvS+rzJqZz8QKBgHGsOr7SRYYXEOlutkZ37+MWOtcAt9fNS88NRIpclU2z058/e9fo1DMTpNv+fGBczhbWc6A/TTfmOjb4k5Nh3xz1un722qHmVpvOcarAizpEs08GkKW/dMpXLQEPC8xIIwqo3zriQYjw3cou3k/7cQdV/b8uRnG1rDZkAq+XMTHpAoGBAJejNpkDeWS+TGFlqWmlrU1Ty7E5wiXo0tRr4x08FN5cTMxJzADjpByAvPIcT6uyM87afFSp05xX8Y1WhQbmeghpd1fvpiVrHDCso1ckOqi3elUloOo+LEI6Gk1dorkemj9Z6PfeuBgfHMBS9Lh7tUnjolK+jd44wQn998AjlI5O";

}
package com.scoket.RSAANDAESUtil;

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

import javax.crypto.Cipher;
import java.io.IOException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtil {

    //生成秘钥对
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return keyPair;
    }

    //获取公钥(Base64编码)
    public static String getPublicKey(KeyPair keyPair){
        PublicKey publicKey = keyPair.getPublic();
        byte[] bytes = publicKey.getEncoded();
        return byte2Base64(bytes);
    }

    //获取私钥(Base64编码)
    public static String getPrivateKey(KeyPair keyPair){
        PrivateKey privateKey = keyPair.getPrivate();
        byte[] bytes = privateKey.getEncoded();
        return byte2Base64(bytes);
    }

    //将Base64编码后的公钥转换成PublicKey对象
    public static PublicKey string2PublicKey(String pubStr) throws Exception{
        byte[] keyBytes = base642Byte(pubStr);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    //将Base64编码后的私钥转换成PrivateKey对象
    public static PrivateKey string2PrivateKey(String priStr) throws Exception{
        byte[] keyBytes = base642Byte(priStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    //公钥加密
    public static byte[] publicEncrypt(byte[] content, PublicKey publicKey) throws Exception{
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] bytes = cipher.doFinal(content);
        return bytes;
    }

    //私钥解密
    public static byte[] privateDecrypt(byte[] content, PrivateKey privateKey) throws Exception{
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] bytes = cipher.doFinal(content);
        return bytes;
    }

    //字节数组转Base64编码
    public static String byte2Base64(byte[] bytes){
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }

    //Base64编码转字节数组
    public static byte[] base642Byte(String base64Key) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(base64Key);
    }

}
package com.scoket.RSAANDAESUtil;

import com.jtws.common.base.BaseTest;
import org.junit.Test;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

/**
 * 1:app加密
 * 2:服务端解密
 * 3:服务端加密
 * 4:app解密
 *
 *  健泰卫士端为服务端
 *  优顾端为app端
 *
 *  优顾端自行生成一对密钥,将公钥给健泰卫士
 *
 */
public class TestHttpEncrypt extends BaseTest{

    //app公钥
    private final String appPublicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmdTS0fGjmaQBAjrWZlbdMeWPJuEdJa6E\n" +
            "gUoeklOrfmsuLn+TCApINQ+FFlUPL+X75pqkgC1TUPco3H9HvkRuMfmdOCLG726SM/BY17HhwXc5\n" +
            "XWdAB3hhBfM191rMoDq6renQds07NKyklBT1Nrp9wmguun5j4pgo49eDlI9nzSd5j9xBQQVpQ7NE\n" +
            "1RZzI6KFNvqmFu0Y40SRDR+Mm53DL4koDdrlc9QsCe6TZs7Gp82HKFjS9nuxi0LTKC2Bm+gkO6h+\n" +
            "ysTyYEVDzqE+uPjmC4KRznQsj2NefAT0opJ6NrS96WXtTxXhy8VAN97LBR1LGnpXD6C3BmcTyOf+\n" +
            "Rr0kkQIDAQAB";

    //app私钥
    private final String appPrivatKet = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCZ1NLR8aOZpAECOtZmVt0x5Y8m\n" +
            "4R0lroSBSh6SU6t+ay4uf5MICkg1D4UWVQ8v5fvmmqSALVNQ9yjcf0e+RG4x+Z04IsbvbpIz8FjX\n" +
            "seHBdzldZ0AHeGEF8zX3WsygOrqt6dB2zTs0rKSUFPU2un3CaC66fmPimCjj14OUj2fNJ3mP3EFB\n" +
            "BWlDs0TVFnMjooU2+qYW7RjjRJENH4ybncMviSgN2uVz1CwJ7pNmzsanzYcoWNL2e7GLQtMoLYGb\n" +
            "6CQ7qH7KxPJgRUPOoT64+OYLgpHOdCyPY158BPSikno2tL3pZe1PFeHLxUA33ssFHUsaelcPoLcG\n" +
            "ZxPI5/5GvSSRAgMBAAECggEBAI4UJQtHNSVIdq4Kjc9D11Sog4kTTgppn3SScp4PrUs7zxGfPruk\n" +
            "U4C+bttrgHVq4zfgCKNiOZuETDcrT6YKKgT6WR1p8XdfFqXmDQhbAPnhFhiQrnC33FTUhzmIoYoz\n" +
            "9AuA8stnTpGeCvvCR6FeqZyPAOm6pqK4iru1Z5Aky2iM5mn162rdinGKVUM23HNTjmAEbZ3dsP1H\n" +
            "BmnK3XQ6stlBFyYIVZoof7eiuezEoNOI7ZeLd4gmuubY5a3/oKSoxT6YUNcyO0Iam8EWPAFaYV8c\n" +
            "2J0dahSqu50X9jJ2qhko/6J03qnj4p1/DSD25r84RKyq29n59JW7XdNNlS3MWeECgYEA3OCce1Rt\n" +
            "gnda7GUHMfFW2vV8Ehu6KWEaIxm/M9R/CiK4MWp7hcMwdh7xVNFkrUqNf8hyP0alI8/Enx6CUST3\n" +
            "MUZsQzQI97KaBK7aWI0YHxTCj4ba/qGuY4EgHf9SspiTeoD41bAv8dRijjWNBs7zdOSCPER9UxXL\n" +
            "RWMSdwO924UCgYEAskrts6rMVuVLc32ER/IWEGdk5ApxvuJdklPmkj/duOgOLT4D4OStLSQ8Oqth\n" +
            "Dvwe8UDaZFZPngraQZODY4lZgaP70qLpAKPqrad2LrBYxsnTTd20b7x5cGLpSmix6NOzwTTtjpaB\n" +
            "QsMLhtPoJ0UY2AaEr0XDe/ay821BOtlktJ0CgYEArKwjaP7txYrNV/T7FP4Y6n/zCK0IcgTpS/t6\n" +
            "0GgVELVnzany+vVG03EJNUelLxwTVow7VGBEBaUNj19ofUsqvCjTxg3N3OaRJYwUQhm7e8DdARtp\n" +
            "5Jo9HKj7lLffzKMe2CwvW86rDKD+kzImF+Z9ySpC7h6U4vksugfjjYstR4kCgYBB/avHgWNKkmn/\n" +
            "4ChS/M6f2bUlFpyNO3nIzFceMJdfdjyxEDAdUGasu6mzSXWON1E4mHl9A9lKNNgdx3ytHcxMSKbP\n" +
            "is7VFtao2b/LfigNw+v6+SFs7gTAzUtt6BxZgeoZi/6VdS14yXp9t/dIebG9W4RG33qAaopHwVuQ\n" +
            "baBxnQKBgBpcNAfPVPMN3LnsXC/UYiM8e6xSMXS1v0TBHj2XScdHxHYUBT9yyzk+n4XJ0G+loQWo\n" +
            "u4eaMS2u2r8yQ3pL8oJom0LnQr+fxnjm1ttlITViSiYBseV1Jbq+ZI7M5mTTog1AMn8wdSwt176L\n" +
            "SvtQ398JRA/7ndunvnfdFWulFU8m";


    /**
     * 生成密钥对
     * @throws Exception
     */
    @Test
    public void testGenerateKeyPair() throws Exception{
        //生成RSA公钥和私钥,并Base64编码
        KeyPair keyPair = RSAUtil.getKeyPair();
        String publicKeyStr = RSAUtil.getPublicKey(keyPair);
        String privateKeyStr = RSAUtil.getPrivateKey(keyPair);
        System.out.println("==========");
        System.out.println("RSA公钥Base64编码:" + publicKeyStr);
        System.out.println("RSA私钥Base64编码:" + privateKeyStr);
    }


    @Test
    public void testRsa() throws Exception{
        //加密参数
        Map<String,String> map = new HashMap<>();
        map.put("name","阿狸");
        map.put("sex","2");
        map.put("password","123456");
        String mapStr = map.toString();
        //app端加密
        String appSecret = HttpEncryptUtil.appEncrypt(appPublicKey,KeyUtil.SERVER_PUBLIC_KEY,mapStr);
        //服务端解密
        String serverContent = HttpEncryptUtil.serverDecrypt(appSecret);
        //服务端加密
        String serverSecret = HttpEncryptUtil.serverEncrypt(appPublicKey,AESUtil.genKeyAES(),mapStr);
        //app端解密
        String appContent = HttpEncryptUtil.appDecrypt(appPrivatKet,serverSecret);

        System.out.println("app端解密内容="+appContent);
        System.out.println("服务端解密内容="+serverContent);

    }

}

 

posted @ 2019-01-29 10:24  铅笔coding  阅读(655)  评论(0编辑  收藏  举报