0

I'm trying to encrypt/decrypt between javascript and postgresql.

I'm using this: https://gist.github.com/vlucas/2bd40f62d20c1d49237a109d491974eb algorithm to encrypt my text, and then in PostgreSQL I use PGCRYPTO.decrypt_iv to decrypt the text.

Encrypted string returned from above: "fc9a03cbc8a57d4061570575f197c29c:a319a4bf354516f392ba96a895478af6"

I have to remove the colon to get something out...and so this:

   select decrypt_iv(decode('fc9a03cbc8a57d4061570575f197c29ca319a4bf354516f392ba96a895478af6','hex')::bytea, 'sKCx49VgtHZ59bJOTLcU0Gr06ogUnDJi'::bytea, 
'null'::bytea, 'aes-cbc/pad:pkcs');

Gives me this: 6 á¶ðÒÿÆÛÏBSïÅThisISMySign

The text in bold was the original string.

The paremeter after the key, 3rd parameter, it can be any string. That just changes the first part of the output, the garbage part.

In decrypt_iv I tried using the encryption algorithm name in the javascript used to encrypt, but that gets me nowhere.

I cannot see what i'm missing here.

1 Answer 1

2

In short. In Javascript use the CryptoJS library and go:

import CryptoJS from 'crypto-js';

const key = CryptoJS.enc.Hex.parse('12345678901234567890123456789012');
var iv = CryptoJS.enc.Hex.parse('12341234123412341234123412341234');

function encrypt(text) {
    let encrypted = CryptoJS.AES.encrypt(text, key, { iv });
    return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}

const text = JSON.stringify({ a: 1, b: 2, c: [{}, {}] });

const encrypted = encrypt(text) // --> BDg4dXSvNbWAOeZY/8XQpr6fQMZqnnhQwv8REep4LvQ=

In Postgres, go:

select convert_from(
  extensions.decrypt_iv(
    decode('BDg4dXSvNbWAOeZY/8XQpr6fQMZqnnhQwv8REep4LvQ=','base64')::bytea, -- encrypted text
    decode('12345678901234567890123456789012','hex')::bytea, -- key
    decode('12341234123412341234123412341234','hex')::bytea, -- iv
    'aes'
  ),
  'utf8'
) --> {"a":1,"b":2,"c":[{},{}]}

I've seen it mentioned somewhere that one should use pgp in javascript and Pgp_sym_decrypt in Postgres for added security. I will update this answer if I have more time.

Sign up to request clarification or add additional context in comments.

Comments

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.