Diff
Not logged in

Differences From:

File src/blob.c part of check-in [5468ec7c5e] - Incremental changes toward encrypting sync traffic. The changes are incomplete, but all legacy functionality appears to still works. by drh on 2009-03-26 15:32:43. [view]

To:

File src/blob.c part of check-in [bf16ab9b7b] - Completed implementation of utility functions to encrypt and decrypt blobs. by drh on 2009-03-26 23:26:31. [view]

@@ -908,8 +908,13 @@
   }
 }
 
 /*
+** Number of bytes of nonce for each encoding
+*/
+#define N_NONCE 20
+
+/*
 ** Encrypt a blob using RC4.
 **
 ** The key is constructed by taking the sha1 hash of the password
 ** and a random 20-byte nonce.  This nonce becomes the first 20 bytes
@@ -927,19 +932,24 @@
 ** pOut should be initialized prior to invoking this routine.  pOut might
 ** already contain other content.  The encryption is appended to pOut.
 */
 void blob_encrypt(Blob *pIn, const char *zPassword, Blob *pOut){
-  unsigned char aNonce[20];
-  unsigned char *aIn;
+  char *aNonce;
+  char *aIn;
   int nIn;
-  unsigned char *aOut;
+  char *aOut;
 
-  sqlite3_randomness(sizeof(aNonce), aNonce);
-  aIn = (unsigned char*)pIn->aData;
+  aIn = pIn->aData;
   aIn += pIn->iCursor;
   nIn = pIn->nUsed - pIn->iCursor;
   if( nIn<=0 ) return;
-
+  blob_resize(pOut, pOut->nUsed+nIn+N_NONCE);
+  aOut = pOut->aData;
+  aOut += pOut->iCursor;
+  aNonce = aOut;
+  sqlite3_randomness(N_NONCE, aNonce);
+  aOut += N_NONCE;
+  rc4_coder(zPassword, aNonce, N_NONCE, aIn, nIn, aOut);
 }
 
 /*
 ** Decrypt a blob.
@@ -955,9 +965,47 @@
 ** pOut should be initialized prior to invoking this routine.  pOut might
 ** already contain other content.  The encryption is appended to pOut.
 */
 void blob_decrypt(Blob *pIn, const char *zPassword, Blob *pOut){
-  /* TBD... */
+  char *aNonce;
+  char *aIn;
+  int nIn;
+  char *aOut;
+
+  aIn = pIn->aData;
+  aNonce = aIn + pIn->iCursor;
+  aIn = aNonce + N_NONCE;
+  nIn = pIn->nUsed - pIn->iCursor - N_NONCE;
+  blob_resize(pOut, pOut->iCursor + nIn);
+  aOut = pOut->aData;
+  aOut += pOut->iCursor;
+  rc4_coder(zPassword, aNonce, N_NONCE, aIn, nIn, aOut);
+}
+
+
+/*
+** COMMAND: test-encrypt PASSWORD PLAINTEXT CYPHERTEXT
+*/
+void encrypt_test_cmd(void){
+  Blob in, out;
+  if( g.argc!=5 ) usage("PASSWORD INPUTFILE OUTPUTFILE");
+  blob_read_from_file(&in, g.argv[3]);
+  blob_zero(&out);
+  blob_encrypt(&in, g.argv[2], &out);
+  blob_write_to_file(&out, g.argv[4]);
+}
+
+
+/*
+** COMMAND: test-decrypt PASSWORD CYPHERTEXT PLAINTEXT
+*/
+void decrypt_test_cmd(void){
+  Blob in, out;
+  if( g.argc!=5 ) usage("PASSWORD INPUTFILE OUTPUTFILE");
+  blob_read_from_file(&in, g.argv[3]);
+  blob_zero(&out);
+  blob_decrypt(&in, g.argv[2], &out);
+  blob_write_to_file(&out, g.argv[4]);
 }
 
 #ifdef __MINGW32__
 /*