0
有誰知道如何正確準備將BYTEA數據類型插入到postgresql中嗎?我有一個從libmcrypt生成的加密字符串。我希望將加密存儲在定義爲 「cdata bytea not null」的表列中。在PostgreSQL中準備,存儲,檢索加密數據
我的核心與命令行完美結合,但現在我希望將加密存儲在RDBMS中作爲opped文件。代碼片段如下:
int rs;
char buffer[1];
char dbuffer[1024];
datafile = "This is my house"; // assume this to be a file
crypt_key[] = "123456789"; // 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.
必須成功地插入和查詢加密的字符串進行解密。
在此先感謝。
來自pgsql-hackers的交叉帖子:http://www.postgresql.org/message-id/[email protected]。後來發現這種情況的讀者也應該關注這個話題,以防晚些時候發佈相關信息。 – 2013-03-04 07:54:13
順便說一句,這段代碼應該真正使用libpq的參數化查詢接口來確保它可以安全地避免任何可能的SQL注入風險,並且更容易調試和轉義。 – 2013-03-04 07:59:02
您引用的過程db處理過程僅僅是我的libpq庫調用的一個包裝器,以減少寫入的行數,並且現在已經工作了多年,沒有任何已知或已報告的損害。但是,我試圖找到解決二進制字符串問題的答案,我使用的是加密輸出,我相信的是,我正在使用的準備技術。這段代碼完全適用於文件I/O,但不適用於DB插入調用。我正在開發這個PSQL版本9.2.3 – Rico 2013-03-04 15:39:46