gpt4 book ai didi

c - 在 PostgreSQL 中准备、存储、检索加密数据

转载 作者:行者123 更新时间:2023-11-30 17:54:04 25 4
gpt4 key购买 nike

有谁知道如何正确准备将 BYTEA 数据类型插入到 postgresql 中?我有一个从 libmcrypt 生成的加密字符串。我希望将加密存储在定义为的表列中 “cdata bytea 不为空”

我的核心可以与命令行完美配合,但现在我希望将加密存储在 RDBMS 中,而不是文件。代码片段如下:

int rs;
char buffer[1];
char dbuffer[1024];
datafile = "This is my house"; // assume this to be a file
crypt_key[] = "12345678901234567890123456789012"; // 32 bytes
crypt_iv[] = "11111111111111111111111111111111"; // 32 bytes
mfd = mcrypt_module_open(MCRYPT_RIJNDAEL_256, NULL, "cfb", NULL); // assume success
mcrypt_generic_init(mfd, crypt_Key, 32,crypt_iv); // assume success

while(readInputFile(datafile,buffer,sizeof(buffer),&bytes) == cgiFormSuccess) {
mcrypt_generic(mfd,buffer,sizeof(buffer)); // buffer size s/b 1
dbuffer[i++] = *buffer;
dbuffer[i] = '\0'; // Time spent on string sanity
} // processed each byte is now encrypted

// Now I wish to prepare dbuffer for table insertion
sb = PQescapeByteaConn(dbconn,dbuffer,(size_t)strlen(dbuffer),&rs);

// Perform Insertion --> cdata::BYTEA
sprintf(query,"INSERT INTO crypto (uid,crypt_key,crypt_iv,cdata,cfile)"
"VALUES('%s','%s','%s','%s','%s')",
ebs->uid,ebs->crkey,ebs->crivs,sb,credf); // cfile == original filename
ebs->r=db_func_query(ebs->r,query,0,proc); // Please assume DB command success

// Expected output sb == \x...some hex, dbuffer == encrypted bytes. sb is now in bytea table column.
######################################
// Prepare to decrypt the cdata::bytea column

sprintf(query,"DECLARE %s CURSOR FOR SELECT crypt_iv,cdata,cfile " // not sure if cursor s/b regular or binary for this
"FROM crypto WHERE uid='%s' AND crypt_iv='%s' AND action=true",
VCURSOR,ebs->uid,ebs->crkey);

db_func_txn_begin(ebs->r,proc);
ebs->r = db_func_query(ebs->r,query,1,proc); // process the query and assume it delivers the row
if(totalrow) {
nFields = PQnfields(ebs->r);
char* results[nFields];
for(i = 0;i < totalrow;i++) {
for(j = 0;j < nFields;j++)
results[j] = PQgetvalue(ebs->r,i,j);
strcpy(crypt_iv,results[0]);
strcpy(dbuffer,results[1]);
strcpy(cfile,results[2]);
}
mcrypt_generic_init(mfd, crypt_Key, 32,crypt_iv); // assume success
sb = PQunescapeBytea(dataBuf,&rs);

for(i = 0;i < rs+1;i++) {
mdecrypt_generic(mfd,sb[i],1); // buffer size s/b 1
dbuffer[i] = sb[i];
dbuffer[i+1] = '\0'; // Time spent on string sanity
}

// Expected output sb == reverse of PQescapeByteaConn, dbuffer == unencrypted bytes.

必须有一种方法可以成功插入和查询加密字符串以进行解密。

提前致谢。

最佳答案

问题已解决。只要转义 mcrypted 字符串的输出,您就可以只使用文本列。 Bytea 更干净,但代码行更多,PGunescapeBytea 显然是强制解密的。

关于c - 在 PostgreSQL 中准备、存储、检索加密数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15196151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com