根据克雷格的建议,我最终使用 plpythonu 来解决这个问题。
CREATE OR REPLACE FUNCTION api.verify(
p_data text,
p_signature text,
p_publickey text
)
RETURNS boolean AS
$$
try:
import rsa
pubkey = rsa.PublicKey.load_pkcs1(p_publickey)
signature = bytearray.fromhex(p_signature)
verified = rsa.verify(p_data, signature, pubkey)
return verified
except:
return False
$$ LANGUAGE plpythonu VOLATILE
SECURITY DEFINER;
由于我缺乏 python 知识,这其中最困难的部分实际上是设置所需的 python 包(在我的例子中是 Docker 环境)。以下是 Dockerfile 的相关摘录:
FROM postgres:9.6
# Install necessary python packages to work with postgres
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
"postgresql-plpython-$PG_MAJOR" \
&& apt-get install -y python-pip python-dev
# Install python rsa module for signature verification
RUN pip install rsa
该函数在给定以下参数的情况下起作用:
-- Generate private key. Provide secure passphrase when prompted.
openssl genrsa -aes256 -out private.pem 4096
--Export public KEY
openssl rsa -in private.pem -RSAPublicKey_out -out public.pem
--Sign data. Provide secure passphrase when prompted.
--Remove first line (RSA-SHA256(data.txt)=) when passing into database verify function.
openssl dgst -hex -sign private.pem data.txt > signature.txt