Skip to content

Commit

Permalink
Support FIPS mode where possible
Browse files Browse the repository at this point in the history
Computer systems can be configured to operate in compliance with the U.S.
Federal Information Processing Standards. Such configuration restricts usage of
MD5 due to its cryptographic insecurity. Trying to use `hashlib.md5()` on a FIPS
system raises an exception:

```
ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS
```

In Python 3.9 and newer, using MD5 for non-cryptographic purposes is allowed by
passing `usedforsecurity=False`.
  • Loading branch information
khanfluence authored and nedbat committed Nov 24, 2023
1 parent 5eaf16d commit 9794d73
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions cogapp/cogapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"""

import copy
import functools
import getopt
import glob
import hashlib
Expand Down Expand Up @@ -57,6 +58,13 @@
-h Print this help.
"""

# Support FIPS mode where possible (Python >= 3.9). We don't use MD5 for security.
md5 = (
functools.partial(hashlib.md5, usedforsecurity=False)
if sys.version_info >= (3, 9)
else hashlib.md5
)

class CogError(Exception):
""" Any exception raised by Cog.
"""
Expand Down Expand Up @@ -446,7 +454,7 @@ def processFile(self, fIn, fOut, fname=None, globals=None):

self.cogmodule.inFile = sFileIn
self.cogmodule.outFile = sFileOut
self.cogmodulename = 'cog_' + hashlib.md5(sFileOut.encode()).hexdigest()
self.cogmodulename = 'cog_' + md5(sFileOut.encode()).hexdigest()
sys.modules[self.cogmodulename] = self.cogmodule
# if "import cog" explicitly done in code by user, note threading will cause clashes.
sys.modules['cog'] = self.cogmodule
Expand Down Expand Up @@ -536,7 +544,7 @@ def processFile(self, fIn, fOut, fname=None, globals=None):
# Eat all the lines in the output section. While reading past
# them, compute the md5 hash of the old output.
previous = ""
hasher = hashlib.md5()
hasher = md5()
while l and not self.isEndOutputLine(l):
if self.isBeginSpecLine(l):
raise CogError(
Expand Down Expand Up @@ -568,7 +576,7 @@ def processFile(self, fIn, fOut, fname=None, globals=None):

# Write the output of the spec to be the new output if we're
# supposed to generate code.
hasher = hashlib.md5()
hasher = md5()
if not self.options.bNoGenerate:
sFile = f"<cog {sFileIn}:{firstLineNum}>"
sGen = gen.evaluate(cog=self, globals=globals, fname=sFile)
Expand Down

0 comments on commit 9794d73

Please sign in to comment.