f0b0ff
--- Python-3.4.0a4/Lib/hashlib.py.hashlib-fips	2013-11-07 13:29:43.046881440 +0100
f0b0ff
+++ Python-3.4.0a4/Lib/hashlib.py	2013-11-07 13:42:04.438486289 +0100
f0b0ff
@@ -23,6 +23,16 @@
b8f92b
 Choose your hash function wisely.  Some have known collision weaknesses.
b8f92b
 sha384 and sha512 will be slow on 32 bit platforms.
b8f92b
 
b8f92b
+If the underlying implementation supports "FIPS mode", and this is enabled, it
b8f92b
+may restrict the available hashes to only those that are compliant with FIPS
b8f92b
+regulations.  For example, it may deny the use of MD5, on the grounds that this
b8f92b
+is not secure for uses such as authentication, system integrity checking, or
b8f92b
+digital signatures.   If you need to use such a hash for non-security purposes
b8f92b
+(such as indexing into a data structure for speed), you can override the keyword
b8f92b
+argument "usedforsecurity" from True to False to signify that your code is not
b8f92b
+relying on the hash for security purposes, and this will allow the hash to be
b8f92b
+usable even in FIPS mode.
b8f92b
+
b8f92b
 Hash objects have these methods:
b8f92b
  - update(arg): Update the hash object with the bytes in arg. Repeated calls
b8f92b
                 are equivalent to a single call with the concatenation of all
f0b0ff
@@ -64,6 +74,19 @@
f0b0ff
                                 'algorithms_available', 'pbkdf2_hmac')
f0b0ff
 
f0b0ff
 
f0b0ff
+import functools
f0b0ff
+def __ignore_usedforsecurity(func):
f0b0ff
+    """Used for sha3_* functions. Until OpenSSL implements them, we want
f0b0ff
+    to use them from Python _sha3 module, but we want them to accept
f0b0ff
+    usedforsecurity argument too."""
f0b0ff
+    # TODO: remove this function when OpenSSL implements sha3
f0b0ff
+    @functools.wraps(func)
f0b0ff
+    def inner(*args, **kwargs):
f0b0ff
+        if 'usedforsecurity' in kwargs:
f0b0ff
+            kwargs.pop('usedforsecurity')
f0b0ff
+        return func(*args, **kwargs)
f0b0ff
+    return inner
f0b0ff
+
f0b0ff
 def __get_builtin_constructor(name):
f0b0ff
     try:
f0b0ff
         if name in ('SHA1', 'sha1'):
f0b0ff
@@ -109,34 +132,41 @@
b8f92b
         f = getattr(_hashlib, 'openssl_' + name)
b8f92b
         # Allow the C module to raise ValueError.  The function will be
b8f92b
         # defined but the hash not actually available thanks to OpenSSL.
b8f92b
-        f()
b8f92b
+        # We pass "usedforsecurity=False" to disable FIPS-based restrictions:
b8f92b
+        # at this stage we're merely seeing if the function is callable,
b8f92b
+        # rather than using it for actual work.
b8f92b
+        f(usedforsecurity=False)
b8f92b
         # Use the C function directly (very fast)
b8f92b
         return f
b8f92b
     except (AttributeError, ValueError):
f0b0ff
+        # TODO: We want to just raise here when OpenSSL implements sha3
f0b0ff
+        # because we want to make sure that Fedora uses everything from OpenSSL
f0b0ff
         return __get_builtin_constructor(name)
b8f92b
 
b8f92b
 
b8f92b
-def __py_new(name, data=b''):
b8f92b
-    """new(name, data=b'') - Return a new hashing object using the named algorithm;
b8f92b
-    optionally initialized with data (which must be bytes).
f0b0ff
+def __py_new(name, data=b'', usedforsecurity=True):
f0b0ff
+    """new(name, data=b'', usedforsecurity=True) - Return a new hashing object using
f0b0ff
+    the named algorithm; optionally initialized with data (which must be bytes).
b8f92b
+    The 'usedforsecurity' keyword argument does nothing, and is for compatibilty
b8f92b
+    with the OpenSSL implementation
b8f92b
     """
b8f92b
     return __get_builtin_constructor(name)(data)
b8f92b
 
b8f92b
 
b8f92b
-def __hash_new(name, data=b''):
b8f92b
-    """new(name, data=b'') - Return a new hashing object using the named algorithm;
b8f92b
-    optionally initialized with data (which must be bytes).
b8f92b
+def __hash_new(name, data=b'', usedforsecurity=True):
b8f92b
+    """new(name, data=b'', usedforsecurity=True) - Return a new hashing object using
b8f92b
+    the named algorithm; optionally initialized with data (which must be bytes).
b8f92b
+    
b8f92b
+    Override 'usedforsecurity' to False when using for non-security purposes in
b8f92b
+    a FIPS environment
b8f92b
     """
b8f92b
     try:
b8f92b
-        return _hashlib.new(name, data)
b8f92b
+        return _hashlib.new(name, data, usedforsecurity)
b8f92b
     except ValueError:
b8f92b
-        # If the _hashlib module (OpenSSL) doesn't support the named
b8f92b
-        # hash, try using our builtin implementations.
b8f92b
-        # This allows for SHA224/256 and SHA384/512 support even though
b8f92b
-        # the OpenSSL library prior to 0.9.8 doesn't provide them.
f0b0ff
+        # TODO: We want to just raise here when OpenSSL implements sha3
f0b0ff
+        # because we want to make sure that Fedora uses everything from OpenSSL
f0b0ff
         return __get_builtin_constructor(name)(data)
b8f92b
 
f0b0ff
-
b8f92b
 try:
b8f92b
     import _hashlib
f0b0ff
     new = __hash_new
f0b0ff
@@ -216,7 +246,10 @@
f0b0ff
     # try them all, some may not work due to the OpenSSL
f0b0ff
     # version not supporting that algorithm.
f0b0ff
     try:
f0b0ff
-        globals()[__func_name] = __get_hash(__func_name)
f0b0ff
+        func = __get_hash(__func_name)
f0b0ff
+        if 'sha3_' in __func_name:
f0b0ff
+            func = __ignore_usedforsecurity(func)
f0b0ff
+        globals()[__func_name] = func
f0b0ff
     except ValueError:
f0b0ff
         import logging
f0b0ff
         logging.exception('code for hash %s was not found.', __func_name)
f0b0ff
@@ -224,3 +257,4 @@
f0b0ff
 # Cleanup locals()
f0b0ff
 del __always_supported, __func_name, __get_hash
f0b0ff
 del __py_new, __hash_new, __get_openssl_constructor
f0b0ff
+del __ignore_usedforsecurity
f0b0ff
--- Python-3.4.0a4/Lib/test/test_hashlib.py.hashlib-fips	2013-11-07 13:43:08.763454594 +0100
f0b0ff
+++ Python-3.4.0a4/Lib/test/test_hashlib.py	2013-11-07 13:55:23.233038101 +0100
f0b0ff
@@ -26,6 +26,20 @@
f5250e
 c_hashlib = import_fresh_module('hashlib', fresh=['_hashlib'])
f5250e
 py_hashlib = import_fresh_module('hashlib', blocked=['_hashlib'])
b8f92b
 
b8f92b
+def openssl_enforces_fips():
b8f92b
+    # Use the "openssl" command (if present) to try to determine if the local
b8f92b
+    # OpenSSL is configured to enforce FIPS
b8f92b
+    from subprocess import Popen, PIPE
b8f92b
+    try:
b8f92b
+        p = Popen(['openssl', 'md5'],
b8f92b
+                  stdin=PIPE, stdout=PIPE, stderr=PIPE)
b8f92b
+    except OSError:
b8f92b
+        # "openssl" command not found
b8f92b
+        return False
b8f92b
+    stdout, stderr = p.communicate(input=b'abc')
b8f92b
+    return b'unknown cipher' in stderr
b8f92b
+OPENSSL_ENFORCES_FIPS = openssl_enforces_fips()
f5250e
+
b8f92b
 def hexstr(s):
b8f92b
     assert isinstance(s, bytes), repr(s)
f5250e
     h = "0123456789abcdef"
f0b0ff
@@ -34,6 +48,16 @@
b8f92b
         r += h[(i >> 4) & 0xF] + h[i & 0xF]
b8f92b
     return r
b8f92b
 
b8f92b
+# hashlib and _hashlib-based functions support a "usedforsecurity" keyword
b8f92b
+# argument, and FIPS mode requires that it be used overridden with a False
b8f92b
+# value for these selftests to work.  Other cryptographic code within Python
b8f92b
+# doesn't support this keyword.
b8f92b
+# Modify a function to one in which "usedforsecurity=False" is added to the
b8f92b
+# keyword arguments:
b8f92b
+def suppress_fips(f):
b8f92b
+    def g(*args, **kwargs):
b8f92b
+        return f(*args, usedforsecurity=False, **kwargs)
b8f92b
+    return g
b8f92b
 
b8f92b
 class HashLibTestCase(unittest.TestCase):
b8f92b
     supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
f0b0ff
@@ -66,11 +90,11 @@
b8f92b
         # For each algorithm, test the direct constructor and the use
b8f92b
         # of hashlib.new given the algorithm name.
b8f92b
         for algorithm, constructors in self.constructors_to_test.items():
b8f92b
-            constructors.add(getattr(hashlib, algorithm))
b8f92b
+            constructors.add(suppress_fips(getattr(hashlib, algorithm)))
b8f92b
             def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
b8f92b
                 if data is None:
b8f92b
-                    return hashlib.new(_alg)
b8f92b
-                return hashlib.new(_alg, data)
b8f92b
+                    return suppress_fips(hashlib.new)(_alg)
b8f92b
+                return suppress_fips(hashlib.new)(_alg, data)
b8f92b
             constructors.add(_test_algorithm_via_hashlib_new)
b8f92b
 
b8f92b
         _hashlib = self._conditional_import_module('_hashlib')
f0b0ff
@@ -82,22 +106,9 @@
b8f92b
             for algorithm, constructors in self.constructors_to_test.items():
b8f92b
                 constructor = getattr(_hashlib, 'openssl_'+algorithm, None)
b8f92b
                 if constructor:
b8f92b
-                    constructors.add(constructor)
f0b0ff
+                    constructors.add(suppress_fips(constructor))
f0b0ff
 
b8f92b
-        _md5 = self._conditional_import_module('_md5')
b8f92b
-        if _md5:
b8f92b
-            self.constructors_to_test['md5'].add(_md5.md5)
b8f92b
-        _sha1 = self._conditional_import_module('_sha1')
b8f92b
-        if _sha1:
b8f92b
-            self.constructors_to_test['sha1'].add(_sha1.sha1)
b8f92b
-        _sha256 = self._conditional_import_module('_sha256')
b8f92b
-        if _sha256:
b8f92b
-            self.constructors_to_test['sha224'].add(_sha256.sha224)
b8f92b
-            self.constructors_to_test['sha256'].add(_sha256.sha256)
b8f92b
-        _sha512 = self._conditional_import_module('_sha512')
b8f92b
-        if _sha512:
b8f92b
-            self.constructors_to_test['sha384'].add(_sha512.sha384)
b8f92b
-            self.constructors_to_test['sha512'].add(_sha512.sha512)
f0b0ff
+        # TODO: remove this after sha3 is available through OpenSSL
f5250e
         _sha3 = self._conditional_import_module('_sha3')
f5250e
         if _sha3:
f5250e
             self.constructors_to_test['sha3_224'].add(_sha3.sha3_224)
f0b0ff
@@ -547,6 +558,65 @@
b8f92b
 
b8f92b
         self.assertEqual(expected_hash, hasher.hexdigest())
b8f92b
 
b8f92b
+    def test_issue9146(self):
b8f92b
+        # Ensure that various ways to use "MD5" from "hashlib" don't segfault:
b8f92b
+        m = hashlib.md5(usedforsecurity=False)
b8f92b
+        m.update(b'abc\n')
b8f92b
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b
+        
b8f92b
+        m = hashlib.new('md5', usedforsecurity=False)
b8f92b
+        m.update(b'abc\n')
b8f92b
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b
+        
b8f92b
+        m = hashlib.md5(b'abc\n', usedforsecurity=False)
b8f92b
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b
+        
b8f92b
+        m = hashlib.new('md5', b'abc\n', usedforsecurity=False)
b8f92b
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b
+
b8f92b
+    @unittest.skipUnless(OPENSSL_ENFORCES_FIPS,
b8f92b
+                         'FIPS enforcement required for this test.')
b8f92b
+    def test_hashlib_fips_mode(self):        
b8f92b
+        # Ensure that we raise a ValueError on vanilla attempts to use MD5
b8f92b
+        # in hashlib in a FIPS-enforced setting:
b8f92b
+        with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
b8f92b
+            m = hashlib.md5()
b8f92b
+            
b8f92b
+        if not self._conditional_import_module('_md5'):
b8f92b
+            with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
b8f92b
+                m = hashlib.new('md5')
b8f92b
+
b8f92b
+    @unittest.skipUnless(OPENSSL_ENFORCES_FIPS,
b8f92b
+                         'FIPS enforcement required for this test.')
b8f92b
+    def test_hashopenssl_fips_mode(self):
b8f92b
+        # Verify the _hashlib module's handling of md5:
b8f92b
+        _hashlib = self._conditional_import_module('_hashlib')
b8f92b
+        if _hashlib:
b8f92b
+            assert hasattr(_hashlib, 'openssl_md5')
b8f92b
+
b8f92b
+            # Ensure that _hashlib raises a ValueError on vanilla attempts to
b8f92b
+            # use MD5 in a FIPS-enforced setting:
b8f92b
+            with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
b8f92b
+                m = _hashlib.openssl_md5()
b8f92b
+            with self.assertRaisesRegexp(ValueError, '.*unknown cipher'):
b8f92b
+                m = _hashlib.new('md5')
b8f92b
+
b8f92b
+            # Ensure that in such a setting we can whitelist a callsite with
b8f92b
+            # usedforsecurity=False and have it succeed:
b8f92b
+            m = _hashlib.openssl_md5(usedforsecurity=False)
b8f92b
+            m.update(b'abc\n')
b8f92b
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b
+        
b8f92b
+            m = _hashlib.new('md5', usedforsecurity=False)
b8f92b
+            m.update(b'abc\n')
b8f92b
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
f0b0ff
+       
b8f92b
+            m = _hashlib.openssl_md5(b'abc\n', usedforsecurity=False)
b8f92b
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b
+        
b8f92b
+            m = _hashlib.new('md5', b'abc\n', usedforsecurity=False)
b8f92b
+            self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
b8f92b
+
b8f92b
 
f0b0ff
 class KDFTests(unittest.TestCase):
f0b0ff
 
f0b0ff
@@ -628,6 +698,7 @@
f0b0ff
         with self.assertRaisesRegex(ValueError, 'unsupported hash type'):
f0b0ff
             pbkdf2('unknown', b'pass', b'salt', 1)
f0b0ff
 
f0b0ff
+    @unittest.skip('skipped on Fedora, as we always use OpenSSL pbkdf2_hmac')
f0b0ff
     def test_pbkdf2_hmac_py(self):
f0b0ff
         self._test_pbkdf2_hmac(py_hashlib.pbkdf2_hmac)
f0b0ff
 
f0b0ff
--- Python-3.4.0a4/Modules/_hashopenssl.c.hashlib-fips	2013-11-07 13:55:47.466025086 +0100
f0b0ff
+++ Python-3.4.0a4/Modules/_hashopenssl.c	2013-11-07 14:14:32.745272791 +0100
f0b0ff
@@ -19,6 +19,8 @@
f0b0ff
 
b8f92b
 
b8f92b
 /* EVP is the preferred interface to hashing in OpenSSL */
b8f92b
+#include <openssl/ssl.h>
b8f92b
+#include <openssl/err.h>
b8f92b
 #include <openssl/evp.h>
f0b0ff
 #include <openssl/hmac.h>
b8f92b
 /* We use the object interface to discover what hashes OpenSSL supports. */
f0b0ff
@@ -48,11 +50,19 @@
b8f92b
 
b8f92b
 static PyTypeObject EVPtype;
b8f92b
 
b8f92b
+/* Struct to hold all the cached information we need on a specific algorithm.
b8f92b
+   We have one of these per algorithm */
b8f92b
+typedef struct {
b8f92b
+    PyObject *name_obj;
b8f92b
+    EVP_MD_CTX ctxs[2];
b8f92b
+    /* ctx_ptrs will point to ctxs unless an error occurred, when it will
b8f92b
+       be NULL: */
b8f92b
+    EVP_MD_CTX *ctx_ptrs[2];
b8f92b
+    PyObject *error_msgs[2];
b8f92b
+} EVPCachedInfo;
b8f92b
 
b8f92b
-#define DEFINE_CONSTS_FOR_NEW(Name)  \
58f477
-    static PyObject *CONST_ ## Name ## _name_obj = NULL; \
b8f92b
-    static EVP_MD_CTX CONST_new_ ## Name ## _ctx; \
b8f92b
-    static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
b8f92b
+#define DEFINE_CONSTS_FOR_NEW(Name) \
b8f92b
+    static EVPCachedInfo cached_info_ ##Name;
b8f92b
 
b8f92b
 DEFINE_CONSTS_FOR_NEW(md5)
b8f92b
 DEFINE_CONSTS_FOR_NEW(sha1)
f0b0ff
@@ -125,6 +135,48 @@
b8f92b
     }
b8f92b
 }
b8f92b
 
b8f92b
+static void
b8f92b
+mc_ctx_init(EVP_MD_CTX *ctx, int usedforsecurity)
b8f92b
+{
b8f92b
+    EVP_MD_CTX_init(ctx);
b8f92b
+
b8f92b
+    /*
b8f92b
+      If the user has declared that this digest is being used in a
b8f92b
+      non-security role (e.g. indexing into a data structure), set
b8f92b
+      the exception flag for openssl to allow it
b8f92b
+    */
b8f92b
+    if (!usedforsecurity) {
b8f92b
+#ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW
b8f92b
+        EVP_MD_CTX_set_flags(ctx,
b8f92b
+                             EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
b8f92b
+#endif
b8f92b
+    }
b8f92b
+}
b8f92b
+
b8f92b
+/* Get an error msg for the last error as a PyObject */
b8f92b
+static PyObject *
b8f92b
+error_msg_for_last_error(void)
b8f92b
+{
b8f92b
+    char *errstr;
b8f92b
+
b8f92b
+    errstr = ERR_error_string(ERR_peek_last_error(), NULL);
b8f92b
+    ERR_clear_error();
b8f92b
+
b8f92b
+    return PyUnicode_FromString(errstr); /* Can be NULL */
b8f92b
+}
b8f92b
+
b8f92b
+static void
b8f92b
+set_evp_exception(void)
b8f92b
+{
b8f92b
+    char *errstr;
b8f92b
+
b8f92b
+    errstr = ERR_error_string(ERR_peek_last_error(), NULL);
b8f92b
+    ERR_clear_error();
b8f92b
+
b8f92b
+    PyErr_SetString(PyExc_ValueError, errstr);
b8f92b
+}
b8f92b
+
b8f92b
+
b8f92b
 /* Internal methods for a hash object */
b8f92b
 
b8f92b
 static void
f0b0ff
@@ -309,15 +361,16 @@
b8f92b
 static int
b8f92b
 EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
b8f92b
 {
b8f92b
-    static char *kwlist[] = {"name", "string", NULL};
b8f92b
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
b8f92b
     PyObject *name_obj = NULL;
b8f92b
     PyObject *data_obj = NULL;
b8f92b
+    int usedforsecurity = 1;
b8f92b
     Py_buffer view;
b8f92b
     char *nameStr;
b8f92b
     const EVP_MD *digest;
b8f92b
 
b8f92b
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:HASH", kwlist,
b8f92b
-                                     &name_obj, &data_obj)) {
b8f92b
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oi:HASH", kwlist,
b8f92b
+                                     &name_obj, &data_obj, &usedforsecurity)) {
b8f92b
         return -1;
b8f92b
     }
b8f92b
 
f0b0ff
@@ -338,7 +391,12 @@
b8f92b
             PyBuffer_Release(&view);
b8f92b
         return -1;
b8f92b
     }
b8f92b
-    EVP_DigestInit(&self->ctx, digest);
b8f92b
+    mc_ctx_init(&self->ctx, usedforsecurity);
b8f92b
+    if (!EVP_DigestInit_ex(&self->ctx, digest, NULL)) {
b8f92b
+        set_evp_exception();
b8f92b
+        PyBuffer_Release(&view);
b8f92b
+        return -1;
b8f92b
+    }
b8f92b
 
b8f92b
     self->name = name_obj;
b8f92b
     Py_INCREF(self->name);
f0b0ff
@@ -422,7 +480,8 @@
b8f92b
 static PyObject *
b8f92b
 EVPnew(PyObject *name_obj,
b8f92b
        const EVP_MD *digest, const EVP_MD_CTX *initial_ctx,
b8f92b
-       const unsigned char *cp, Py_ssize_t len)
b8f92b
+       const unsigned char *cp, Py_ssize_t len,
b8f92b
+       int usedforsecurity)
b8f92b
 {
b8f92b
     EVPobject *self;
b8f92b
 
f0b0ff
@@ -437,7 +495,12 @@
b8f92b
     if (initial_ctx) {
b8f92b
         EVP_MD_CTX_copy(&self->ctx, initial_ctx);
b8f92b
     } else {
b8f92b
-        EVP_DigestInit(&self->ctx, digest);
b8f92b
+        mc_ctx_init(&self->ctx, usedforsecurity);
b8f92b
+        if (!EVP_DigestInit_ex(&self->ctx, digest, NULL)) {
b8f92b
+            set_evp_exception();
b8f92b
+            Py_DECREF(self);
b8f92b
+            return NULL;
b8f92b
+        }
b8f92b
     }
b8f92b
 
b8f92b
     if (cp && len) {
f0b0ff
@@ -461,21 +524,29 @@
b8f92b
 An optional string argument may be provided and will be\n\
b8f92b
 automatically hashed.\n\
b8f92b
 \n\
b8f92b
-The MD5 and SHA1 algorithms are always supported.\n");
b8f92b
+The MD5 and SHA1 algorithms are always supported.\n\
b8f92b
+\n\
b8f92b
+An optional \"usedforsecurity=True\" keyword argument is provided for use in\n\
b8f92b
+environments that enforce FIPS-based restrictions.  Some implementations of\n\
b8f92b
+OpenSSL can be configured to prevent the usage of non-secure algorithms (such\n\
b8f92b
+as MD5).  If you have a non-security use for these algorithms (e.g. a hash\n\
b8f92b
+table), you can override this argument by marking the callsite as\n\
b8f92b
+\"usedforsecurity=False\".");
b8f92b
 
b8f92b
 static PyObject *
b8f92b
 EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
b8f92b
 {
b8f92b
-    static char *kwlist[] = {"name", "string", NULL};
b8f92b
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
b8f92b
     PyObject *name_obj = NULL;
b8f92b
     PyObject *data_obj = NULL;
b8f92b
+    int usedforsecurity = 1;
b8f92b
     Py_buffer view = { 0 };
b8f92b
     PyObject *ret_obj;
b8f92b
     char *name;
b8f92b
     const EVP_MD *digest;
b8f92b
 
b8f92b
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|O:new", kwlist,
b8f92b
-                                     &name_obj, &data_obj)) {
b8f92b
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|Oi:new", kwlist,
b8f92b
+                                     &name_obj, &data_obj, &usedforsecurity)) {
b8f92b
         return NULL;
b8f92b
     }
b8f92b
 
f0b0ff
@@ -489,7 +560,8 @@
b8f92b
 
b8f92b
     digest = EVP_get_digestbyname(name);
b8f92b
 
b8f92b
-    ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf, view.len);
b8f92b
+    ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf, view.len,
b8f92b
+                     usedforsecurity);
b8f92b
 
b8f92b
     if (data_obj)
b8f92b
         PyBuffer_Release(&view);
f0b0ff
@@ -744,57 +816,115 @@
b8f92b
 
b8f92b
 
b8f92b
 /*
b8f92b
- *  This macro generates constructor function definitions for specific
b8f92b
- *  hash algorithms.  These constructors are much faster than calling
b8f92b
- *  the generic one passing it a python string and are noticably
b8f92b
- *  faster than calling a python new() wrapper.  Thats important for
b8f92b
+ *  This macro and function generates a family of constructor function
b8f92b
+ *  definitions for specific hash algorithms.  These constructors are much
b8f92b
+ *  faster than calling the generic one passing it a python string and are
b8f92b
+ *  noticably faster than calling a python new() wrapper.  That's important for
b8f92b
  *  code that wants to make hashes of a bunch of small strings.
b8f92b
  */
b8f92b
 #define GEN_CONSTRUCTOR(NAME)  \
b8f92b
     static PyObject * \
b8f92b
-    EVP_new_ ## NAME (PyObject *self, PyObject *args) \
f0b0ff
+    EVP_new_ ## NAME (PyObject *self, PyObject *args, PyObject *kwdict)        \
b8f92b
     { \
b8f92b
-        PyObject *data_obj = NULL; \
b8f92b
-        Py_buffer view = { 0 }; \
b8f92b
-        PyObject *ret_obj; \
b8f92b
-     \
b8f92b
-        if (!PyArg_ParseTuple(args, "|O:" #NAME , &data_obj)) { \
b8f92b
-            return NULL; \
b8f92b
-        } \
b8f92b
-     \
b8f92b
-        if (data_obj) \
b8f92b
-            GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view); \
b8f92b
-     \
b8f92b
-        ret_obj = EVPnew( \
b8f92b
-                    CONST_ ## NAME ## _name_obj, \
b8f92b
-                    NULL, \
b8f92b
-                    CONST_new_ ## NAME ## _ctx_p, \
b8f92b
-                    (unsigned char*)view.buf, \
b8f92b
-                    view.len); \
b8f92b
-     \
b8f92b
-        if (data_obj) \
b8f92b
-            PyBuffer_Release(&view); \
b8f92b
-        return ret_obj; \
b8f92b
+       return implement_specific_EVP_new(self, args, kwdict,      \
b8f92b
+                                         "|Oi:" #NAME,            \
b8f92b
+                                         &cached_info_ ## NAME ); \
f0b0ff
+    }
f0b0ff
+
b8f92b
+static PyObject *
b8f92b
+implement_specific_EVP_new(PyObject *self, PyObject *args, PyObject *kwdict,
b8f92b
+                           const char *format,
b8f92b
+                           EVPCachedInfo *cached_info)
b8f92b
+{
b8f92b
+    static char *kwlist[] = {"string", "usedforsecurity", NULL}; 
b8f92b
+    PyObject *data_obj = NULL;
b8f92b
+    Py_buffer view = { 0 };
b8f92b
+    int usedforsecurity = 1;
b8f92b
+    int idx;
b8f92b
+    PyObject *ret_obj = NULL;
b8f92b
+
b8f92b
+    assert(cached_info);
b8f92b
+
b8f92b
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, format, kwlist,
b8f92b
+                                     &data_obj, &usedforsecurity)) {
b8f92b
+        return NULL;
b8f92b
+    }
b8f92b
+
b8f92b
+    if (data_obj)
b8f92b
+       GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
b8f92b
+
b8f92b
+    idx = usedforsecurity ? 1 : 0;
b8f92b
+
b8f92b
+    /*
b8f92b
+     * If an error occurred during creation of the global content, the ctx_ptr
b8f92b
+     * will be NULL, and the error_msg will hopefully be non-NULL:
b8f92b
+     */
b8f92b
+    if (cached_info->ctx_ptrs[idx]) {
b8f92b
+        /* We successfully initialized this context; copy it: */
b8f92b
+        ret_obj = EVPnew(cached_info->name_obj,
b8f92b
+                         NULL,
b8f92b
+                         cached_info->ctx_ptrs[idx],
b8f92b
+                         (unsigned char*)view.buf, view.len,
b8f92b
+                         usedforsecurity);
b8f92b
+    } else {
b8f92b
+        /* Some kind of error happened initializing the global context for
b8f92b
+           this (digest, usedforsecurity) pair.
b8f92b
+           Raise an exception with the saved error message: */
b8f92b
+        if (cached_info->error_msgs[idx]) {
b8f92b
+            PyErr_SetObject(PyExc_ValueError, cached_info->error_msgs[idx]);
b8f92b
+        } else {
b8f92b
+            PyErr_SetString(PyExc_ValueError, "Error initializing hash");
b8f92b
+        }
f0b0ff
     }
f0b0ff
 
b8f92b
+    if (data_obj)
b8f92b
+        PyBuffer_Release(&view);
b8f92b
+
b8f92b
+    return ret_obj;
b8f92b
+}
b8f92b
+
b8f92b
 /* a PyMethodDef structure for the constructor */
b8f92b
 #define CONSTRUCTOR_METH_DEF(NAME)  \
b8f92b
-    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, METH_VARARGS, \
b8f92b
+    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, \
b8f92b
+        METH_VARARGS|METH_KEYWORDS, \
b8f92b
         PyDoc_STR("Returns a " #NAME \
b8f92b
                   " hash object; optionally initialized with a string") \
b8f92b
     }
b8f92b
 
58f477
-/* used in the init function to setup a constructor: initialize OpenSSL
58f477
-   constructor constants if they haven't been initialized already.  */
b8f92b
-#define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do { \
58f477
-    if (CONST_ ## NAME ## _name_obj == NULL) { \
58f477
-        CONST_ ## NAME ## _name_obj = PyUnicode_FromString(#NAME); \
58f477
-        if (EVP_get_digestbyname(#NAME)) { \
58f477
-            CONST_new_ ## NAME ## _ctx_p = &CONST_new_ ## NAME ## _ctx; \
58f477
-            EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
58f477
-        } \
b8f92b
-    } \
b8f92b
+/*
b8f92b
+  Macro/function pair to set up the constructors.
f0b0ff
+
b8f92b
+  Try to initialize a context for each hash twice, once with
b8f92b
+  EVP_MD_CTX_FLAG_NON_FIPS_ALLOW and once without.
b8f92b
+  
b8f92b
+  Any that have errors during initialization will end up with a NULL ctx_ptrs
b8f92b
+  entry, and err_msgs will be set (unless we're very low on memory)
b8f92b
+*/
b8f92b
+#define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do {    \
b8f92b
+    init_constructor_constant(&cached_info_ ## NAME, #NAME); \
f0b0ff
 } while (0);
b8f92b
+static void
b8f92b
+init_constructor_constant(EVPCachedInfo *cached_info, const char *name)
b8f92b
+{
b8f92b
+    assert(cached_info);
b8f92b
+    cached_info->name_obj = PyUnicode_FromString(name);
b8f92b
+    if (EVP_get_digestbyname(name)) {
b8f92b
+        int i;
b8f92b
+        for (i=0; i<2; i++) {
b8f92b
+            mc_ctx_init(&cached_info->ctxs[i], i);
b8f92b
+            if (EVP_DigestInit_ex(&cached_info->ctxs[i],
b8f92b
+                                  EVP_get_digestbyname(name), NULL)) {
b8f92b
+                /* Success: */
b8f92b
+                cached_info->ctx_ptrs[i] = &cached_info->ctxs[i];
b8f92b
+            } else {
b8f92b
+                /* Failure: */
b8f92b
+              cached_info->ctx_ptrs[i] = NULL;
b8f92b
+              cached_info->error_msgs[i] = error_msg_for_last_error();
b8f92b
+            }
b8f92b
+        }
b8f92b
+    }
b8f92b
+}
f0b0ff
+
f0b0ff
 
b8f92b
 GEN_CONSTRUCTOR(md5)
b8f92b
 GEN_CONSTRUCTOR(sha1)
f0b0ff
@@ -845,12 +974,10 @@
b8f92b
 {
b8f92b
     PyObject *m, *openssl_md_meth_names;
b8f92b
 
b8f92b
-    OpenSSL_add_all_digests();
b8f92b
+    SSL_load_error_strings();
b8f92b
+    SSL_library_init();
b8f92b
 
b8f92b
-    /* TODO build EVP_functions openssl_* entries dynamically based
b8f92b
-     * on what hashes are supported rather than listing many
b8f92b
-     * but having some be unsupported.  Only init appropriate
b8f92b
-     * constants. */
b8f92b
+    OpenSSL_add_all_digests();
b8f92b
 
b8f92b
     Py_TYPE(&EVPtype) = &PyType_Type;
b8f92b
     if (PyType_Ready(&EVPtype) < 0)