通過Python調(diào)用java中的Jar文件

一些特殊場景需要使用Python調(diào)用java,一下是對這個過程的簡單的封裝。

1.準備java的jar文件

其中的內(nèi)容如下:

package cn.diaoyc.aes;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author Tony     
 * @projectName  AESCB
 * @title  AecCBCUtil   
 * @package  cn.diaoyc.aes   
 * @date 2020/5/10 -- 10:06
 * @version v1.1
 *  
 */
public class AecCBCUtil {
    // 加密方式
    private static String ALGORITHM = "AES";
    //算法數(shù)據(jù)填充方式
    private static String ALGORITHM_FILL_TYPE = "AES/CBC/PKCS5Padding";
    //字符編碼(String轉(zhuǎn)byte[] 使用UTF-8的編碼格式)
    private static String ENCODING_FORMAT = "UTF-8";

    // 內(nèi)部實例參數(shù)
    private static AecCBCUtil instance = null;

    private AecCBCUtil() {

    }

    //采用單例模式,此靜態(tài)方法供外部直接訪問
    public static AecCBCUtil getInstance() {
        if (instance == null) {
            instance = new AecCBCUtil();
        }
        return instance;
    }

    /**
     * 加密
     * @param originalContent 明文
     * @param encryptKey 密鑰
     * @param ivParameter 初始偏移量
     * @return 返回加密后的字符串
     */
    public String encrypt(String originalContent, String encryptKey, String ivParameter) {
        try {
            //處理傳進來的明文
            byte[] originalContentBytes = originalContent.getBytes(ENCODING_FORMAT);

            //處理傳進來的密鑰(String轉(zhuǎn)成byte[])
            byte[] enKeyBytes = encryptKey.getBytes();

            //處理傳進來的偏移量(String轉(zhuǎn)成byte[])
            byte[] ivParameterBytes = ivParameter.getBytes();

            //根據(jù)傳入的密鑰按照AEC方式構(gòu)造密鑰
            SecretKeySpec sKeySpec = new SecretKeySpec(enKeyBytes, ALGORITHM);

            //根據(jù)傳入的偏移量指定一個初始化偏移量
            IvParameterSpec iv = new IvParameterSpec(ivParameterBytes);
            //根據(jù)數(shù)據(jù)填充方式生成一個加解密對象
            Cipher cipher = Cipher.getInstance(ALGORITHM_FILL_TYPE);

            //初始化 傳入類型(加密/解密)、構(gòu)造過的密鑰、指定的初始偏移量
            cipher.init(Cipher.ENCRYPT_MODE, sKeySpec, iv);

            //加密操作
            byte[] encrypted = cipher.doFinal(originalContentBytes);

            //base64轉(zhuǎn)碼
            String cipherString = new BASE64Encoder().encode(encrypted);
            return cipherString;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 解密
     * @param cipherStr 加密過的密文
     * @param encryptKey 密鑰
     * @param ivParameter 偏移量
     * @return 返回解密過后的字符串
     */
    public String decrypt(String cipherStr, String encryptKey, String ivParameter) {
        try {
            //處理傳進來的密文 使用base64解密
            byte[] cipherStrByte = new BASE64Decoder().decodeBuffer(cipherStr);

            //處理傳進來的密鑰(String轉(zhuǎn)成byte[])   可以指定編碼格式為:ASCII
            byte[] enKeyBytes = encryptKey.getBytes();

            //處理傳進來的偏移量(String轉(zhuǎn)成byte[])
            byte[] ivParameterBytes = ivParameter.getBytes();

            //根據(jù)傳入的密鑰按照AEC方式構(gòu)造密鑰
            SecretKeySpec sKeySpec = new SecretKeySpec(enKeyBytes, ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM_FILL_TYPE);
            IvParameterSpec iv = new IvParameterSpec(ivParameterBytes);
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, iv);

            //獲得解密的明文數(shù)組
            byte[] original = cipher.doFinal(cipherStrByte);
            return new String(original, ENCODING_FORMAT);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}

2.首先需要使用pip命令安裝jpype

pip install jpype

3.新建Python文件導(dǎo)入jpype,代碼如下

import jpype
import os
from jpype import *


class PyCallJava(object):
    def __init__(self, jPath, jClassName):
        self.jPath = jPath  # jar 路徑
        self.jClassName = jClassName  # java類的全路徑

    # 加載類
    def toCallJava(self):
        # 第二個參數(shù)是jar包的路徑
        jarpath = os.path.join(os.path.abspath('.'), self.jPath)
        # 啟動jvm
        jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jarpath)
        # 類名
        jd_class = JClass(self.jClassName)
        return jd_class

    def closeJvm(self):
        # 關(guān)閉jvm
        jpype.shutdownJVM()

    # 使用類中的方法
    def test(self, param):
        jd_class = self.toCallJava()
        # 調(diào)用類中的方法
        # enString = jd_class.getInstance().encrypt(originalContent, encryptKey, ivParameter)
        enString = jd_class.getInstance().encrypt(param["originalContent"], param["encryptKey"], param["ivParameter"])
        print(enString)
        # 調(diào)用關(guān)閉方法
        self.closeJvm()


if __name__ == '__main__':

    # 參數(shù)
    param = {"gdfgfa": "{\"fadsfads\":{\"fasdfds\":\"fasdfdsfa\",\"adsfdsa\":{\"adsf\":\"\",\"fadsfd\":\"\",\"fasdfd\":\"\",\"OSType\":\"\"},\"Name\":\"fadf\",\"afdf\":1,\"fadsfdsfdsa\":\"fasdfdsfa\"},\"P\":\"adminfafdsfadsmanager-123456\",\"U\":\"f-masdfdsfnager\"}", "fasdfds": "NV20fEAD55uEtWx5", "ivParameter": "IpaQo57JVO0GkU7s"}
    # jar路徑
    Path = r'C:\Users\Tony\IdeaProjects\AESCB\target\AESCB-1.0-SNAPSHOT.jar'
    # 類的名稱
    classname = "cn.diaoyc.aes.AecCBCUtil"

    PyCallJava(Path, classname,).test(param)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容