如何在JAVA中使用PHP PKCS7加密解密

时间:2019-07-30 02:45:33

标签: java php pkcs#7

我正在将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;
    }
}

1 个答案:

答案 0 :(得分:0)

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