使用 psycopg2 连接到 Google Cloud SQL Postgres DB over SSL



直到今天我才对加密一无所知,所以如果我的问题是基本的,请原谅我。

我有一个使用 SSL 加密为 Postgres 设置的 GCP SQL 实例。我已经在 GCP 上创建了一个客户端证书,并下载并存储了:

  • server-ca.pem
  • client-cert.pem
  • client-key.pem

我的计算机中的文件。

我正在尝试使用 python2 中的 psycopg3.6(使用 conda 安装)连接到远程数据库。我已经检查了建立连接的文档,显然需要使用上述文件才能建立连接。具体来说,在psycopg2.connect()函数中,我使用以下参数:

  • sslmode='verify-ca'
  • sslcert=[local path of client-cert.pem file]
  • sslkey=[local path of client-key.pem file]
  • sslrootcert=[local path of server-ca.pem file]

显然会出现错误,因为根据此,上述文件需要以以下格式结尾:.crt.key.

经过研究,我发现我(也许)必须使用openssl来生成.crt.key格式。我应该怎么做?

如果我转换.pem文件并将转换后的文件传递给psycopg2.connect()我是否能够连接到我的远程数据库?

使用 openssl 将 .pem 文件转换为 .crt 和 .key 文件

首先使用命令提示符/终端转到存储.pem文件的目录。

对于 .crt 文件类型:

  • openssl x509 -in client-cert.pem -out ssl-cert.crt
  • openssl x509 -in server-ca.pem -out ca-cert.crt

对于 .key 文件类型:

  • openssl rsa -in client-key.pem -out ssl-key.key

最后,为了使用连接到数据库psycopg2.connect()只需将上述文件的文件路径传递给sslcert , sslkey and sslrootcert参数即可。

最新更新