Use MD5 hashing to store passwords
[blerg.git] / common / auth.c
index 0dbe6a4..0d40455 100644 (file)
 #include "config.h"
 #include "auth.h"
 #include "util.h"
+#include "md5.h"
 
 #define TOKEN_SIZE 16
 #define MAX_PASSWORD_LENGTH 64
 
 int auth_set_password(const char *username, const char *password) {
        char filename[512];
+       unsigned char md5pass[MD5_DIGEST_SIZE];
+       struct MD5Context ctx;
        int fd, n;
 
        if (!valid_name(username) || !blerg_exists(username))
@@ -25,9 +28,14 @@ int auth_set_password(const char *username, const char *password) {
        if (n > MAX_PASSWORD_LENGTH)
                return 0;
 
+       MD5Init(&ctx);
+       MD5Update(&ctx, username, strlen(username));
+       MD5Update(&ctx, password, n);
+       MD5Final(md5pass, &ctx);
+
        snprintf(filename, 512, "%s/%s/password", DATA_PATH, username);
        fd = open(filename, O_WRONLY | O_CREAT, 0600);
-       write(fd, password, n);
+       write(fd, md5pass, MD5_DIGEST_SIZE);
        close(fd);
        
        return 1;
@@ -45,7 +53,7 @@ int auth_get_password(const char *username, char *password) {
        fd = open(filename, O_RDONLY);
        if (fd == -1)
                return 0;
-       len = read(fd, password, MAX_PASSWORD_LENGTH);
+       len = read(fd, password, MD5_DIGEST_SIZE);
        close(fd);
 
        password[len] = 0;
@@ -54,12 +62,19 @@ int auth_get_password(const char *username, char *password) {
 }
 
 int auth_check_password(const char *username, const char *password) {
-       char epw[33];
+       char epw[MD5_DIGEST_SIZE + 1];
+       unsigned char givenpw[MD5_DIGEST_SIZE];
+       struct MD5Context ctx;
 
        if (auth_get_password(username, epw) == 0)
                return 0;
 
-       if (strncmp(password, epw, MAX_PASSWORD_LENGTH) == 0)
+       MD5Init(&ctx);
+       MD5Update(&ctx, username, strlen(username));
+       MD5Update(&ctx, password, strlen(password));
+       MD5Final(givenpw, &ctx);
+
+       if (strncmp(givenpw, epw, MD5_DIGEST_SIZE) == 0)
                return 1;
        else
                return 0;