java生成私鑰、公鑰和密鑰

通過(guò)jmeter客戶(hù)端去訪(fǎng)問(wèn)服務(wù)端程序,需要用到私鑰、公鑰和密鑰,還有服務(wù)端公鑰
image.png

定義ApiEncryptUtil.java文件為OpenApi通信協(xié)議加解密工具類(lèi),以下代碼:

package com.niiwoo.sdk.test;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.commons.codec.binary.Base64;


/**
 * OpenApi通信協(xié)議加解密工具類(lèi)
 * 
 * 
 */
public class ApiEncryptUtil {

    private final static Random random = new Random();

    public static void main(String[] args) throws Exception {
        
        Map<String, Object> map = generateRSAKeyPairs();
        System.out.println("publicKey:===>"+map.get("publicKey"));
        System.out.println("privateKey:===>"+map.get("privateKey"));
        
        System.out.println(KeyCreate(24));
        
    }
    
    /**
     * 生成RSA公、私鑰對(duì)
     * 
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static Map<String, Object> generateRSAKeyPairs() throws NoSuchAlgorithmException {
        Map<String, Object> keyPairMap = new HashMap<String, Object>();
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        KeyPair keyPair = generator.genKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        keyPairMap.put("publicKey", Base64.encodeBase64String(publicKey.getEncoded()));
        keyPairMap.put("privateKey", Base64.encodeBase64String(privateKey.getEncoded()));
        return keyPairMap;
    }

    public static byte[] signByPrivateKey(byte[] data, PrivateKey privateKey)
            throws Exception {
        Signature sig = Signature.getInstance("SHA256withRSA");
        sig.initSign(privateKey);
        sig.update(data);
        byte[] ret = sig.sign();
        return ret;
    }
    public static PrivateKey getPrivateKeyFromString(String base64String)
            throws InvalidKeySpecException, NoSuchAlgorithmException {
        byte[] bt = Base64.decodeBase64(base64String.getBytes());
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bt);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
        return privateKey;
    }
    


    /**
     * 生成16位AES隨機(jī)密鑰
     * @return
     */
    public static String getAESRandomKey(){
        long longValue = random.nextLong();
        return String.format("%016x", longValue);
    }
    

    public static String KeyCreate(int KeyLength) {
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*:_+<>?~#$@";
        Random random = new Random();
        StringBuffer Keysb = new StringBuffer();
        // 生成指定位數(shù)的隨機(jī)秘鑰字符串
        for (int i = 0; i < KeyLength; i++) {
            int number = random.nextInt(base.length());
            Keysb.append(base.charAt(number));
        }
        return Keysb.toString();
    }
    
    

}

Eclipse客戶(hù)端執(zhí)行代碼生成私鑰、公鑰和密鑰
image.png

服務(wù)端公鑰是在配置文件已經(jīng)配置好了
image.png

使用生成的私鑰、公鑰和密鑰替換在jmeter上的配置,修改驗(yàn)簽TianChengSampler.java文件

/**
 *TianCheng Sampler ,for tiancheng uap2.0
 */

package org.apache.niiwoo;

//import java.io.ByteArrayOutputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.PrintStream;
//import java.io.UnsupportedEncodingException;
//import java.net.MalformedURLException;
//import java.net.URISyntaxException;
//import java.net.URL;
//import java.security.MessageDigest;
//import java.security.NoSuchAlgorithmException;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.Collections;
import java.util.HashMap;
//import java.util.HashSet;
//import java.util.Iterator;
//import java.util.List;
import java.util.Map;
//import java.util.Set;
//import java.util.concurrent.Callable;
//import java.util.concurrent.ExecutionException;
//import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.Date;
import java.util.UUID;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.apache.jmeter.config.Argument;
//import org.apache.jmeter.config.Arguments;
//import org.apache.jmeter.config.ConfigTestElement;
//import org.apache.jmeter.engine.event.LoopIterationEvent;
//import org.apache.jmeter.protocol.http.control.AuthManager;
//import org.apache.jmeter.protocol.http.control.CacheManager;
//import org.apache.jmeter.protocol.http.control.Cookie;
//import org.apache.jmeter.protocol.http.control.CookieManager;
//import org.apache.jmeter.protocol.http.control.DNSCacheManager;
//import org.apache.jmeter.protocol.http.control.HeaderManager;
//import org.apache.jmeter.protocol.http.parser.BaseParser;
//import org.apache.jmeter.protocol.http.parser.LinkExtractorParseException;
//import org.apache.jmeter.protocol.http.parser.LinkExtractorParser;
//import org.apache.jmeter.protocol.http.sampler.ResourcesDownloader.AsynSamplerResultHolder;
//import org.apache.jmeter.protocol.http.util.ConversionUtils;
//import org.apache.jmeter.protocol.http.util.EncoderCache;
//import org.apache.jmeter.protocol.http.util.HTTPArgument;
//import org.apache.jmeter.protocol.http.util.HTTPConstants;
//import org.apache.jmeter.protocol.http.util.HTTPConstantsInterface;
//import org.apache.jmeter.protocol.http.util.HTTPFileArg;
//import org.apache.jmeter.protocol.http.util.HTTPFileArgs;
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.SampleResult;
//import org.apache.jmeter.testelement.TestElement;
//import org.apache.jmeter.testelement.TestIterationListener;
//import org.apache.jmeter.testelement.TestStateListener;
//import org.apache.jmeter.testelement.ThreadListener;
//import org.apache.jmeter.testelement.property.BooleanProperty;
//import org.apache.jmeter.testelement.property.CollectionProperty;
//import org.apache.jmeter.testelement.property.IntegerProperty;
//import org.apache.jmeter.testelement.property.JMeterProperty;
//import org.apache.jmeter.testelement.property.PropertyIterator;
//import org.apache.jmeter.testelement.property.StringProperty;
//import org.apache.jmeter.testelement.property.TestElementProperty;
//import org.apache.jmeter.threads.JMeterContext;
//import org.apache.jmeter.threads.JMeterContextService;
//import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
//import org.apache.jorphan.util.JOrphanUtils;
import org.apache.log.Logger;
//import org.apache.oro.text.MalformedCachePatternException;
//import org.apache.oro.text.regex.Pattern;
//import org.apache.oro.text.regex.Perl5Matcher;
import org.apache.niiwoo.commons.Base64;
import org.apache.niiwoo.commons.ThreeDes;
import org.apache.niiwoo.commons.EncryptUtil;
import org.apache.niiwoo.commons.RSA;
import org.apache.niiwoo.commons.HttpRequestUtil;
import com.alibaba.fastjson.JSONObject;



/**
*TianCheng Sampler class
 */
public class TianChengSampler extends AbstractSampler {

    private static final long serialVersionUID = 240L;

    private static final Logger log = LoggingManager.getLoggerForClass();

    // The name of the property used to hold our data
    public static final String DATA = "TianChengSampler.data"; //$NON-NLS-1$
    public static final String serverURL = "TianChengSampler.serverURL"; //$NON-NLS-1$
    public static final String orgCode = "TianChengSampler.orgCode"; //$NON-NLS-1$
    public static final String userName = "TianChengSampler.userName"; //$NON-NLS-1$
    public static final String userPassword = "TianChengSampler.userPassword"; //$NON-NLS-1$
    public static final String functionCode = "TianChengSampler.functionCode"; //$NON-NLS-1$
    public static final String clientPrivateKey = "TianChengSampler.clientPrivateKey"; //$NON-NLS-1$
    public static final String clientPublicKey = "TianChengSampler.clientPublicKey"; //$NON-NLS-1$
    public static final String serverPublicKey = "TianChengSampler.serverPublicKey"; //$NON-NLS-1$
    public static final String threeDesKey = "TianChengSampler.threeDesKey"; //$NON-NLS-1$

    private static AtomicInteger classCount = new AtomicInteger(0); // keep track of classes created

    // (for instructional purposes only!)

    public TianChengSampler() {
        classCount.incrementAndGet();
                        
        trace("TianChengSampler()");
    }
    
    /**
     * 發(fā)送HTTP請(qǐng)求
     * 
     * @throws Exception
     */
    public String postHttpRequest() throws Exception
    {
        String data = getData(); // Sampler data
        String server_url = getServerURL();
        String org_code   = getOrgCode(); 
        String username = getUserName(); 
        String password = getUserPassword(); 
        String function_code = getFunctionCode(); 
        String client_private_key = getClientPrivateKey(); 
        //String client_public_key = getClientPublicKey(); 
        String server_public_key = getServerPublicKey();
        String three_des_key = getThreeDesKey(); 
        UUID uuid = UUID.randomUUID();
        String transNo = uuid.toString();
        
        
        Map<String, Object> root = new HashMap<String, Object>();
        Map<String, Object> header = new HashMap<String, Object>();
        Map<String, Object> securityInfo = new HashMap<String, Object>();
        
        header.put("orgCode", org_code.toString());
        header.put("transNo", transNo);
        header.put("transDate", new Date().toString());
        header.put("userName", username.toString());
        header.put("userPassword", EncryptUtil.md5(password.toString()));
        header.put("functionCode", function_code.toString());
        String headerStr = JSONObject.toJSONString(header);
        
        //使用pcks8編碼格式的私鑰
        String sigValue = RSA.sign(headerStr, client_private_key);
        securityInfo.put("signatureValue", sigValue);
        
        byte[] encBusiData = ThreeDes.encryptMode(three_des_key.getBytes(), data.getBytes("UTF-8"));
        
        root.put("header", headerStr);
        root.put("busiData", Base64.getBase64ByByteArray(encBusiData));
        root.put("securityInfo", securityInfo);
        String message = JSONObject.toJSONString(root);
        
        log.debug("向BOSS發(fā)送請(qǐng)求:" + message);

        String res = HttpRequestUtil.sendJsonWithHttp(server_url, message);

        //System.out.println("響應(yīng)Message:" + res);
        JSONObject msgJSON = JSONObject.parseObject(res);
        String head = msgJSON.getString("header");
        if(!JSONObject.parseObject(head).getString("rtCode").equals("E0000000"))
        {
            log.debug("消息返回失敗");
            String retMessage = "返回失敗,錯(cuò)誤碼rtCode:";
            switch(JSONObject.parseObject(head).getString("rtCode")) {
                case "E0000001":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 請(qǐng)求消息為空!";
                    break;
                case "E0000002":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 驗(yàn)簽失敗!";
                    break;
                case "E0000003":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 請(qǐng)求數(shù)據(jù)解析失敗!";
                    break;
                case "E0000004":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 請(qǐng)求的用戶(hù)不存在!";
                    break;
                case "E0000005":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 用戶(hù)名密碼錯(cuò)誤!";
                    break;
                case "E0000006":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 交易流水重復(fù)!";
                    break;
                case "E0000007":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", base64解碼失敗!";
                    break;
                case "E0000008":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 3des解碼失敗!";
                    break;
                case "E0000009":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 錯(cuò)誤的請(qǐng)求方式!";
                    break;
                case "E0000010":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 用戶(hù)余額不足!";
                    break;
                case "E0000011":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 內(nèi)部響應(yīng)超時(shí)!";
                    break;
                case "E0000012":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 功能號(hào)格式錯(cuò)誤!";
                    break;
                case "E0000013":
                    retMessage += JSONObject.parseObject(head).getString("rtCode") + ", 系統(tǒng)正在升級(jí)中,請(qǐng)稍后再試!";
                    break;
                default : retMessage += ", 未定義的錯(cuò)誤碼!";
            }
            return retMessage;
        }
        //驗(yàn)證簽名
        String securityInfo1 = msgJSON.getString("securityInfo");
        String signatureValue = JSONObject.parseObject(securityInfo1).getString("signatureValue");
        boolean verifyFlag = RSA.verify(msgJSON.getString("header"), signatureValue, server_public_key);
        if(verifyFlag == true){
            log.debug("驗(yàn)簽成功");
            byte[] b64 = Base64.getFormBase64ByString(msgJSON.getString("busiData"));
            byte[] busiData = ThreeDes.decryptMode(three_des_key.getBytes(), b64);
            String rspData = new String(busiData, 0, busiData.length, "UTF-8"); 
            log.debug("響應(yīng)BusiData明文:" + rspData);
            return rspData;
        }else{
            log.debug("驗(yàn)簽失敗");
            return "響應(yīng)數(shù)據(jù)驗(yàn)簽失敗!";
        }
        
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SampleResult sample(Entry e) {
        log.debug("into SampleResult.sample");
        trace("sample()");
        SampleResult res = new SampleResult();
        boolean isOK = false; // Did sample succeed?
        String data = getData(); // Sampler data

        String response = null;

        res.setSampleLabel(getTitle());
        /*
         * Perform the sampling
         */
        res.sampleStart(); // Start timing
        try {

            // Do something here ...

            response = postHttpRequest(); //Thread.currentThread().getName();
            /*
             * Set up the sample result details
             */
            res.setSamplerData(data);
            res.setResponseData(response, null);
            res.setDataType(SampleResult.TEXT);

            res.setResponseCodeOK();
            res.setResponseMessage("OK");// $NON-NLS-1$
            isOK = true;
        } catch (Exception ex) {
            log.debug("", ex);
            res.setResponseCode("500");// $NON-NLS-1$
            res.setResponseMessage(ex.toString());
        }
        res.sampleEnd(); // End timimg

        res.setSuccessful(isOK);

        return res;
    }

    /**
     * @return a string for the sampleResult Title
     */
    private String getTitle() {
        log.debug("into getTitle");
        return this.getName();
    }

    /**
     * @return the data for the sample
     */
    public String getData() {
        return getPropertyAsString(DATA);
    }
    
    /**
     * @return the serverURL for the sample
     */
    public String getServerURL() {
        return getPropertyAsString(serverURL);
    }
    
    /**
     * @return the orgCode for the sample
     */
    public String getOrgCode() {
        return getPropertyAsString(orgCode);
    }
    
    public String getUserName() {
        return getPropertyAsString(userName);
    }
    
    public String getUserPassword() {
        return getPropertyAsString(userPassword);
    }
    
    public String getFunctionCode() {
        return getPropertyAsString(functionCode);
    }
    
    public String getClientPrivateKey() {
        return getPropertyAsString(clientPrivateKey);
    }
    
    public String getClientPublicKey() {
        return getPropertyAsString(clientPublicKey);
    }
    
    public String getServerPublicKey() {
        return getPropertyAsString(serverPublicKey);
    }
    
    public String getThreeDesKey() {
        return getPropertyAsString(threeDesKey);
    }
    

    /*
     * Helper method
     */
    private void trace(String s) {
        String tl = getTitle();
        String tn = Thread.currentThread().getName();
        String th = this.toString();
        log.debug(tn + " (" + classCount.get() + ") " + tl + " " + s + " " + th);
    }
}

修改前
image.png

修改后
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,578評(píng)論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,701評(píng)論 3 429
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 178,691評(píng)論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 63,974評(píng)論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,694評(píng)論 6 413
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 56,026評(píng)論 1 329
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,015評(píng)論 3 450
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 43,193評(píng)論 0 290
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,719評(píng)論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 360
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,668評(píng)論 1 374
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,151評(píng)論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,846評(píng)論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 35,255評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 36,592評(píng)論 1 295
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,394評(píng)論 3 400
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,635評(píng)論 2 380

推薦閱讀更多精彩內(nèi)容