title: Encryption in postgres using pgcrypto module and Decryption in java
body: <p>I have created a trigger and a trigger function which invokes on every update operation on a table and encrypts a specific value as below:</p>
  <pre><code>create trigger project_trigger
  before update
  on projects
  for each row
  execute procedure project_function();
  
  create or replace function project_function()
  returns trigger as
  $BODY$
  begin
  IF (TG_OP = 'UPDATE') THEN
  NEW.title = armor(pgp_sym_encrypt(NEW.title, 'cipher-algo=aes256' ));
  return NEW;
  END IF;
  end;
  $BODY$
  language plpgsql;
  </code></pre>
  <p>The above approach for encryption is working fine and an armored PGP encrypted value gets saved as below:</p>
  <pre><code>-----BEGIN PGP MESSAGE-----
  
  ww0EBwMCneBsNZw1gYFq0jYB9y58EoTaRXWmDFqvQArWU5tZ+wS+7yAm9ycVUpkH1EzvYLbfRoDj
  rqR83I0nGErHcLSLlAs=
  =IYg8
  -----END PGP MESSAGE-----
  </code></pre>
  <p>Decryption needs to be done at the application level for which I followed the following 2 steps:</p>
  <ul>
  <li>Added bcpg-jdk15on and bcprov-jdk15on dependencies. (v1.47)</li>
  <li>Implementation:</li>
  </ul>
  <pre><code>String key = &quot;aes_key&quot;;
  File file = new File(&quot;D:\\file.txt.asc&quot;); //this file contains the PGP encrypted value as shown above
  InputStream input = new FileInputStream(file);
  byte[] byt = new byte[input.available()];
  input.read(byt);
  input.close();
  Security.addProvider(new BouncyCastleProvider());
  System.out.println(new String(ByteArrayHandler.decrypt(byt, 
                      key.toCharArray())));
  </code></pre>
  <p>I keep getting the following exception while using the above approach to decrypt the value:</p>
  <blockquote>
  <p>Exception in thread &quot;main&quot;
  org.bouncycastle.openpgp.PGPDataValidationException: data check
  failed.   at
  org.bouncycastle.openpgp.PGPPBEEncryptedData.getDataStream(Unknown
  Source)   at
  org.bouncycastle.openpgp.examples.ByteArrayHandler.decrypt(Unknown
  Source)   at
  abc.demo.encryption.SymmetricDecyption.main(SymmetricDecyption.java:59)</p>
  </blockquote>
  <p>So can someone guide me to the appropriate approach to achieve decryption at the application level (not in the queries).</p>