Ticket #50: core_add_ngx_crypt_sha.patch

File core_add_ngx_crypt_sha.patch, 1.7 KB (added by Louis Opter, 14 years ago)

Add support for {SHA} in htpasswd files

  • src/core/ngx_crypt.c

    Add support for the {SHA} encryption scheme in htpasswd files
    
    Author: Louis Opter <kalessin@kalessin.fr
    
    diff --git a/src/core/ngx_crypt.c b/src/core/ngx_crypt.c
    a b  
    2424
    2525static ngx_int_t ngx_crypt_ssha(ngx_pool_t *pool, u_char *key, u_char *salt,
    2626    u_char **encrypted);
     27static ngx_int_t ngx_crypt_sha(ngx_pool_t *pool, u_char *key, u_char *salt,
     28    u_char **encrypted);
    2729
    2830#endif
    2931
     
    4345#if (NGX_HAVE_SHA1)
    4446    } else if (ngx_strncmp(salt, "{SSHA}", sizeof("{SSHA}") - 1) == 0) {
    4547        return ngx_crypt_ssha(pool, key, salt, encrypted);
     48    } else if (ngx_strncmp(salt, "{SHA}", sizeof("{SHA}") - 1) == 0) {
     49        return ngx_crypt_sha(pool, key, salt, encrypted);
    4650#endif
    4751    }
    4852
     
    241245    return NGX_OK;
    242246}
    243247
     248static ngx_int_t
     249ngx_crypt_sha(ngx_pool_t *pool, u_char *key, u_char *salt, u_char **encrypted)
     250{
     251    ngx_sha1_t  sha1;
     252    u_char      digest[20];
     253    ngx_str_t   encoded, decoded;
     254
     255    /* "{SHA}" base64(SHA1(key)), generated with htpasswd -s from Apache */
     256
     257    decoded.len = sizeof(digest);
     258    decoded.data = digest;
     259
     260    ngx_sha1_init(&sha1);
     261    ngx_sha1_update(&sha1, key, ngx_strlen(key));
     262    ngx_sha1_final(digest, &sha1);
     263
     264    encoded.len = sizeof("{SHA}") - 1 + ngx_base64_encoded_length(sizeof(digest)) + 1;
     265    *encrypted = ngx_pnalloc(pool, encoded.len);
     266    if (*encrypted == NULL) {
     267        return NGX_ERROR;
     268    }
     269
     270    encoded.data = ngx_cpymem(*encrypted, "{SHA}", sizeof("{SHA}") - 1);
     271    ngx_encode_base64(&encoded, &decoded);
     272    encoded.data[encoded.len] = '\0';
     273
     274    return NGX_OK;
     275}
     276
    244277#endif /* NGX_HAVE_SHA1 */
    245278
    246279#endif /* NGX_CRYPT */