«

PHP如何实现与Java兼容的PKCS7签名?

时间:2025-1-8 08:27     作者:emer     分类:


php 实现 pkcs7 签名

问题:

与第三方对接时,需要使用 java 实现 pkcs7 签名,在 php 中该如何实现此功能?

答案:

立即学习“”;

php 中可以通过 openssl_pkcs7_verify 函数进行 pkcs7 签名。

实现代码:

<?php

/**
 * 加签
 *
 * @param string $plaintext 明文
 * @param string $password 密钥密码
 * @param string $privateKeyFile 私钥文件
 * @param string $certificateFile 证书文件
 *
 * @return string
 */
function pkcs7_sign($plaintext, $password, $privateKeyFile, $certificateFile)
{
    $privateKey = openssl_pkey_get_private('file://' . $privateKeyFile, $password);
    $certificate = openssl_x509_read(file_get_contents('file://' . $certificateFile));
    $signature = openssl_pkcs7_sign($plaintext, 'file://sign.p7', $certificate, $privateKey, ['detach' => true]);

    // 将签名转为 Base64 编码
    return base64_encode($signature);
}
登录后复制

以上就是PHP如何实现与Java兼容的PKCS7签名?的详细内容,