hammer2 - Fix flush issues with unmounted PFSs and shutdown panic
[dragonfly.git] / sbin / md5 / sha1hl.c
blob5068fc9f74ae0b1e5cc00edca62b1ba10566ebcd
1 /* mdXhl.c * ----------------------------------------------------------------------------
2 * "THE BEER-WARE LICENSE" (Revision 42):
3 * <phk@FreeBSD.org> wrote this file. As long as you retain this notice you
4 * can do whatever you want with this stuff. If we meet some day, and you think
5 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
6 * ----------------------------------------------------------------------------
8 * $FreeBSD: src/lib/libmd/mdXhl.c,v 1.19 2006/01/17 15:35:56 phk Exp $
9 * $DragonFly: src/lib/libmd/mdXhl.c,v 1.3 2008/09/11 20:25:34 swildner Exp $
12 * This code has been deprecated, do not put this in libmd or anywhere else please.
13 * The few base system programs that use this code will .PATH it in.
15 * Note that libcrypto/lib[re]ssl provides the standard API that this file extends
16 * for these functions.
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <sha.h>
25 #include <errno.h>
26 #include <stdio.h>
27 #include <stdlib.h>
29 #include "sha1hl.h"
31 #define LENGTH 20
33 char *
34 SHA1_End(SHA1_CTX *ctx, char *buf)
36 int i;
37 unsigned char digest[LENGTH];
38 static const char hex[]="0123456789abcdef";
40 if (!buf)
41 buf = malloc(2*LENGTH + 1);
42 if (!buf)
43 return 0;
44 SHA1_Final(digest, ctx);
45 for (i = 0; i < LENGTH; i++) {
46 buf[i+i] = hex[digest[i] >> 4];
47 buf[i+i+1] = hex[digest[i] & 0x0f];
49 buf[i+i] = '\0';
50 return buf;
53 char *
54 SHA1_File(const char *filename, char *buf)
56 return (SHA1_FileChunk(filename, buf, 0, 0));
59 char *
60 SHA1_FileChunk(const char *filename, char *buf, off_t ofs, off_t len)
62 unsigned char buffer[8192];
63 SHA1_CTX ctx;
64 struct stat stbuf;
65 int f, i, e;
66 off_t n;
68 SHA1_Init(&ctx);
69 f = open(filename, O_RDONLY);
70 if (f < 0)
71 return 0;
72 if (fstat(f, &stbuf) < 0)
73 return 0;
74 if (ofs > stbuf.st_size)
75 ofs = stbuf.st_size;
76 if ((len == 0) || (len > stbuf.st_size - ofs))
77 len = stbuf.st_size - ofs;
78 if (lseek(f, ofs, SEEK_SET) < 0)
79 return 0;
80 n = len;
81 i = 0;
82 while (n > 0) {
83 if ((size_t)n > sizeof(buffer))
84 i = read(f, buffer, sizeof(buffer));
85 else
86 i = read(f, buffer, n);
87 if (i < 0)
88 break;
89 SHA1_Update(&ctx, buffer, i);
90 n -= i;
92 e = errno;
93 close(f);
94 errno = e;
95 if (i < 0)
96 return 0;
97 return (SHA1_End(&ctx, buf));
100 char *
101 SHA1_Data (const void *data, unsigned int len, char *buf)
103 SHA1_CTX ctx;
105 SHA1_Init(&ctx);
106 SHA1_Update(&ctx,data,len);
107 return (SHA1_End(&ctx, buf));