如何使用sha256代替sha1作为签名算法? phpseclib

问题描述 投票:0回答:2

在示例页面上:http://phpseclib.sourceforge.net/x509/guide.html有一个示例“示例:CA签名的证书”我一直在使用它,但无论我做什么,我只得到sha1 签名。我尝试过

setHash('sha256')
,但没有运气。这个示例代码如何生成sha256签名?

谢谢!

sha1 sha256 phpseclib sethash
2个回答
0
投票
$x509->sign($issuer, $subject, 'sha256WithRSAEncryption');

$issuer
私钥需要是 RSA 的实例才能工作,但这就是你要做的。

它可能会忽略

setHash('sha256')
的事情,因为 (1) 并非所有可以与 RSA 一起使用的哈希都具有 X509.php 知道的 OID,并且 (2) RSA 中可用的选项 - 如 PSS 签名 - 不受支持X509.php 可能没有任何 IETF RFC 定义的 OID,并且可能不受其他 X509 实现的支持。


0
投票

我最近开始使用 phpsecllib 版本 3 来处理 x509 证书,并发现了许多阻碍,经过多天的血汗之后,这是我的最终成果。我希望它能帮助别人。

我很有趣,你已经有了 RSA 公钥/私钥对。 设置

withPadding(RSA::SIGNATURE_PKCS1)
很重要,因为这将设置为使用sha256算法。

/**
 * @param string $privateKey
 * @param string $publicKey
 * @param string|null $password
 * @return bool|string
 */
final public function generateX509Cert(string $privateKey, string $publicKey, string $password = null): bool|string
{
    $subjectDN = [
        'C' => 'FI',
        'ST' => 'Jyvaskyla',
        'L' => 'Jyvaskyla',
        'O' => 'Landis Gyr',
        'OU' => 'HES',
        'CN' => 'FOM Total Mobile Test Cert',
    ];
    // create the DN for the subject
    $subject = new X509();
    $subject->setDN($subjectDN);
    $publicKeyObj = PublicKeyLoader::loadPublicKey($publicKey);
    $publicKeyObj = $publicKeyObj->withPadding(RSA::SIGNATURE_PKCS1);
    $subject->setPublicKey($publicKeyObj);
    // Set subject key identifier. This is used by the id-ce-subjectKeyIdentifier extension
    $subject->setKeyIdentifier(Utils::uuid());

    $issuerDN = [
        'C' => 'IE',
        'ST' => 'Dublin',
        'L' => 'Dublin',
        'O' => 'Totalmobile',
        'OU' => 'Utilise',
        'CN' => 'FOM Total Mobile Test Cert',
    ];
    // create the DN for the issuer (the DN can be loaded from another X.509 cert too)
    $issuer = new X509();
    $issuer->setDN($issuerDN);
    $privateKeyObj = PublicKeyLoader::loadPrivateKey($privateKey, $password);
    $privateKeyObj = $privateKeyObj->withPadding(RSA::SIGNATURE_PKCS1);
    $issuer->setPrivateKey($privateKeyObj);

    // Create an X509 object and a new certificate
    $x509 = new X509();
    // $x509->makeCA();
    // Default expiry is 1 year
    // $x509->setStartDate('-1 month');
    // $x509->setEndDate('+100 year');

    $x509->setKeyIdentifier(Utils::uuid());

    // This is required in order to set multiple extensions
    $x509->loadX509($x509->sign($issuer, $subject));

    $x509->setExtension('id-ce-keyUsage', ['digitalSignature', 'nonRepudiation', 'keyEncipherment']);
    $x509->setExtension('id-ce-extKeyUsage', ['id-kp-serverAuth', 'id-kp-clientAuth']);
    // $x509->setExtension('id-ce-basicConstraints', ['cA' => true], true);

     $cert = $x509->sign($issuer, $x509);

    // Output the certificate in PEM format
    return $x509->saveX509($cert);
}
© www.soinside.com 2019 - 2024. All rights reserved.