Check-in [bf16ab9b7b]
Not logged in
Overview

SHA1 Hash:bf16ab9b7bdcaa80d7fd868b997abaa018e372e7
Date: 2009-03-26 23:26:31
User: drh
Comment:Completed implementation of utility functions to encrypt and decrypt blobs.
Timelines: ancestors | descendants | both | experimental
Other Links: files | ZIP archive | manifest

Tags And Properties
Changes
[hide diffs]

Modified src/blob.c from [4adbb9d2f8] to [2ed932bfd8].

@@ -907,10 +907,15 @@
     aOut[k] = aIn[k] ^ s[(s[i] + s[j])&255];
   }
 }
 
 /*
+** 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
 ** of the encrypted output.  The first 1000 bytes of the RC4 byte stream
@@ -926,21 +931,26 @@
 **
 ** 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.
 **
@@ -954,11 +964,49 @@
 **
 ** 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__
 /*
 ** Convert every \n character in the given blob into \r\n.