Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Check digest function to prevent error on OTP Generation (#170)
## Summary This pull request introduces a validation check in the `init` and `generate_otp` functions to prevent errors caused by incompatible digest functions and inadequate digest sizes. The changes aim to improve the stability and reliability of OTP generation. While the `RFC4226` states that the base function is `sha1`, the existing code will allow user to use other hash functions such as `MD5` and `SHAKE-128` due to their availability in the hashlib. ## Changes Made ### Digest Function Validation Added checks to disallow the use of `hashlib.md5` and `hashlib.shake_128` as digest functions in the `__init__` function of `otp.py`, `hotp.py`, and `totp.py`. These functions are not suitable for OTP generation due to their shorter hash sizes. ### Digest Size Check Implemented a check to ensure that the digest size is not lower than `18 bytes`. This prevents an `IndexError` that could occur when the last hash byte is `0xF`, causing the `generate_otp` function to set the offset to `15`. The subsequent operation would attempt to access `hmac_hash[offset + 1]` and so on, leading to an out-of-bounds error for `md5` and `shake128` due to their shorter digest lengths. ## Impact - Prevents potential errors and crashes during OTP generation by ensuring only suitable digest functions and sizes are used. - Improves overall code robustness by validating inputs before proceeding with OTP generation. ## Testing - Tested that `hashlib.md5` and `hashlib.shake128` are correctly rejected as digest functions on `__init__`. - Tested the digest size check to ensure that digest lengths below 18 bytes trigger the appropriate error handling on `generate_otp`. - Added `DigestFunctionTest` unit test as a negative test case where it will trigger an error if the selected digest function is `md5` or `shake_128`.
- Loading branch information