簡體   English   中英

如何找到給定私鑰的首選簽名算法

[英]How to find preferred signature algorithm for given private key

我正在使用 BouncyCastle 頒發 X509 證書。 我在這里找到了許多代碼示例,其中簽名算法名稱是固定的,例如“ SHA256WithRSAEncryption ”:

ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
        .setProvider(BC).build(privKey);

BouncyCastle 或 JDK 中是否有一種方法可以找到給定PrivateKey的首選簽名算法名稱? 類似getPreferredSignatureAlgorithm()的東西在這里:

// is there method like this?
String signatureAlgorithm = getPreferredSignatureAlgorithm(issuerPrivKey);

JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(...);
ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm)
        .build(issuerPrivKey);
X509Certificate certificate = new JcaX509CertificateConverter()
        .setProvider(new BouncyCastleProvider())
        .getCertificate(builder.build(signer));

回答我自己的問題,我最終只是像這樣實現了我自己的方法

private static String signatureAlgorithm(PublicKey pub) {
    switch (pub.getAlgorithm()) {
        case "EC":
            EllipticCurve curve = ((ECPublicKey) pub).getParams().getCurve();
            switch (curve.getField().getFieldSize()) {
                case 224:
                case 256:
                    return "SHA256withECDSA";
                case 384:
                    return "SHA384withECDSA";
                case 521:
                    return "SHA512withECDSA";
                default:
                    throw new IllegalArgumentException("unknown elliptic curve: " + curve);
            }
        case "RSA":
            return "SHA256WithRSAEncryption";
        default:
            throw new UnsupportedOperationException("unsupported private key algorithm: " + pub.getAlgorithm());
    }
}

推薦的 EC 曲線消息摘要算法在RFC5480第 9 頁的表格中給出( 勘誤表)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM