Subversion Repositories MLServ

Rev

Rev 6 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
5 nishi 1
/* $Id: crypt.c 5 2024-09-25 00:19:35Z nishi $ */
2
 
3
#include "cm_crypt.h"
4
 
5
#include <unistd.h>
6
#include <stdio.h>
7
#include <stdlib.h>
8
#include <string.h>
9
 
10
const char* cm_crypt_methods[] = {"DES", "MD5", "Blowfish", "", "", "SHA-256", "SHA-512"};
11
 
12
char* cm_crypt_spec(int num, const char* string, const char* salt) {
13
	char* r = NULL;
14
	if(num == C_DES) {
15
		r = crypt(string, salt);
16
	} else if(num == C_MD5 || num == C_SHA256 || num == C_SHA512) {
17
		char* buffer = malloc(3 + strlen(salt) + 1);
18
		buffer[3 + strlen(salt)] = 0;
19
		sprintf(buffer, "$%d$%s", num, salt);
20
 
21
		r = crypt(string, buffer);
22
 
23
		free(buffer);
24
	} else if(num == C_BLOWFISH) {
25
		char* buffer = malloc(4 + 3 + strlen(salt) + 1);
26
		buffer[4 + 3 + strlen(salt)] = 0;
27
		sprintf(buffer, "$%da$08$%s", num, salt);
28
 
29
		r = crypt(string, buffer);
30
 
31
		free(buffer);
32
	}
33
	if(r == NULL || strcmp(r, "*0") == 0 || strcmp(r, ":") == 0) r = NULL;
34
	return r;
35
}
36
 
37
int cm_crypt_try(int num) {
38
	printf("Trying %s... ", cm_crypt_methods[num]);
39
	fflush(stdout);
40
 
41
	if(cm_crypt_spec(num, "random", "randomrandomrandomrandom") != NULL) {
42
		printf("works\n");
43
		return 1;
44
	} else {
45
		printf("does not work\n");
46
		return 0;
47
	}
48
}
49
 
50
int cm_chosen_crypt;
51
 
52
int cm_crypt_init(void) {
53
	int i;
54
	int last = -1;
55
	for(i = C_START + 1; i < C_END; i++) {
56
		if(strlen(cm_crypt_methods[i]) != 0) {
57
			if(cm_crypt_try(i)) {
58
				last = i;
59
			}
60
		}
61
	}
62
	cm_chosen_crypt = last;
63
	return last;
64
}
65
 
66
char* cm_crypt(const char* string) {
67
	char salt[65];
68
	salt[64] = 0;
69
	int i;
70
	FILE* f = fopen("/dev/urandom", "rb");
71
	unsigned char c;
72
	const char usable[] = "0123456789abcdefghijklmnopqrstuvwxyz";
73
	for(i = 0; i < 64; i++) {
74
		fread(&c, 1, 1, f);
75
		salt[i] = c % strlen(usable);
76
	}
77
	fclose(f);
78
	return cm_crypt_spec(cm_chosen_crypt, string, salt);
79
}