调用需客户端证书的REST API:Ruby实现报错求解决方案
Ruby客户端证书认证请求解决方案
问题原因
报错incorrect pkey type: id-ecPublicKey是因为你的客户端密钥是**椭圆曲线(EC)**类型,但代码中错误使用OpenSSL::PKey::RSA.new加载——该方法仅支持RSA密钥,无法识别EC密钥格式。
修复方案:RestClient正确实现
使用OpenSSL::PKey.read方法自动识别密钥类型(兼容RSA/EC),同时补充URL缺失的https://前缀:
require 'openssl' require 'rest-client' keypass = '' # 自动识别密钥类型,兼容EC/RSA格式 client_key = OpenSSL::PKey.read(File.read('/root/client/client.key'), keypass) client_cert = OpenSSL::X509::Certificate.new(File.read('/root/client/client.crt')) response = RestClient::Request.execute( method: :get, url: "https://{SERVER_IP_HERE}:{PORT}/1.0", # 补充https前缀,匹配curl请求路径 ssl_client_cert: client_cert, ssl_client_key: client_key, verify_ssl: OpenSSL::SSL::VERIFY_NONE ) puts response.body
备选方案:Ruby标准库Net::HTTP实现
如果RestClient仍有兼容性问题,可直接使用Ruby内置的Net::HTTP,稳定性更强:
require 'openssl' require 'net/http' # 配置参数 server_ip = "{SERVER_IP_HERE}" port = "{PORT}" api_path = "/1.0" cert_path = "/root/client/client.crt" key_path = "/root/client/client.key" keypass = '' # 加载证书和密钥 client_cert = OpenSSL::X509::Certificate.new(File.read(cert_path)) client_key = OpenSSL::PKey.read(File.read(key_path), keypass) # 构建并发送请求 uri = URI("https://#{server_ip}:#{port}#{api_path}") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE # 对应curl的-k参数 http.cert = client_cert http.key = client_key response = http.get(uri.path) puts response.body
内容的提问来源于stack exchange,提问作者medBouzid
相关产品推荐
相关产品推荐

