#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include "postgres.h"
#include "fmgr.h"
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(decrypt_data);
Datum decrypt_data(PG_FUNCTION_ARGS)
{
text *cipherdata = PG_GETARG_TEXT_P(0);
text *keyid = PG_GETARG_TEXT_P(1);
text *metadata = PG_GETARG_TEXT_P(2);
text *ivhex = PG_GETARG_TEXT_P(3);
int32 cipherdata_len = VARSIZE(cipherdata) - VARHDRSZ;
int32 keyid_len = VARSIZE(keyid) - VARHDRSZ;
int32 metadata_len = VARSIZE(metadata) - VARHDRSZ;
int32 ivhex_len = VARSIZE(ivhex) - VARHDRSZ;
int32 new_text_size = cipherdata_len + VARHDRSZ;
text *new_text = (text *) palloc(new_text_size);
SET_VARSIZE(new_text, new_text_size);
char *ch_plain = NULL;
unsigned char *ch_cipher = NULL;
char ch_keyid[128] = {0};
char ch_metadata[128] = {0};
char ch_ivhex[128] = {0};
char ch_end[1+1] = {0};
int i_ret = 0;
ch_plain = (char *)malloc(cipherdata_len + 64);
if (ch_plain == NULL)
{
memcpy(VARDATA(new_text), VARDATA(cipherdata), cipherdata_len);
PG_RETURN_TEXT_P(new_text);
}
ch_cipher = (char *)malloc(cipherdata_len + 64);
if (ch_cipher == NULL)
{
free(ch_plain);
memcpy(VARDATA(new_text), VARDATA(cipherdata), cipherdata_len);
PG_RETURN_TEXT_P(new_text);
}
memset(ch_plain,0,cipherdata_len + 64);
memset(ch_cipher,0,cipherdata_len + 64);
memcpy(ch_cipher,VARDATA(cipherdata), cipherdata_len);
memcpy(ch_keyid,VARDATA(keyid), keyid_len);
memcpy(ch_metadata,VARDATA(metadata), metadata_len);
memcpy(ch_ivhex,VARDATA(ivhex), ivhex_len);
i_ret = Sm4GcmDecryptData(ch_cipher,ch_plain,ch_keyid,ch_metadata,ch_ivhex);
if ( i_ret != 0 )
{
free(ch_plain);
free(ch_cipher);
memcpy(VARDATA(new_text), VARDATA(cipherdata), cipherdata_len);
PG_RETURN_TEXT_P(new_text);
}
else
{
memcpy(VARDATA(new_text),ch_plain, strlen(ch_plain));
memcpy(VARDATA(new_text) + strlen(ch_plain),ch_end, 1);
free(ch_plain);
free(ch_cipher);
PG_RETURN_TEXT_P(new_text);
}
}
编译生成动态库;
创建函数
create function decryptdata(varchar(256),varchar(64),varchar(64),varchar(64)) RETURNs VARCHAR(256)
AS 'libpostgresudf_Sdk.so', 'decrypt_data'
LANGUAGE C STRICT;
select name from AAA;
select decryptaoedata(name,'131798494913716','d4bcf051406dda1832b15a91fc652fb8','5b45197f108bb6ef18963796c394175b') from AAA;
|