77#include "shared-bindings/hashlib/Hash.h"
88#include "shared-module/hashlib/__init__.h"
99
10+ #include "mbedtls/version.h"
11+
12+ #if MBEDTLS_VERSION_MAJOR >= 4
13+
1014#include "psa/crypto.h"
1115
1216void common_hal_hashlib_hash_update (hashlib_hash_obj_t * self , const uint8_t * data , size_t datalen ) {
@@ -27,3 +31,47 @@ void common_hal_hashlib_hash_digest(hashlib_hash_obj_t *self, uint8_t *data, siz
2731size_t common_hal_hashlib_hash_get_digest_size (hashlib_hash_obj_t * self ) {
2832 return PSA_HASH_LENGTH (self -> hash_alg );
2933}
34+
35+ #else
36+
37+ #include "mbedtls/ssl.h"
38+
39+ void common_hal_hashlib_hash_update (hashlib_hash_obj_t * self , const uint8_t * data , size_t datalen ) {
40+ if (self -> hash_type == MBEDTLS_SSL_HASH_SHA1 ) {
41+ mbedtls_sha1_update_ret (& self -> sha1 , data , datalen );
42+ return ;
43+ } else if (self -> hash_type == MBEDTLS_SSL_HASH_SHA256 ) {
44+ mbedtls_sha256_update_ret (& self -> sha256 , data , datalen );
45+ return ;
46+ }
47+ }
48+
49+ void common_hal_hashlib_hash_digest (hashlib_hash_obj_t * self , uint8_t * data , size_t datalen ) {
50+ if (datalen < common_hal_hashlib_hash_get_digest_size (self )) {
51+ return ;
52+ }
53+ if (self -> hash_type == MBEDTLS_SSL_HASH_SHA1 ) {
54+ // We copy the sha1 state so we can continue to update if needed or get
55+ // the digest a second time.
56+ mbedtls_sha1_context copy ;
57+ mbedtls_sha1_clone (& copy , & self -> sha1 );
58+ mbedtls_sha1_finish_ret (& self -> sha1 , data );
59+ mbedtls_sha1_clone (& self -> sha1 , & copy );
60+ } else if (self -> hash_type == MBEDTLS_SSL_HASH_SHA256 ) {
61+ mbedtls_sha256_context copy ;
62+ mbedtls_sha256_clone (& copy , & self -> sha256 );
63+ mbedtls_sha256_finish_ret (& self -> sha256 , data );
64+ mbedtls_sha256_clone (& self -> sha256 , & copy );
65+ }
66+ }
67+
68+ size_t common_hal_hashlib_hash_get_digest_size (hashlib_hash_obj_t * self ) {
69+ if (self -> hash_type == MBEDTLS_SSL_HASH_SHA1 ) {
70+ return 20 ;
71+ } else if (self -> hash_type == MBEDTLS_SSL_HASH_SHA256 ) {
72+ return 32 ;
73+ }
74+ return 0 ;
75+ }
76+
77+ #endif
0 commit comments