AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79431415
Accepted
Kris Rice
Kris Rice
Asked: 2025-02-12 05:52:42 +0800 CST2025-02-12 05:52:42 +0800 CST 2025-02-12 05:52:42 +0800 CST

javax.net.ssl.SSLHandshakeException:(certificate_unknown)在 Scala 客户端中通过 NGINX

  • 772

问题:

在过去一周左右的时间里,我一直在反复尝试配置我的 Scala+AKKA 客户端,以便能够向运行 NGINX 的服务器发送消息。

我不断收到错误: javax.net.ssl.SSLHandshakeException: (certificate_unknown)

设置:

nginx配置:

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
    server_name localhost;

    ssl_certificate /home/hydra/.localhost-ssl/localhost.crt;           //<- combined certificates (server_cert + rootCA)
    ssl_certificate_key /home/hydra/.localhost-ssl/localhost-key.key;

    ssl_trusted_certificate /home/hydra/.localhost-ssl/rootCA.crt;      //<- just the rootCA

    index index.html index.htm;
    root /home/hydra/ui/;

    location / {
        try_files $uri.html $uri/index.html
        @public
        @nextjs;
        add_header Cache-Control "public, max-age=3600";
    }

    location @public {
        add_header Cache-Control "public, max-age=3600";
    }

    location /ping {
        proxy_pass http://localhost:8080;
    }

    location @nextjs {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-Proto https;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-Host $remote_addr;
    }
}

客户要求:


  private val sslContext: SSLContext = SSLManager.getClientSSLContext
  private val connectionContext = ConnectionContext.httpsClient(sslContext)

...

    val request = HttpRequest(method = HttpMethods.GET, uri = s"https://${server.serverIP}/ping")
    http.singleRequest(request, connectionContext).pipeTo(self)

createClientContext:

  def getClientSSLContext: SSLContext = {
    val keyStore = KeyStore.getInstance("JKS")
    keyStore.load(null, null) // Create an empty keystore
    keyStore.setCertificateEntry("rootCA", loadRootCertificate())

    // Set up a TrustManager that trusts the root CA certificate
    val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
    trustManagerFactory.init(keyStore)
    val trustManagers = trustManagerFactory.getTrustManagers

    // Create an SSLContext with the custom TrustManager
    val sslContext = SSLContext.getInstance("TLS")
    sslContext.init(null, trustManagers, new SecureRandom())
    sslContext
  }

写入rootCA文件:

    val rootCA = new StringBuilder()
    rootCA.append("-----BEGIN CERTIFICATE-----\n")
    rootCA.append(Base64.getEncoder.encodeToString(rootCACertificate.getEncoded))
    rootCA.append("\n-----END CERTIFICATE-----")
    writeFile(ROOT_CA_PATH, Seq(rootCA.toString))

如何创建签名的服务器证书:

def createCSR(keyPair: KeyPair, subject: String, keyAlgorithm: String): PKCS10CertificationRequest = {
    val csrGen = new PKCS10CertificationRequestBuilder(new X500Name(subject), SubjectPublicKeyInfo.getInstance(keyPair.getPublic.getEncoded))
    val signer = new JcaContentSignerBuilder("SHA256with" + keyAlgorithm).build(keyPair.getPrivate)
    csrGen.build(signer)
  }

  // Sign the CSR with the root CA's private key to generate a certificate
  def signCertificate(csr: PKCS10CertificationRequest, rootCACertificate: X509Certificate, rootCAPrivateKey: PrivateKey): X509Certificate = {
    val notBefore = new Date()
    val notAfter = new Date(notBefore.getTime + 36500L * 24 * 60 * 60 * 1000) // Valid for 1 year

    val certGen = new X509v3CertificateBuilder(
      new X500Name("CN=Hydra SSL Certificate"),
      new BigInteger(128, new Random()),
      notBefore,
      notAfter,
      csr.getSubject,
      csr.getSubjectPublicKeyInfo
    )

    // Add SubjectAlternativeName (SAN) extension
    val sanNames = Array[GeneralName](
      new GeneralName(GeneralName.iPAddress, SERVER_IP)
    )

    val generalNames = new GeneralNames(sanNames)
    certGen.addExtension(Extension.subjectAlternativeName, false, generalNames)

    // Sign with root CA's private key
    val signer = new JcaContentSignerBuilder("SHA256withRSA").build(rootCAPrivateKey)
    val certificateHolder: X509CertificateHolder = certGen.build(signer)

    // Convert to a JCE certificate
    val converter = new JcaX509CertificateConverter().setProvider("BC")
    converter.getCertificate(certificateHolder)
  }

...

    // Step 1: Load Root CA certificate and private key
    val rootCACertificate = loadRootCertificate()
    val rootCAPrivateKey = loadRootPrivateKey()

    // Step 2: Generate new key pair for SSL certificate
    val keyPair = generateKey("RSA")

    // Step 3: Create CSR (Certificate Signing Request)
    val csr = createCSR(keyPair, s"CN=hydra_server_$SERVER_ID, O=Hydra, C=UK", "RSA")

    // Step 4: Sign the CSR with the Root CA to generate the SSL certificate
    val sslCertificate = signCertificate(csr, rootCACertificate, rootCAPrivateKey)

我尝试过的:

咨询后chatGPT,我尝试了该命令openssl s_client -connect 192.168.0.4:443 -showcerts

该命令的输出可以在这里找到。

这帮助我验证是否nginx确实按正确的顺序发送了整个链(可以通过日期确认 - rootCA(输出中的证书 1)是在 2025 年 7 月 2 日生成的,服务器证书(证书 0)是在今天生成的。

那么我的设置中哪里做错了/遗漏了什么?

scala
  • 1 1 个回答
  • 49 Views

1 个回答

  • Voted
  1. Best Answer
    dave_thompson_085
    2025-02-12T13:34:59+08:002025-02-12T13:34:59+08:00

    您的 CA 名称是C=UK, ST=London, L=London, O=Hydra, OU=Hydra, CN=Hydra,但服务器证书中的颁发者名称不同;而是CN=Hydra SSL Certificate。因此,证书验证器无法将服务器证书链接到 CA 证书,验证失败。

    X509v3CertificateBuilder 的第一个参数应该是来自父级(此处为根)证书的主题名称,从 base-Java X500Principal 类型转换为 BouncyCastle X500Name 类型,方式与您已经转换 SPKI 的方式相同;有关示例,请参阅(我的)https://security.stackexchange.com/questions/179526/how-to-import-plain-public-key-into-java-keystore

    此外,在 PEM 格式中,base64 主体应该分成 64 个字符的行(最后一个字符除外);请参阅 RFC 7468 第 2 节。nginx 使用 OpenSSL,旧版本的 OpenSSL 会因您编写的单行长行而完全失败。自 2012 年以来,OpenSSL 支持更长的 base64 行,但不是无限制的,因此根据您的数据,写入此格式有时会失败。其他软件各不相同,因此同一个文件可能同时有效和​​无效。避免这种情况的最简单方法是使用Base64.getMimeEncoder()根据 MIME 标准分成 76 个字符的行,这些标准在概念上与 PEM 相似;即使是最古老的 OpenSSL 也能处理 76 个字符,而且我从未遇到过其他不这样做的东西。

    • 4

相关问题

  • 为什么这个 ZIO 层组合无法编译?

  • 如何在 Scala 3 中将 Expr 转换为树?

  • 如何正确匹配 Scala 3 宏注释中的 TypeDef?

  • Spark Scala 将多列合并为单列

  • 可变参数的多类型方法参数

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve