@@ -83,6 +83,7 @@ struct codec_ctx {
8383 cipher_ctx * read_ctx ;
8484 cipher_ctx * write_ctx ;
8585 unsigned int skip_read_hmac ;
86+ unsigned int need_kdf_salt ;
8687};
8788
8889int sqlcipher_register_provider (sqlcipher_provider * p ) {
@@ -650,8 +651,7 @@ int sqlcipher_codec_ctx_init(codec_ctx **iCtx, Db *pDb, Pager *pPager, sqlite3_f
650651 if ((rc = sqlcipher_cipher_ctx_init (& ctx -> write_ctx )) != SQLITE_OK ) return rc ;
651652
652653 if (fd == NULL || sqlite3OsRead (fd , ctx -> kdf_salt , FILE_HEADER_SZ , 0 ) != SQLITE_OK ) {
653- /* if unable to read the bytes, generate random salt */
654- if (ctx -> read_ctx -> provider -> random (ctx -> read_ctx -> provider_ctx , ctx -> kdf_salt , FILE_HEADER_SZ ) != SQLITE_OK ) return SQLITE_ERROR ;
654+ ctx -> need_kdf_salt = 1 ;
655655 }
656656
657657 if ((rc = sqlcipher_codec_ctx_set_cipher (ctx , CIPHER , 0 )) != SQLITE_OK ) return rc ;
@@ -823,8 +823,13 @@ static int sqlcipher_cipher_ctx_key_derive(codec_ctx *ctx, cipher_ctx *c_ctx) {
823823 c_ctx -> pass , c_ctx -> pass_sz , ctx -> kdf_salt , ctx -> kdf_salt_sz , c_ctx -> kdf_iter ,
824824 ctx -> hmac_kdf_salt , c_ctx -> fast_kdf_iter , c_ctx -> key_sz ));
825825
826-
826+
827827 if (c_ctx -> pass && c_ctx -> pass_sz ) { // if pass is not null
828+
829+ if (ctx -> need_kdf_salt ) {
830+ if (ctx -> read_ctx -> provider -> random (ctx -> read_ctx -> provider_ctx , ctx -> kdf_salt , FILE_HEADER_SZ ) != SQLITE_OK ) return SQLITE_ERROR ;
831+ ctx -> need_kdf_salt = 0 ;
832+ }
828833 if (c_ctx -> pass_sz == ((c_ctx -> key_sz * 2 ) + 3 ) && sqlite3StrNICmp ((const char * )c_ctx -> pass ,"x'" , 2 ) == 0 ) {
829834 int n = c_ctx -> pass_sz - 3 ; /* adjust for leading x' and tailing ' */
830835 const unsigned char * z = c_ctx -> pass + 2 ; /* adjust lead offset of x' */
@@ -1119,6 +1124,23 @@ int sqlcipher_codec_ctx_migrate(codec_ctx *ctx) {
11191124 return rc ;
11201125}
11211126
1127+ int sqlcipher_codec_add_random (codec_ctx * ctx , const char * zRight ){
1128+ int random_sz = strlen (zRight );
1129+ if (random_sz == ((ctx -> read_ctx -> key_sz * 2 ) + 3 ) && sqlite3StrNICmp ((const char * )zRight ,"x'" , 2 ) == 0 ) {
1130+ unsigned char * random ;
1131+ int n = random_sz - 3 ; /* adjust for leading x' and tailing ' */
1132+ const unsigned char * z = (const unsigned char * )zRight + 2 ; /* adjust lead offset of x' */
1133+ CODEC_TRACE (("sqlcipher_codec_add_random: using raw random blob from hex\n" ));
1134+ random = sqlcipher_malloc (n );
1135+ memset (random , 0 , n );
1136+ cipher_hex2bin (z , n , random );
1137+ int rc = ctx -> read_ctx -> provider -> add_random (ctx -> read_ctx -> provider_ctx , random , n );
1138+ sqlcipher_free (random , n );
1139+ return rc ;
1140+ }
1141+ return SQLITE_ERROR ;
1142+ }
1143+
11221144
11231145#endif
11241146/* END SQLCIPHER */
0 commit comments