|
| 1 | +#include "pgsodium.h" |
| 2 | + |
| 3 | +PG_FUNCTION_INFO_V1 (pgsodium_crypto_aead_det_decrypt_by_id); |
| 4 | +Datum |
| 5 | +pgsodium_crypto_aead_det_decrypt_by_id (PG_FUNCTION_ARGS) |
| 6 | +{ |
| 7 | + bytea *ciphertext; |
| 8 | + bytea *associated; |
| 9 | + unsigned long long key_id; |
| 10 | + bytea *context; |
| 11 | + size_t result_len; |
| 12 | + bytea *key, *result, *nonce; |
| 13 | + int success; |
| 14 | + |
| 15 | + |
| 16 | + ERRORIF (PG_ARGISNULL (0), "%s: message cannot be NULL"); |
| 17 | + ERRORIF (PG_ARGISNULL (2), "%s: key id cannot be NULL"); |
| 18 | + ERRORIF (PG_ARGISNULL (3), "%s: key context cannot be NULL"); |
| 19 | + |
| 20 | + ciphertext = PG_GETARG_BYTEA_PP (0); |
| 21 | + |
| 22 | + if (!PG_ARGISNULL (1)) |
| 23 | + { |
| 24 | + associated = PG_GETARG_BYTEA_PP (1); |
| 25 | + } |
| 26 | + else |
| 27 | + { |
| 28 | + associated = NULL; |
| 29 | + } |
| 30 | + |
| 31 | + key_id = PG_GETARG_INT64 (2); |
| 32 | + context = PG_GETARG_BYTEA_PP (3); |
| 33 | + |
| 34 | + if (!PG_ARGISNULL (4)) |
| 35 | + { |
| 36 | + nonce = PG_GETARG_BYTEA_PP (4); |
| 37 | + ERRORIF (VARSIZE_ANY_EXHDR (nonce) != |
| 38 | + crypto_aead_det_xchacha20_NONCEBYTES, "%s: invalid nonce"); |
| 39 | + } |
| 40 | + else |
| 41 | + { |
| 42 | + nonce = NULL; |
| 43 | + } |
| 44 | + ERRORIF (VARSIZE_ANY_EXHDR (ciphertext) <= |
| 45 | + crypto_aead_det_xchacha20_ABYTES, "%s: invalid message"); |
| 46 | + result_len = |
| 47 | + VARSIZE_ANY_EXHDR (ciphertext) - crypto_aead_det_xchacha20_ABYTES; |
| 48 | + result = _pgsodium_zalloc_bytea (result_len + VARHDRSZ); |
| 49 | + key = |
| 50 | + pgsodium_derive_helper (key_id, crypto_aead_det_xchacha20_KEYBYTES, |
| 51 | + context); |
| 52 | + |
| 53 | + success = crypto_aead_det_xchacha20_decrypt ( |
| 54 | + PGSODIUM_UCHARDATA (result), |
| 55 | + PGSODIUM_UCHARDATA_ANY (ciphertext), |
| 56 | + VARSIZE_ANY_EXHDR (ciphertext), |
| 57 | + associated != NULL ? PGSODIUM_UCHARDATA_ANY (associated) : NULL, |
| 58 | + associated != NULL ? VARSIZE_ANY_EXHDR (associated) : 0, |
| 59 | + nonce != NULL ? PGSODIUM_UCHARDATA_ANY (nonce) : NULL, |
| 60 | + PGSODIUM_UCHARDATA_ANY (key)); |
| 61 | + ERRORIF (success != 0, "%s: invalid ciphertext"); |
| 62 | + PG_RETURN_BYTEA_P (result); |
| 63 | +} |
0 commit comments