使用psycopg2

时间:2018-04-19 16:52:40

标签: python ssl openssl google-cloud-platform psycopg2

直到今天我都没有关于加密的线索所以请原谅我,如果我的问题是基本的。

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

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

我计算机中的文件。

我正在尝试使用python3.6中的psycopg2连接到远程数据库(使用conda安装)。我检查了documentation以建立连接,显然需要使用上面的文件,以便我可以建立连接。具体在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]

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

在我的研究之后,我发现我(可能)必须使用openssl来生成.crt.key格式。我该怎么做?

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

1 个答案:

答案 0 :(得分:1)

使用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参数。