AES和RAS双重加密

一、加密签名
public Map sendContractInfo(Map objectMap) {
    Map paramMap = new HashMap();
    Map httpRes = null;
    // 发送请求到第三方
    try {
        String content = JSON.toJSONString(objectMap);
        // 1、生成8位随机的AES KEY
        String aeskey = RandomStringUtils.random(16, true, true);
        // 2、使用AES KEY加密后的主体内容--->加密数据段1
        content = AES_CBCUtils.encrypt(aeskey, content.getBytes("UTF-8"));
        // 3、将AES的秘钥使用公证处提供的RSA公钥加密得到 --->加密数据段2
        String encryptedkey = RSAUtil.encryptByPublicKey(aeskey, publicKey);
        String data = content + encryptedkey;
        // 4、加密数据段1+加密数据段2 MD5签名
        String signed = RSAUtil.sign(MD5Utils.sign(data).toLowerCase(), privateKey);

        paramMap.put("apiid", apiid);
        paramMap.put("key", encryptedkey);
        paramMap.put("signed", signed);
        paramMap.put("content", content);

        String contentType = "application/x-www-form-urlencoded;charset=utf-8";
        httpRes= SnHttpCilentUtil.requestPost(MapUtils.getString(paramMap, "signed", ""), url, "utf-8", SnHttpCilentUtil.socketTimeout,
                SnHttpCilentUtil.connectTimeout, paramMap, false, contentType);
        LOGGER.info("合同发起接口下发公证,返回结果:{}。", httpRes.toString());
    } catch (Exception e) {
        LOGGER.error("合同发起接口下发公证异常:"+ MsgHandleUtil.getExceptionString(e));
    }
    if(httpRes == null){
        httpRes = new HashMap();
    }

    return httpRes;
}

二、http请求

public static Map requestPost(String token,String url, String charset, int socketTimeout, int connectTimeout,
         Map paramMap, boolean isProxy, String contentType) {
//    SnHttpResult result = new SnHttpResult();
      Map resultMap=new HashMap();
      String content ="" ;
      CloseableHttpResponse response = null;
      CloseableHttpClient closeableHttpClient = null;
      try {
         HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
         
         closeableHttpClient = httpClientBuilder.build();
         
         
         Builder custom = RequestConfig.custom();
         custom.setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout);
         
//       if (isProxy) {
//          custom.setProxy(proxy);
//       }
         RequestConfig config = custom.build();
         
         HttpPost httpPost = new HttpPost(url);
         //设置cookie给mpossport
            if (!StringUtils.isNullOrEmpty(token)) {
                StringBuilder sb = new StringBuilder();
                sb.append("_device_session_id=");
                sb.append(token);
                sb.append(";");
                httpPost.addHeader("Cookie", sb.toString());
            }

         Iterator> entries = paramMap.entrySet().iterator();
         List formParams = new ArrayList();
         while (entries.hasNext()) {
            Map.Entry entry = entries.next();
            formParams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
         }
         // 设置参数到请求对象中
         httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
         
         httpPost.setConfig(config);  
         
         
//       StringEntity strEntity = new StringEntity(context, charset);
         
         // 设置参数到请求对象中
//       httpPost.setEntity(strEntity);

         // 设置header信息
         // 指定报文头【Content-type】、【User-Agent】
         httpPost.setHeader("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
         httpPost.setHeader("Content-Type", contentType);
         
         response = closeableHttpClient.execute(httpPost);

         Header[] headers=response.getAllHeaders();
         List cookieHeaders=new ArrayList();
         for (int i=0;i 
  

三、加密方法

1、AES_CBCUtils.java

public class AES_CBCUtils {

      private static Logger logger = LoggerFactory.getLogger(AES_CBCUtils.class);

   private static String        defaultencoding    = "UTF-8";
   private static byte[]        ips             = "0000000000000000".getBytes();
   private static IvParameterSpec iv          = new IvParameterSpec(ips);

        public static Cipher initCipher(String password, int mode) {
            SecretKey skeySpec = getKey(password);
            Cipher cipher = null;
            try {
                cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(mode, skeySpec, iv);
            } catch (Exception e) {
                logger.error("initCipher" + MsgHandleUtil.getExceptionString(e));
            }
            return cipher;
        }

   public static String encrypt(String password, byte[] content) {
      Cipher cipher = initCipher(password, Cipher.ENCRYPT_MODE);
          byte[] encrypted = new byte[0];
          try {
              encrypted = cipher.doFinal(content);
          } catch (Exception e) {
              logger.error("encrypt" + MsgHandleUtil.getExceptionString(e));
          }
          return Base64.encodeBase64String(encrypted);
   }

   public static String encrypt(Cipher cipher, byte[] content){
          byte[] encrypted = new byte[0];
          try {
              encrypted = cipher.doFinal(content);
          } catch (Exception e) {
              logger.error("encrypt" + MsgHandleUtil.getExceptionString(e));
          }
          return Base64.encodeBase64String(encrypted);
   }

   public static String decrypt(String password, String strIn) throws BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
      Cipher cipher = initCipher(password, Cipher.DECRYPT_MODE);
      byte[] encrypted1 = Base64.decodeBase64(strIn);
      byte[] original = cipher.doFinal(encrypted1);
      return new String(original, defaultencoding);
   }

   private static SecretKey getKey(String password) {
          byte[] arrBTmp = new byte[0];
          try {
              arrBTmp = password.getBytes(defaultencoding);
          } catch (Exception e) {
              logger.error("getKey" + MsgHandleUtil.getExceptionString(e));
          }
          byte[] arrB = new byte[16]; // 创建一个空的16位字节数组(默认值为0)
      for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
         arrB[i] = arrBTmp[i];
      }
      SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES");
      return skeySpec;
      // KeyGenerator kgen = KeyGenerator.getInstance("AES");
      // kgen.init(128, new SecureRandom(strKey.getBytes()));
      // SecretKey secretKey = kgen.generateKey();
      // return secretKey;
   }

// public static void main(String[] args) throws Exception {
//    String Code = "测试加密";
//    String password = "YgtJA3AKbKwoy2Ur";
//    // Cipher cipher = initCipher(password, Cipher.ENCRYPT_MODE);
//    long aaa = System.currentTimeMillis();
//    // for (int i = 0; i < 1000000; i++) {
//    // String t = encrypt(cipher, Code.getBytes("UTF-8"));
//    // }
//    // sYZPFymN4XVHcBNvrGMc1w==
//    String codE = encrypt(password, Code.getBytes("UTF-8"));
//    System.out.println("1000000加密时长 " + (System.currentTimeMillis() - aaa));
//    System.out.println("加密时长 " + (System.currentTimeMillis() - aaa));
//    System.out.println("原文:" + Code);
//    System.out.println("密钥:" + password);
//    System.out.println("密文:" + codE);
//    System.out.println("解密:" + decrypt(password + "2", codE));
//    String aaaaa = "{\"act\":\"U\",\"company_register_name\":\"仙鹤茗苑次卧C\",\"is_certification\":\"1\",\"register_email\":\"[email protected]\",\"register_mobile\":\"14442223332\",\"user_type\":\"1\",\"userid\":\"70058527\",\"username\":\"[email protected]\"}";
//    String text = "仙鹤茗苑次卧C";
//    System.out.println("原文 = " + text);
//    System.out.println(new String(text.getBytes("GBK"), "UTF-8"));
// }
}

2、RSAUtil.java

public class RSAUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtil.class);

    public static final String KEY_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";
    private static final String UTF_8 = "UTF-8";
    private static String privateKey_sn = "";
    private static String publicKey_sn = "";
    private static String privateKey_gzc = "";
    private static String publickey_gzc = "";

    public RSAUtil() {
    }

    public static String sign(String data, String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, UnsupportedEncodingException, SignatureException {
        byte[] keyBytes = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(priKey);
        signature.update(data.getBytes("UTF-8"));
        return new String(Base64.encodeBase64(signature.sign()), "UTF-8");
    }

    public static boolean verify(String data, String publicKey, String sign) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, UnsupportedEncodingException, SignatureException {
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(pubKey);
        signature.update(data.getBytes("UTF-8"));
        return signature.verify(Base64.decodeBase64(sign));
    }

    public static Map initKey() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
        Map keyMap = new HashMap(2);
        keyMap.put("RSAPublicKey", publicKey);
        keyMap.put("RSAPrivateKey", privateKey);
        return keyMap;
    }

    public static String getPrivateKey(Map keyMap) throws UnsupportedEncodingException {
        Key key = (Key)keyMap.get("RSAPrivateKey");
        return new String(Base64.encodeBase64(key.getEncoded()), "UTF-8");
    }

    public static String getPublicKey(Map keyMap) throws UnsupportedEncodingException {
        Key key = (Key)keyMap.get("RSAPublicKey");
        return new String(Base64.encodeBase64(key.getEncoded()), "UTF-8");
    }

    public static String encryptByPrivateKey(String data, String key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
        byte[] keyBytes = Base64.decodeBase64(key);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(1, privateKey);
        return new String(Base64.encodeBase64(cipher.doFinal(data.getBytes("UTF-8"))), "UTF-8");
    }

    public static String encryptByPublicKey(String data, String key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
        byte[] keyBytes = Base64.decodeBase64(key);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(1, publicKey);
        return new String(Base64.encodeBase64(cipher.doFinal(data.getBytes("UTF-8"))), "UTF-8");
    }

    public static String decryptByPrivateKey(String data, String key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
        byte[] keyBytes = Base64.decodeBase64(key);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(2, privateKey);
        byte[] data1 = Base64.decodeBase64(data.getBytes("UTF-8"));
        return new String(cipher.doFinal(data1), "UTF-8");
    }

    public static String decryptByPublicKey(String data, String key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
        byte[] keyBytes = Base64.decodeBase64(key);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(2, publicKey);
        byte[] data1 = Base64.decodeBase64(data.getBytes("UTF-8"));
        return new String(cipher.doFinal(data1), "UTF-8");
    }

//    public static void main(String[] args) throws Exception {
//        String source = "哈哈哈";
//        String aeskey = RandomStringUtils.random(16, true, true);
//        System.out.println("加密前的内容:" + source);
//        String content = com.raising.framework.utils.aes.AESUtil.encrypt(source, aeskey);
//        System.out.println("加密后的content内容:" + content);
//        String key = encryptByPublicKey(aeskey, publickey_gzc);
//        System.out.println("加密后的key内容:" + key);
//        String data = content + key;
//        String signed = sign(data, privateKey_sn);
//        System.out.println("加密后的signed内容:" + signed);
//        boolean isSame = verify(data, publicKey_sn, signed);
//        System.out.println(isSame);
//        if(isSame) {
//            String decodeKey = decryptByPrivateKey(key, privateKey_gzc);
//            String decryptResult = com.raising.framework.utils.aes.AESUtil.decrypt(content, decodeKey);
//            System.out.println("解密后的Key:" + decodeKey);
//            System.out.println("解密后的内容:" + decryptResult);
//        }
//
//    }

    static {
        try {
            Map keyMap = initKey();
            privateKey_sn = getPrivateKey(keyMap);
            publicKey_sn = getPublicKey(keyMap);
            keyMap = initKey();
            privateKey_gzc = getPrivateKey(keyMap);
            publickey_gzc = getPublicKey(keyMap);
        } catch (Exception var1) {
            LOGGER.error("初始化异常:"+var1);
        }

    }
}

四、解密

1、解密请求

String decipheringContent = AES_CBCUtils1.decrypt(key, content, privateKey);
map = new Gson().fromJson(decipheringContent, Map.class);

2、AES_CBCUtils1.java

public class AES_CBCUtils1 {
    private static final Logger LOGGER = LoggerFactory.getLogger(AES_CBCUtils1.class);

    public static JSONObject decrypt(String key, String signed, String content, String notary_publicKey,
                                     String business_privateKey) {
        try {
            if (verify(key, signed, content,notary_publicKey)) {
                String result = decrypt(key, content, business_privateKey);
                JSONObject jsonDecrypt = JSONObject.parseObject(result);
                String errorCode = jsonDecrypt.getString("errorCode");
                if("0".equals(errorCode)||"-9".equals(errorCode)){
                    return jsonDecrypt;
                }
            }
        } catch (Exception e) {
            LOGGER.error("AES_CBCUtils1解密异常:"+e);
        }
        return null;
    }



    public static boolean verify(String key, String signed, String content, String oppositePublicKey) throws InvalidKeySpecException, SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        return RSAUtil.verify(MD5Utils.sign(content + key).toLowerCase(), oppositePublicKey, signed);
    }





    public static String decrypt(String key, String content, String myPrivateKey) {
        String decryptContent = null;

        try {
            String decryptedKey = RSAUtil.decryptByPrivateKey(key, myPrivateKey);
            decryptContent = AES_CBCUtils.decrypt(decryptedKey, content);
        } catch (Exception var5) {
            LOGGER.error("AES_CBCUtils1解密异常:"+var5);
        }

        return decryptContent;
    }

你可能感兴趣的:(AES和RAS双重加密)