公司项目,对方的外链地址是通过 post一个地址,成功验证rsa后会进行跳转,跳转后的那个地址是最终我们需要的,

即 httpstatus=302的时候,获取header中的location 得到他的redirect地址

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.10</version>
    </dependency>

    <dependency>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-jdk15on</artifactId>
      <version>1.60</version>
    </dependency>
package thinking.in.spring.boot;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.util.Base64Utils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {

    public static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCq2XklNNdeB0byEKeYIJr7GlMa\n" +
            "H4FGuEbmBno9t9ZR0O4Y4Ma6bX/dK6xPb3FQ4fg8yKe43Na16w/JHgA2Q+DjwxPI\n" +
            "REFMGlAou++o42cbRvR6+EqH4tNZ6hJQvYIv8hS1Ozf8g3P966wazeKbuZhXfdLe\n" +
            "ylVqBvnlroACAeBnGQIDAQAB";
    public static final String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKrZeSU0114HRvIQ\n" +
            "p5ggmvsaUxofgUa4RuYGej231lHQ7hjgxrptf90rrE9vcVDh+DzIp7jc1rXrD8ke\n" +
            "ADZD4OPDE8hEQUwaUCi776jjZxtG9Hr4Sofi01nqElC9gi/yFLU7N/yDc/3rrBrN\n" +
            "4pu5mFd90t7KVWoG+eWugAIB4GcZAgMBAAECgYB2SpzWZf+32tIESAPCENE9irx/\n" +
            "GdEoZe6w1UtN8Dsz6rTwBLGT4rzlJZfoaADNP6fgbg2ysTT4QAht95et+tF5v4ae\n" +
            "1UnrdQxASY2ifhWafUkDRwfrXc6mAqoBhmu+yfvJhpTtv2bKytaDI2Jll/R+R9fV\n" +
            "BVyBAxQjDNEaHeYgAQJBANlTEXqbWgJQx0CfBqf9nKod3oxScFInaSHPp4IYmvgv\n" +
            "kiaix5DJXU/JVewLJLEiQYMtcgNapQt+iIX+8RkRT8kCQQDJQRWXlyM0kazSnaeV\n" +
            "AKUkCj26+w6vwfHEjy9HEojB9aLi8bUDhWEkLuBbrBXvwt5lCaPbSAC9+vffRf3e\n" +
            "ViTRAkEAqUqYVxYla6BZVvGKUdqx66MQ9eZSMO0abIhCSIm6TpNgGlC7fQIfekOw\n" +
            "dwvHLWUt+22vXwWBhA6xcxBB5/EgYQJBAMd8ROvSuunDr9vAu7jdP9PedtvdOOyM\n" +
            "QJpGF2XKgFZJpeBwF63ayrQz5t3XUJMsxIbALHQSBfJKTuI4nXCCUNECQE92lgea\n" +
            "/ddIRTzAUG5fhEW2WjH4brLNeBXKFu69IKSuNVCu3edU0eBxcWQojCVx2yDzXoSs\n" +
            "07S/gKSEmuprwjc=";

    public static void main(String[] args) throws Exception {
        String json = "{\"Issuer_NAME\":\"MTDP\",\"EUID\":\"fccab33e-015e-11ea-95d9-000c292235b2\",\"Campaign_ID\":\"15814865334230070\"}";
        //String a = new String(encryptByPublicKey(json.getBytes(),publicKey));
        //String b = new String(decryptByPrivateKey(a.getBytes(),privateKey));

        System.out.println(json);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpClientContext context = HttpClientContext.create();
        HttpPost httpPost = new HttpPost("https://a.com/home");
        CloseableHttpResponse response = null;
        String location = null;
        try {
            Map<String,String> map = new HashMap<>();
            map.put("data", encrypt(json,"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvhnuoppOFs/L+VmgRNjopZcP3Kz+7fF0UCag8aCc6jPU2+JUgg5su3McI2IP40aQeU9Z+KxFTuYZ1J8Ib35T+s8sbn2gv3rG+xdwSxVh81lKZ0fulZKox6WtHaDPykpJgkNsB9d1izg83OX0R3mwnLrh3XvGlFUQKsmrh92LfM9Kr/bFVzyNviaT1qoIBImIzSlbe/2tRo3rt5jRBU386E6iJq9KPSzwGwZ3Y3ZgTPgxXStxPuBbtcFQIEhZV2usv0ws7As1Az2tdpAfcAvVKRxsi2Dc/44DFUhtXjsqa7HU/GQKalXW9HbZUa2mTZH0+Ur8OBAiH/NrK/4Ndxfz3wIDAQAB"));
            //map.put("data","WEsUKl/ZYYBv6BwIuevduVc1XIB5WiVyhIryK5oy/UScOJ7ThODDJjFHeccFBPJDCNV4KMirACvZVFkYAqGuz3k71cA1AF+ZBbap+wjMRnNNd1GuwyVa1+fONxEPg/kY0jYCIuFK9sUJW5liMGbq+rNY+1J3dFYmHkscm3XYbJRC2kj6NZdpMh2VcOFoI5kHJaa0rWYX5uhpre7vr085B1XOjl8lGzvqtASl+kJwmMbEbo2Yvy0KaXoOkgzHaNrEVJsQaIiFPWv9gpP3KVXNFQDkONNThyCE2BkvJOfBB1SpZAoNzk2p7+WTT/rfUn86vrpFysn3oyzqWUfcA438IQ==");
            List<BasicNameValuePair> pair =new ArrayList<BasicNameValuePair>();

            //我们遍历map 将数据转化为我们的表单数据
            for (Map.Entry<String,String> entry:
                    map.entrySet()) {
                pair.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
            }

            //httppost 中放入我们的经过url编码的表单参数

            httpPost.setEntity(new UrlEncodedFormEntity(pair));
            response = httpclient.execute(httpPost, context);
            int responseCode = response.getStatusLine().getStatusCode();
            if (responseCode == 302) {
                Header locationHeader = response.getFirstHeader("Location");
                location = locationHeader.getValue();
            }
        }catch(IOException e){
            e.printStackTrace();
        }catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(location);
    }

    public static String encrypt( String str, String publicKey ) throws Exception{
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA",new BouncyCastleProvider());
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] cipherText = cipher.doFinal(str.getBytes());
        String outStr = Base64.encodeBase64String(cipherText);
        System.out.println("cipher: " + outStr);

        return outStr;
    }

    public static String decrypt(String str, String privateKey) throws Exception{
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }


    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("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;
    }


    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("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;
    }



    /**
     * 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);
    }


}

 

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐