libmongo-client 0.1.4
|
00001 /* compat.c - Various compatibility functions 00002 * Copyright 2011 Gergely Nagy <algernon@balabit.hu> 00003 * 00004 * Licensed under the Apache License, Version 2.0 (the "License"); 00005 * you may not use this file except in compliance with the License. 00006 * You may obtain a copy of the License at 00007 * 00008 * http://www.apache.org/licenses/LICENSE-2.0 00009 * 00010 * Unless required by applicable law or agreed to in writing, software 00011 * distributed under the License is distributed on an "AS IS" BASIS, 00012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00013 * See the License for the specific language governing permissions and 00014 * limitations under the License. 00015 */ 00016 00017 #include "config.h" 00018 00019 #if WITH_OPENSSL 00020 00021 #include "compat.h" 00022 #include <errno.h> 00023 #include <stdlib.h> 00024 #include <string.h> 00025 #include <openssl/md5.h> 00026 00027 struct _GChecksum 00028 { 00029 GChecksumType type; 00030 char hex_digest[33]; 00031 00032 MD5_CTX context; 00033 }; 00034 00035 GChecksum * 00036 g_checksum_new (GChecksumType checksum_type) 00037 { 00038 GChecksum *chk; 00039 00040 if (checksum_type != G_CHECKSUM_MD5) 00041 { 00042 errno = ENOSYS; 00043 return NULL; 00044 } 00045 00046 chk = calloc (1, sizeof (GChecksum)); 00047 chk->type = checksum_type; 00048 00049 MD5_Init (&chk->context); 00050 00051 return chk; 00052 } 00053 00054 void 00055 g_checksum_free (GChecksum *checksum) 00056 { 00057 if (checksum) 00058 free (checksum); 00059 } 00060 00061 void 00062 g_checksum_update (GChecksum *checksum, 00063 const unsigned char *data, 00064 ssize_t length) 00065 { 00066 size_t l = length; 00067 00068 if (!checksum || !data || length == 0) 00069 { 00070 errno = EINVAL; 00071 return; 00072 } 00073 errno = 0; 00074 00075 if (length < 0) 00076 l = strlen ((const char *)data); 00077 00078 MD5_Update (&checksum->context, (const void *)data, l); 00079 } 00080 00081 const char * 00082 g_checksum_get_string (GChecksum *checksum) 00083 { 00084 unsigned char digest[16]; 00085 static const char hex[16] = 00086 {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 00087 'a', 'b', 'c', 'd', 'e', 'f'}; 00088 int i; 00089 00090 if (!checksum) 00091 { 00092 errno = EINVAL; 00093 return NULL; 00094 } 00095 00096 MD5_Final (digest, &checksum->context); 00097 00098 for (i = 0; i < 16; i++) 00099 { 00100 checksum->hex_digest[2 * i] = hex[(digest[i] & 0xf0) >> 4]; 00101 checksum->hex_digest[2 * i + 1] = hex[digest[i] & 0x0f]; 00102 } 00103 checksum->hex_digest[32] = '\0'; 00104 00105 return checksum->hex_digest; 00106 } 00107 00108 #endif /* WITH_OPENSSL */