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:
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;
The above approach for encryption is working fine and an armored PGP encrypted value gets saved as below:
-----BEGIN PGP MESSAGE-----
ww0EBwMCneBsNZw1gYFq0jYB9y58EoTaRXWmDFqvQArWU5tZ+wS+7yAm9ycVUpkH1EzvYLbfRoDj
rqR83I0nGErHcLSLlAs=
=IYg8
-----END PGP MESSAGE-----
Decryption needs to be done at the application level for which I followed the following 2 steps:
- Added bcpg-jdk15on and bcprov-jdk15on dependencies. (v1.47)
- Implementation:
String key = "aes_key";
File file = new File("D:\\file.txt.asc"); //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())));
I keep getting the following exception while using the above approach to decrypt the value:
Exception in thread "main" 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)
So can someone guide me to the appropriate approach to achieve decryption at the application level (not in the queries).