Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I am trying to encrypt a Postgres table column using my own algorithms. I am reading rsa key from file and encrypting data using algorithms. My column type is bytea.

When I try to insert encrypted data the Postgres gives the following error:

pg_query(): Query failed: ERROR: invalid byte sequence for encoding "UTF8": 0xa3

I tried few options setting encoding as found on internet but did not work.

I don't know what is causing this error.

share|improve this question

The problem is that you are trying to store binary data in a string (text, character varying, …) column.

PostgreSQL rejects data that do not match the encoding set by the parameter client_encoding. If you study RFC 3629, you will find that no character can start with 0xa3 (binary 10100011) in UTF-8.

The solution is to use a column of type bytea (byte array) to store binary data.

share|improve this answer
    
I am using bytea column type.. – Sachin Patil Jul 25 at 11:14
    
Could you show the complete insert statement and table definition? – Laurenz Albe Jul 25 at 12:15

The salient part of your code consists of these lines:

$ec = SaferCrypto::encrypt($c, $k);

So $ec presumably contains binary at this point. And so the rest is wrong:

$query = "INSERT into enc_test values('$ec')";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());

because you're trying to pass binary contents directly in the text of a query. The value must be encoded in a text representation to be injected as a literal into the query's values clause.

This should be done with the pg_escape_bytea() function.

share|improve this answer
    
Thank you very much .. pg_escape_bytea() worked..!! – Sachin Patil Jul 26 at 17:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.