酏剂/ Erlang:证书链验证

yvgpqqbh  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(174)

我有一个使用案例,其中证书链必须针对PKI进行验证。我有两个证书,一个是设备证书,另一个是certificate_chain。两个证书都是pem格式。:public_key.pkix_path_validation/3看起来很有前途,但我不知道如何以der格式给予证书链。我正在使用www.example.com _der将设备证书转换为derX509.Certificate.to,但我如何将证书链转换为der,因为它有3个证书(根CA,中间CA,签名CA),当我使用X509库转换它,并将其提供给:public_key.pkix_path_validation/3 .基本上,我想实现替代“openssl验证-CAfile证书/root_ca.pem -不受信任的证书链.pem证书/device_cert.pem”在酏剂.
我取得了一些进展,编写了一个方法来读取证书并传递它以进行验证。

defmodule Cert do
  def stubChainValidation do
    certRaw = File.read!("software_signing.pem")
    {:ok, certEncoded} = X509.Certificate.from_pem(certRaw)
    certChainRaw = File.read!("chain.pem")
    certChain = :public_key.pem_decode(certChainRaw)

    cert_chain_decoded =
      Enum.map(
        cert_chain,
        fn {_, bin, _} -> bin end
      )

    :public_key.pkix_path_validation(certEncoded, 
cert_chain_decoded, [{:max_path_length, 0}])
  end
end

运行此函数时,输出为Invalid issuer

{:error, {:bad_cert, :invalid_issuer}}
o75abkj4

o75abkj41#

在花了将近一个完整的星期后,我发现我做错了什么,Erlang以不同的方式期望参数,你需要传递根,然后传递包含中间证书和签名证书的链。
我附上了一个Erlang社区的示例实现,以防将来有人在验证时遇到麻烦。

defmodule Cert do
  def verify_fun(_, {:extension, _}, state) do
    {:unknown, state}
  end

  def verify_fun(_, {:bad_cert, reason}, _state) do
    {:fail, reason}
  end

  def verify_fun(_, {:revoked, _}, _state) do
    {:fail, :revoked}
  end

  def verify_fun(_cert, _event, state) do
    {:unknown, state}
  end

  def stubChainValidation do
    Application.ensure_all_started(:inets)
    Application.ensure_all_started(:ssl)
    Application.ensure_all_started(:public_key)
    certRaw = File.read!("./certs/root_ca.pem")
    {:ok, certEncoded} = X509.Certificate.from_pem(certRaw)

    certChainRaw = File.read!("./certs/chain_2.pem")
    certChain = :public_key.pem_decode(certChainRaw)

    cert_chain_decoded =
      Enum.map(
        certChain,
        fn {_, bin, _} -> bin end
      )

case :public_key.pkix_path_validation(certEncoded, cert_chain_decoded, [
       {:verify_fun, {&verify_fun/3, {}}}
     ]) do
  {:ok, {_public_key_info, _policy_tree}} ->
    {:ok, cert_chain_decoded}

  {:error, {:bad_cert, reason}} ->
    {:error, reason}
    end
  end
end

相关问题