compare_digest function is used to compare two strings in a manner which is cryptographically secure. It return True if strings a and b are equal, otherwise False, in such a way as to reduce the risk of timing attacks. Timing attack is a side-channel attack in which the attacker attempts to compromise a cryptosystem by analyzing the time taken to execute cryptographic algorithms. Hence to prevent this type of attack in production compare_digest function is used, which does not linearly compares two strings but instead compare their characters randomly.
compare_digest function is a part of hmac module from where it is imported into secrets module. This function uses an approach designed to prevent timing analysis by avoiding content-based short circuiting behaviour, making it appropriate for cryptography. a and b must both be of the same type: either str or a bytes-like object. If a and b are of different lengths, or if an error occurs, a timing attack could theoretically reveal information about the types and lengths of a and b%u2014but not their values.
Syntax
secrets.
compare_digest
(a, b)
Parameters
a, b : Strings to be compared.
Sample Program
#importing secrets module
import secrets
def printEquality(result):
if(result):
print("Passwords Match")
else:
print("Passwords Donot Match")
password1 = "deekshant123"
password2 = "deekshant223"
result = secrets.compare_digest(password1,password2)
printEquality(result)
password1 = "deekshant123"
password2 = "gibberisj"
result = secrets.compare_digest(password1,password2)
printEquality(result)
password1 = "deekshant123"
password2 = "deekshant123"
result = secrets.compare_digest(password1,password2)
printEquality(result)
Output
Passwords Donot Match
Passwords Donot Match
Passwords Match
Comments