从使用 Nimbus 创建的 Java PublicKey 创建 PEM 证书

Create PEM certificate from Java PublicKey created with Nimbus

我有一个集成,我在其中验证由另一个服务创建的 JSON。他们提供了一个 public 端点来获取 public 证书以进行验证。

但我正在为此设置一个测试,并希望使用 Nimbus 创建相同的 JWT 以使用我自己的私钥对其进行签名。所以我这样做(这是一个嵌套和加密的 JWT): https://connect2id.com/products/nimbus-jose-jwt/examples/signed-and-encrypted-jwt

然后我想在测试中用 MockServer (https://www.mock-server.com/) 端点模拟 public 端点。问题是我尝试从示例中的 senderJWK 的 public 密钥创建 PEM 证书,如下所示:

var encoded = senderJWK.toPublicKey().getEncoded();
var base64Encoded = Base64.getEncoder().encode(encoded);
return new String(base64Encoded, StandardCharsets.UTF_8);

(我也测试过senderJWK.toRSAPublicKey().getEncoded()。)

用于真实证书的代码无法解析它。解析它的代码如下所示:

private static RSAPublicKey readPublicKey(String publicKey) throws CertificateException {
    var bytes = Base64.getDecoder().decode(publicKey);
    var inStream = new ByteArrayInputStream(bytes);
    var certificateFactory = CertificateFactory.getInstance(X_509_CERTIFICATE_FACTORY);
    var certificate = (X509Certificate) certificateFactory.generateCertificate(inStream);
    return (RSAPublicKey) certificate.getPublicKey();
}

我得到的错误是:

    java.io.IOException: Too short
        at java.base/sun.security.util.DerValue.<init>(DerValue.java:333)
        at java.base/sun.security.util.DerInputStream.getDerValue(DerInputStream.java:109)
        at java.base/sun.security.x509.X509CertImpl.parse(X509CertImpl.java:1771)
        at java.base/sun.security.x509.X509CertImpl.<init>(X509CertImpl.java:183)
        ... 100 common frames omitted
    Wrapped by: java.security.cert.CertificateException: Unable to initialize, java.io.IOException: Too short
        at java.base/sun.security.x509.X509CertImpl.<init>(X509CertImpl.java:186)
        at java.base/sun.security.provider.X509Factory.engineGenerateCertificate(X509Factory.java:105)
        at java.base/java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:355)
        ... 95 common frames omitted

好的,我想我需要做的是从 java 创建一个 X509 证书,然后在签名和验证中使用私钥和 public 密钥。

找到有关如何使用充气城堡执行此操作的这些资源: Self signed X509 Certificate with Bouncy Castle in Java How to create a X509 certificate using Java?

编辑:我让它工作得很好。