使用 pgcrypto (PostgresQL) 解密 AES GCM 256

时间:2021-03-01 11:58:46

标签: postgresql encryption aes-gcm pgcrypto

我正在尝试使用使用 AES GCM 256 加密的 pgcrypto 解密消息。

加密规范:

Encryption algorithm     AES
Key                      [secret of listener] (64-character-long hexadecimal string in configuration)
Key length               256 bits (32 bytes)
Block mode               GCM
Padding                  None
Initialization vector    In HTTP header (X-Initialization-Vector)
Authentication tag       In HTTP header (X-Authentication-Tag)

所以我收到了:

  • 身体
  • iv_header
  • auth_tag

我尝试了以下

with base as (
select
    'F8E2F759E528CB69375E51DB2AF9B53734E393' as body,
    '000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F' as key,
    '3D575574536D450F71AC76D8' as iv_header,
    '19FDD068C6F383C173D3A906F7BD1D83' as auth_tag
),
out as (
    select
        decrypt_iv(
            convert_to(concat(decode(body,'hex'),decode(auth_tag,'hex')),'LATIN1'),
            decode(key, 'hex'),
            decode(iv_header, 'hex'),
            'aes/pad:none'
        )
    from base
)

select * from out

我一直收到错误 decrypt_iv error: Data not a multiple of block size 而我希望得到编码消息 {"type": "PAYMENT"}

我预计 bodyauth_tag 的解码和连接会出错,但不知道是什么。

关于我这样做的原因/原因的一些说明

  • 我将 auth_tag 连接到 body,因为有几个来源是这样描述的。
  • 我使用 convert_to 函数,因为它似乎是连接两个 bytea 值的唯一方法

我设法用其他语言(即雪花或 Python)解密了这条消息

如果有人看到我做错了什么或有一些指导,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

pgcrypto 只说它支持 cbc 和 ecb。我不是密码学家,但我认为其中任何一个都与 GCM 不同。所以我认为你不能用 pgcrypto 做到这一点。我不知道为什么它会导致您得到的确切错误,但这也不会让我感到惊讶。

如果我真的需要在数据库中执行此操作,我想我可以通过使用 pl/python3u 编写一个函数来实现。

相关问题