0

I am using the below code to encrypt the data in Java. But when trying to decrypt it using the query I am getting an error Wrong key or corrupt data

SELECT pgp_sym_decrypt(
    decode(email, 'base64'), 
    'secretKeyForTest', 'cipher-algo=aes256'
) 
 from table
where user_id = '1';
public static String encrypt(
            String data,
            String passPhrase
    ) throws IOException, PGPException, NoSuchProviderException, NoSuchAlgorithmException {
        // Create a PGPEncryptedDataGenerator to perform encryption
        PGPDataEncryptorBuilder encryptorBuilder = new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_256)
                .setWithIntegrityPacket(true)
                .setSecureRandom(new SecureRandom());

        PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(encryptorBuilder);
        encryptedDataGenerator.addMethod(new JcePBEKeyEncryptionMethodGenerator(passPhrase.toCharArray()));

        // Encrypt data
        ByteArrayOutputStream encryptedOut = new ByteArrayOutputStream();
        try (OutputStream encryptedStream = encryptedDataGenerator.open(encryptedOut, new byte[4096])) {
            encryptedStream.write(data.getBytes(StandardCharsets.UTF_8));
        }

        return Base64.getEncoder().encodeToString(encryptedOut.toByteArray());
    }
3
  • What is the data type for the email field? Commented Jan 15 at 16:10
  • email is varchar - @AdrianKlaver Commented Jan 16 at 5:57
  • From here PGP Encryption Functions: pgp_sym_decrypt(msg bytea, psw text [, options text ]) returns text. Note the function is looking for bytea. select pgp_sym_decrypt(pgp_sym_encrypt('this is a test', 'test pwd', 'cipher-algo=aes256'), 'test pwd', 'cipher-algo=aes256'); this is a test Commented Jan 16 at 17:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.