Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 74cca70

Browse files
committed
Now that it's possible, avoid timing attacks in the crypt module examples)
1 parent 2246aa8 commit 74cca70

2 files changed

Lines changed: 8 additions & 3 deletions

File tree

Doc/library/crypt.rst

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,11 +121,14 @@ The :mod:`crypt` module defines the following functions:
121121
Examples
122122
--------
123123

124-
A simple example illustrating typical use::
124+
A simple example illustrating typical use (a constant-time comparison
125+
operation is needed to limit exposure to timing attacks.
126+
:func:`hmac.compare_digest` is suitable for this purpose)::
125127

126128
import pwd
127129
import crypt
128130
import getpass
131+
from hmac import compare_digest as compare_hash
129132

130133
def login():
131134
username = input('Python login: ')
@@ -134,15 +137,16 @@ A simple example illustrating typical use::
134137
if cryptedpasswd == 'x' or cryptedpasswd == '*':
135138
raise ValueError('no support for shadow passwords')
136139
cleartext = getpass.getpass()
137-
return crypt.crypt(cleartext, cryptedpasswd) == cryptedpasswd
140+
return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd)
138141
else:
139142
return True
140143

141144
To generate a hash of a password using the strongest available method and
142145
check it against the original::
143146

144147
import crypt
148+
from hmac import compare_digest as compare_hash
145149

146150
hashed = crypt.crypt(plaintext)
147-
if hashed != crypt.crypt(plaintext, hashed):
151+
if not compare_hash(hashed, crypt.crypt(plaintext, hashed)):
148152
raise ValueError("hashed version doesn't validate against original")

Doc/library/crypto.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ Cryptographic Services
88

99
The modules described in this chapter implement various algorithms of a
1010
cryptographic nature. They are available at the discretion of the installation.
11+
On Unix systems, the :mod:`crypt` module may also be available.
1112
Here's an overview:
1213

1314

0 commit comments

Comments
 (0)