pgp_sym_decrypt_bytea返回值不符预期,已确认bytea字段求排查
Hey there, let's work through why your decrypted email field is spitting out that hex string instead of the readable address you expect!
First off, that \x66616b65406578616d706c652e636f6d value is just PostgreSQL's default way of displaying bytea data in hexadecimal format. When you add ::text to it, you're only converting that hex display to text—you're not actually translating the raw bytes back into the original character string. That’s why the result stays the same.
Here’s how to fix this:
Use
convert_from()to turn bytes into readable text
The critical step is converting the decrypted bytea value into a UTF-8 (or your preferred encoding) string. If you’re using thepgcryptoextension (since you mentioned creating an extension), your query should look like this:SELECT convert_from(pgp_sym_decrypt(email, 'your_encryption_key'), 'UTF8') AS decrypted_email FROM your_table;This takes the decrypted bytea output, interprets those bytes as UTF-8 characters, and returns the human-readable email address.
Test the conversion directly
You can confirm this works by running a quick test on the hex string you received:SELECT convert_from('\x66616b65406578616d706c652e636f6d'::bytea, 'UTF8');This should return
fake@example.com—exactly the original email you encrypted.Double-check your encryption workflow
Make sure when you encrypted the email, you passed the actual text (or properly converted bytea) to the encryption function. Forpgcrypto,pgp_sym_encryptaccepts text directly, so something like this works fine:INSERT INTO your_table (email) VALUES (pgp_sym_encrypt('fake@example.com', 'your_encryption_key'));No need to manually cast to bytea first here—the function handles that conversion internally.
Since you noted this is just a proof-of-concept and we can overlook the simple password, the main fix here is swapping out the basic ::text cast for convert_from() to get the readable string from your decrypted bytea data.
内容的提问来源于stack exchange,提问作者Anwinity

