jmeter beanshell rsa公钥加密&base64加密脚本

Life is short , play more!
本文来自lihao's Blog,转载请注明。

jmeter beanshell rsa公钥加密&base64加密脚本。

使用方法请参加jmeter jsr223 sampler或者preprocessor , postprocessor。

 

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


import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;


String inputStr = "[email protected]";  

String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCNzq4tk/SM42/M5ZroVoNGgPzQ/4GudYrcF1OXRdIK3dcj1xISlo4bnf8Hp+hTK8JjxRtakJwW+MCS2kq1MKKn1nRFtClUQq9ljrGlggy0d8Bu0DVzmuwoqszCXqmkHdETo1Iie5dR1k46CSmhsRdN55Wc/CnjV4whrHuV58JdQwIDAQAB";


String KEY_ALGORITHM = "RSA";


   public static byte[] encryptByPublicKey(byte[] data, String key)
            throws Exception {
        // 对公钥解密
        byte[] keyBytes = Base64.decodeBase64(key);

        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);

        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        return cipher.doFinal(data);
    }


        public static byte[] decryptByPrivateKey(byte[] data, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes =  Base64.decodeBase64(key);

        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        return cipher.doFinal(data);
    }


/**
 * 随机获取公私秘钥
 * 
 * */



log.info("==================");

//log.info(Base64.decodeBase64("test").toString());


        log.info("公钥加密——私钥解密");


        // 第一步base64 加密输入串
       
        byte[] data = Base64.encodeBase64String(inputStr.getBytes("UTF-8")).getBytes("UTF-8");   //inputStr.getBytes("UTF-8");
        
       //第二步 公钥加密
        byte[] encodedData = encryptByPublicKey(data, publicKey);

       // 第三步 对加密后的数据再进行base64  得到最后结果
        String ss =Base64.encodeBase64String(encodedData);


        log.info("加密前: " + inputStr + "\n\r" + "加密后: " + ss);

 


发表评论

电子邮件地址不会被公开。 必填项已用*标注