Skip to content

Commit 81e3046

Browse files
committed
simplify digest computation
1 parent 5d8c093 commit 81e3046

1 file changed

Lines changed: 14 additions & 18 deletions

File tree

Modules/md5module.c

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
#include "Python.h"
2424
#include "hashlib.h"
25+
#include "pycore_strhex.h" // _Py_strhex()
2526

2627
/*[clinic input]
2728
module _md5
@@ -126,6 +127,14 @@ MD5Type_copy_impl(MD5object *self, PyTypeObject *cls)
126127
return (PyObject *)newobj;
127128
}
128129

130+
static void
131+
md5_digest_compute_cond_lock(MD5object *self, uint8_t *digest)
132+
{
133+
ENTER_HASHLIB(self);
134+
Hacl_Hash_MD5_digest(self->hash_state, digest);
135+
LEAVE_HASHLIB(self);
136+
}
137+
129138
/*[clinic input]
130139
MD5Type.digest
131140
@@ -136,10 +145,8 @@ static PyObject *
136145
MD5Type_digest_impl(MD5object *self)
137146
/*[clinic end generated code: output=eb691dc4190a07ec input=bc0c4397c2994be6]*/
138147
{
139-
unsigned char digest[MD5_DIGESTSIZE];
140-
ENTER_HASHLIB(self);
141-
Hacl_Hash_MD5_digest(self->hash_state, digest);
142-
LEAVE_HASHLIB(self);
148+
uint8_t digest[MD5_DIGESTSIZE];
149+
md5_digest_compute_cond_lock(self, digest);
143150
return PyBytes_FromStringAndSize((const char *)digest, MD5_DIGESTSIZE);
144151
}
145152

@@ -153,20 +160,9 @@ static PyObject *
153160
MD5Type_hexdigest_impl(MD5object *self)
154161
/*[clinic end generated code: output=17badced1f3ac932 input=b60b19de644798dd]*/
155162
{
156-
unsigned char digest[MD5_DIGESTSIZE];
157-
ENTER_HASHLIB(self);
158-
Hacl_Hash_MD5_digest(self->hash_state, digest);
159-
LEAVE_HASHLIB(self);
160-
161-
const char *hexdigits = "0123456789abcdef";
162-
char digest_hex[MD5_DIGESTSIZE * 2];
163-
char *str = digest_hex;
164-
for (size_t i=0; i < MD5_DIGESTSIZE; i++) {
165-
unsigned char byte = digest[i];
166-
*str++ = hexdigits[byte >> 4];
167-
*str++ = hexdigits[byte & 0x0f];
168-
}
169-
return PyUnicode_FromStringAndSize(digest_hex, sizeof(digest_hex));
163+
uint8_t digest[MD5_DIGESTSIZE];
164+
md5_digest_compute_cond_lock(self, digest);
165+
return _Py_strhex((const char *)digest, MD5_DIGESTSIZE);
170166
}
171167

172168
static void

0 commit comments

Comments
 (0)