首页 > 解决方案 > 如何在 JAVA 中使用 PHP PKCS7 加密解密

问题描述

我将 JAVA 用于 2c2p ( https://developer.2c2p.com/docs/status-inquiry ) API,但他们使用的是 PHP,我不知道如何在 JAVA 中实现 PHP 的 openssl_pkcs7_encrypt 方法

我搜索了node.js的实现(PKCS7 encrypt decrypt in Node.js),但找不到Java实现

这是2c2p提供的PHP代码示例

function encrypt($text,$publickey)
{
    //write text to file
    if(!file_exists( dirname(__FILE__)."/tmp/"))
    {
        mkdir( dirname(__FILE__)."/tmp/");
    }
    $filename = dirname(__FILE__)."/tmp/".time().".txt";
    $this->text_to_file($text,$filename);
    $filename_enc = dirname(__FILE__)."/tmp/".time().".enc";

    $key = file_get_contents($publickey);
    if (openssl_pkcs7_encrypt($filename, $filename_enc, $key,
    array())) {
        // message encrypted - send it!
        unlink($filename);
        if (!$handle = fopen($filename_enc, 'r')) {
                 echo "Cannot open file ($filename_enc)";
                 exit;
            }

            $contents = fread($handle, filesize($filename_enc));
            fclose($handle);
            $contents = str_replace("MIME-Version: 1.0
            Content-Disposition: attachment; filename=\"smime.p7m\"
            Content-Type: application/pkcs7-mime; smime-type=enveloped-                             data; name=\"smime.p7m\"
            Content-Transfer-Encoding: base64
            ","",$contents);
            $contents = str_replace("\n","",$contents);
            unlink($filename_enc);
            return $contents;
    }
}

标签: javaphppkcs#7

解决方案


您好,您可以从此链接下载使用 pkcs7 加密和解密的 2c2p 状态查询的完整代码 https://support.2c2p.com/attachments/token/OaGZTrZWkqVMlHlhhpo3pBT2Y/?name=JAVA.rar


推荐阅读