3636
3737#if MICROPY_PY_UHASHLIB
3838
39+ #include "crypto-algorithms/sha256.h"
40+
3941typedef struct _mp_obj_hash_t {
4042 mp_obj_base_t base ;
4143 char state [0 ];
@@ -45,26 +47,41 @@ STATIC mp_obj_t hash_update(mp_obj_t self_in, mp_obj_t arg);
4547
4648STATIC mp_obj_t hash_make_new (mp_obj_t type_in , mp_uint_t n_args , mp_uint_t n_kw , const mp_obj_t * args ) {
4749 mp_arg_check_num (n_args , n_kw , 0 , 1 , false);
48- mp_obj_hash_t * o = m_new_obj_var (mp_obj_hash_t , char , 0 );
50+ mp_obj_hash_t * o = m_new_obj_var (mp_obj_hash_t , char , sizeof ( SHA256_CTX ) );
4951 o -> base .type = type_in ;
52+ sha256_init ((SHA256_CTX * )o -> state );
5053 if (n_args == 1 ) {
5154 hash_update (o , args [0 ]);
5255 }
5356 return o ;
5457}
5558
5659STATIC mp_obj_t hash_update (mp_obj_t self_in , mp_obj_t arg ) {
60+ mp_obj_hash_t * self = self_in ;
61+ mp_buffer_info_t bufinfo ;
62+ mp_get_buffer_raise (arg , & bufinfo , MP_BUFFER_READ );
63+ sha256_update ((SHA256_CTX * )self -> state , bufinfo .buf , bufinfo .len );
5764 return mp_const_none ;
5865}
5966MP_DEFINE_CONST_FUN_OBJ_2 (hash_update_obj , hash_update );
6067
6168STATIC mp_obj_t hash_digest (mp_obj_t self_in ) {
62- return mp_obj_new_bytes ((const byte * )"\0\0\0\0" , 4 );
69+ mp_obj_hash_t * self = self_in ;
70+ byte * hash ;
71+ mp_obj_t o = mp_obj_str_builder_start (& mp_type_bytes , SHA256_BLOCK_SIZE , & hash );
72+ sha256_final ((SHA256_CTX * )self -> state , hash );
73+ return mp_obj_str_builder_end (o );
6374}
6475MP_DEFINE_CONST_FUN_OBJ_1 (hash_digest_obj , hash_digest );
6576
6677STATIC mp_obj_t hash_hexdigest (mp_obj_t self_in ) {
67- return mp_obj_new_str ("00000000" , 8 , false);
78+ mp_not_implemented ("" );
79+ #if 0
80+ mp_obj_hash_t * self = self_in ;
81+ byte hash [SHA256_BLOCK_SIZE ];
82+ sha256_final ((SHA256_CTX * )self -> state , hash );
83+ return mp_obj_new_str ((char * )hash , SHA256_BLOCK_SIZE , false);
84+ #endif
6885}
6986MP_DEFINE_CONST_FUN_OBJ_1 (hash_hexdigest_obj , hash_hexdigest );
7087
@@ -105,4 +122,6 @@ const mp_obj_module_t mp_module_uhashlib = {
105122 .globals = (mp_obj_dict_t * )& mp_module_hashlib_globals ,
106123};
107124
125+ #include "crypto-algorithms/sha256.c"
126+
108127#endif //MICROPY_PY_UHASHLIB
0 commit comments