Bug 1181814 - Pick up FIPS-140 certification work done by Red Hat, r=kaie, emaldona
authorRobert Relyea <rrelyea@redhat.com>
Thu, 18 Feb 2016 07:44:58 -0800
changeset 11902 43e2d2e1cb741aca5c026de3ed72649e00c9fc2e
parent 11901 458ac5f53544f9228ca9dca0d9b87bd6228b0e54
child 11903 c2bd9431da866e25510f93210ef3155e175731c0
push id998
push useremaldona@redhat.com
push dateThu, 18 Feb 2016 15:57:30 +0000
reviewerskaie, emaldona
bugs1181814
Bug 1181814 - Pick up FIPS-140 certification work done by Red Hat, r=kaie, emaldona - Includes modifications submitted by kaie and emaldona, r=rrelyea
cmd/bltest/blapitest.c
cmd/fipstest/aes.sh
cmd/fipstest/aesgcm.sh
cmd/fipstest/dsa.sh
cmd/fipstest/ecdsa.sh
cmd/fipstest/hmac.sh
cmd/fipstest/rng.sh
cmd/fipstest/rsa.sh
cmd/fipstest/runtest.sh
cmd/fipstest/sha.sh
cmd/fipstest/tdea.sh
cmd/fipstest/tls.sh
cmd/fipstest/validate.sh
cmd/fipstest/validate1.sh
lib/freebl/Makefile
lib/freebl/blapii.h
lib/freebl/blname.c
lib/freebl/ctr.c
lib/freebl/ctr.h
lib/freebl/cts.c
lib/freebl/dh.c
lib/freebl/drbg.c
lib/freebl/ec.c
lib/freebl/fipsfreebl.c
lib/freebl/freebl_hash_vector.def
lib/freebl/gcm.c
lib/freebl/ldvector.c
lib/freebl/loader.c
lib/freebl/loader.h
lib/freebl/lowhash_vector.c
lib/freebl/manifest.mn
lib/freebl/mpi/mpprime.c
lib/freebl/nsslowhash.c
lib/freebl/pqg.c
lib/freebl/rijndael.c
lib/freebl/rijndael.h
lib/freebl/rsa.c
lib/freebl/shvfy.c
lib/freebl/stubs.c
lib/freebl/stubs.h
lib/softoken/Makefile
lib/softoken/fipstest.c
lib/softoken/fipstokn.c
lib/softoken/legacydb/lgdb.h
lib/softoken/legacydb/lgfips.c
lib/softoken/legacydb/lginit.c
lib/softoken/legacydb/manifest.mn
lib/softoken/lgglue.c
lib/softoken/lgglue.h
lib/softoken/pkcs11.c
lib/softoken/pkcs11c.c
lib/softoken/sdb.c
lib/softoken/sdb.h
lib/softoken/sftkdb.c
lib/softoken/softoken.h
lib/util/pkcs11t.h
tests/common/Makefile
--- a/cmd/bltest/blapitest.c
+++ b/cmd/bltest/blapitest.c
@@ -3744,17 +3744,17 @@ int main(int argc, char **argv)
 	rv = blapi_selftest(modesToTest, numModesToTest, inoff, outoff,
 	                    encrypt, decrypt);
 	PORT_Free(cipherInfo);
 	return rv == SECSuccess ? 0 : 1;
     }
 
     /* Do FIPS self-test */
     if (bltest.commands[cmd_FIPS].activated) {
-	CK_RV ckrv = sftk_fipsPowerUpSelfTest();
+	CK_RV ckrv = sftk_FIPSEntryOK();
 	fprintf(stdout, "CK_RV: %ld.\n", ckrv);
         PORT_Free(cipherInfo);
         if (ckrv == CKR_OK)
             return SECSuccess;
         return SECFailure;
     }
 
     /*
--- a/cmd/fipstest/aes.sh
+++ b/cmd/fipstest/aes.sh
@@ -1,22 +1,29 @@
 #!/bin/sh
+# 
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
+#
 #
 # A Bourne shell script for running the NIST AES Algorithm Validation Suite
 #
 # Before you run the script, set your PATH, LD_LIBRARY_PATH, ... environment
 # variables appropriately so that the fipstest command and the NSPR and NSS
 # shared libraries/DLLs are on the search path.  Then run this script in the
 # directory where the REQUEST (.req) files reside.  The script generates the
 # RESPONSE (.rsp) files in the same directory.
 
+BASEDIR=${1-.}
+TESTDIR=${BASEDIR}/AES
+COMMAND=${2-run}
+REQDIR=${TESTDIR}/req
+RSPDIR=${TESTDIR}/resp
+
 cbc_kat_requests="
 CBCGFSbox128.req
 CBCGFSbox192.req
 CBCGFSbox256.req
 CBCKeySbox128.req
 CBCKeySbox192.req
 CBCKeySbox256.req
 CBCVarKey128.req
@@ -61,38 +68,45 @@ ECBMCT256.req
 "
 
 ecb_mmt_requests="
 ECBMMT128.req
 ECBMMT192.req
 ECBMMT256.req
 "
 
+if [ ${COMMAND} = "verify" ]; then
+    for request in $cbc_kat_requests $cbc_mct_requests $cbc_mmt_requests $ecb_kat_requests $ecb_mct_requests $ecb_mmt_requests; do
+	sh ./validate1.sh ${TESTDIR} $request
+    done
+    exit 0
+fi
+
+for request in $cbc_kat_requests; do
+    response=`echo $request | sed -e "s/req/rsp/"`
+    echo $request $response
+    fipstest aes kat cbc ${REQDIR}/$request > ${RSPDIR}/$response
+done
+for request in $cbc_mct_requests; do
+    response=`echo $request | sed -e "s/req/rsp/"`
+    echo $request $response
+    fipstest aes mct cbc ${REQDIR}/$request > ${RSPDIR}/$response
+done
+for request in $cbc_mmt_requests; do
+    response=`echo $request | sed -e "s/req/rsp/"`
+    echo $request $response
+    fipstest aes mmt cbc ${REQDIR}/$request > ${RSPDIR}/$response
+done
 for request in $ecb_kat_requests; do
     response=`echo $request | sed -e "s/req/rsp/"`
     echo $request $response
-    fipstest aes kat ecb $request > $response
-done
-for request in $ecb_mmt_requests; do
-    response=`echo $request | sed -e "s/req/rsp/"`
-    echo $request $response
-    fipstest aes mmt ecb $request > $response
+    fipstest aes kat ecb ${REQDIR}/$request > ${RSPDIR}/$response
 done
 for request in $ecb_mct_requests; do
     response=`echo $request | sed -e "s/req/rsp/"`
     echo $request $response
-    fipstest aes mct ecb $request > $response
+    fipstest aes mct ecb ${REQDIR}/$request > ${RSPDIR}/$response
 done
-for request in $cbc_kat_requests; do
+for request in $ecb_mmt_requests; do
     response=`echo $request | sed -e "s/req/rsp/"`
     echo $request $response
-    fipstest aes kat cbc $request > $response
+    fipstest aes mmt ecb ${REQDIR}/$request > ${RSPDIR}/$response
 done
-for request in $cbc_mmt_requests; do
-    response=`echo $request | sed -e "s/req/rsp/"`
-    echo $request $response
-    fipstest aes mmt cbc $request > $response
-done
-for request in $cbc_mct_requests; do
-    response=`echo $request | sed -e "s/req/rsp/"`
-    echo $request $response
-    fipstest aes mct cbc $request > $response
-done
new file mode 100644
--- /dev/null
+++ b/cmd/fipstest/aesgcm.sh
@@ -0,0 +1,67 @@
+#!/bin/sh
+# 
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# A Bourne shell script for running the NIST AES Algorithm Validation Suite
+#
+# Before you run the script, set your PATH, LD_LIBRARY_PATH, ... environment
+# variables appropriately so that the fipstest command and the NSPR and NSS
+# shared libraries/DLLs are on the search path.  Then run this script in the
+# directory where the REQUEST (.req) files reside.  The script generates the
+# RESPONSE (.rsp) files in the same directory.
+
+BASEDIR=${1-.}
+TESTDIR=${BASEDIR}/AES_GCM
+COMMAND=${2-run}
+REQDIR=${TESTDIR}/req
+RSPDIR=${TESTDIR}/resp
+
+gcm_decrypt_requests="
+gcmDecrypt128.req
+gcmDecrypt192.req
+gcmDecrypt256.req
+"
+
+gcm_encrypt_extiv_requests="
+gcmEncryptExtIV128.req
+gcmEncryptExtIV192.req
+gcmEncryptExtIV256.req
+"
+gcm_encrypt_intiv_requests="
+"
+
+#gcm_encrypt_intiv_requests="
+#gcmEncryptIntIV128.req
+#gcmEncryptIntIV192.req
+#gcmEncryptIntIV256.req
+#"
+
+if [ ${COMMAND} = "verify" ]; then
+    for request in $gcm_decrypt_requests $gcm_encrypt_extiv_requests; do
+	sh ./validate1.sh ${TESTDIR} $request ' ' '-e /Reason:/d'
+    done
+    for request in $gcm_encrypt_intiv_requests; do
+	name=`basename $request .req`
+    	echo ">>>>>  $name"
+        fipstest aes gcm decrypt ${RSPDIR}/$name.rsp | grep FAIL
+    done
+    exit 0
+fi
+
+for request in $gcm_decrypt_requests; do
+    response=`echo $request | sed -e "s/req/rsp/"`
+    echo $request $response
+    fipstest aes gcm decrypt ${REQDIR}/$request > ${RSPDIR}/$response
+done
+for request in $gcm_encrypt_intiv_requests; do
+    response=`echo $request | sed -e "s/req/rsp/"`
+    echo $request $response
+    fipstest aes gcm encrypt_intiv ${REQDIR}/$request > ${RSPDIR}/$response
+done
+for request in $gcm_encrypt_extiv_requests; do
+    response=`echo $request | sed -e "s/req/rsp/"`
+    echo $request $response
+    fipstest aes gcm encrypt_extiv ${REQDIR}/$request > ${RSPDIR}/$response
+done
--- a/cmd/fipstest/dsa.sh
+++ b/cmd/fipstest/dsa.sh
@@ -1,38 +1,71 @@
 #!/bin/sh
+# 
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
 #
 # A Bourne shell script for running the NIST DSA Validation System
 #
 # Before you run the script, set your PATH, LD_LIBRARY_PATH, ... environment
 # variables appropriately so that the fipstest command and the NSPR and NSS
 # shared libraries/DLLs are on the search path.  Then run this script in the
 # directory where the REQUEST (.req) files reside.  The script generates the
 # RESPONSE (.rsp) files in the same directory.
+BASEDIR=${1-.}
+TESTDIR=${BASEDIR}/DSA2
+COMMAND=${2-run}
+REQDIR=${TESTDIR}/req
+RSPDIR=${TESTDIR}/resp
+
+
+#
+# several of the DSA tests do use known answer tests to verify the result.
+# in those cases, feed generated tests back into the fipstest tool and
+# see if we can verify those value. NOTE: th PQGVer and SigVer tests verify
+# the dsa pqgver and dsa sigver functions, so we know they can detect errors
+# in those PQGGen and SigGen. Only the KeyPair verify is potentially circular.
+#
+if [ ${COMMAND} = "verify" ]; then
+# verify generated keys
+    name=KeyPair
+    echo ">>>>>  $name"
+    fipstest dsa keyver ${RSPDIR}/$name.rsp | grep ^Result.=.F
+# verify generated pqg values
+    name=PQGGen
+    echo ">>>>>  $name"
+    fipstest dsa pqgver ${RSPDIR}/$name.rsp | grep ^Result.=.F
+# verify PQGVer with known answer
+#    sh ./validate1.sh ${TESTDIR} PQGVer.req ' ' '-e /^Result.=.F/s;.(.*);; -e /^Result.=.P/s;.(.*);;'
+# verify signatures
+    name=SigGen
+    echo ">>>>>  $name"
+    fipstest dsa sigver ${RSPDIR}/$name.rsp | grep ^Result.=.F
+# verify SigVer with known answer
+    sh ./validate1.sh ${TESTDIR} SigVer.req ' ' '-e /^X.=/d -e /^Result.=.F/s;.(.*);;'
+    exit 0
+fi
 
 request=KeyPair.req
 response=`echo $request | sed -e "s/req/rsp/"`
 echo $request $response
-fipstest dsa keypair $request > $response
+fipstest dsa keypair ${REQDIR}/$request > ${RSPDIR}/$response
 
 request=PQGGen.req
 response=`echo $request | sed -e "s/req/rsp/"`
 echo $request $response
-fipstest dsa pqggen $request > $response
+fipstest dsa pqggen ${REQDIR}/$request > ${RSPDIR}/$response
 
-request=PQGVer.req
+request=PQGVer1863.req
 response=`echo $request | sed -e "s/req/rsp/"`
 echo $request $response
-fipstest dsa pqgver $request > $response
+fipstest dsa pqgver ${REQDIR}/$request > ${RSPDIR}/$response
 
 request=SigGen.req
 response=`echo $request | sed -e "s/req/rsp/"`
 echo $request $response
-fipstest dsa siggen $request > $response
+fipstest dsa siggen ${REQDIR}/$request > ${RSPDIR}/$response
 
 request=SigVer.req
 response=`echo $request | sed -e "s/req/rsp/"`
 echo $request $response
-fipstest dsa sigver $request > $response
+fipstest dsa sigver ${REQDIR}/$request > ${RSPDIR}/$response
--- a/cmd/fipstest/ecdsa.sh
+++ b/cmd/fipstest/ecdsa.sh
@@ -1,33 +1,60 @@
 #!/bin/sh
+# 
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
 #
 # A Bourne shell script for running the NIST ECDSA Validation System
 #
 # Before you run the script, set your PATH, LD_LIBRARY_PATH, ... environment
 # variables appropriately so that the fipstest command and the NSPR and NSS
 # shared libraries/DLLs are on the search path.  Then run this script in the
 # directory where the REQUEST (.req) files reside.  The script generates the
 # RESPONSE (.rsp) files in the same directory.
+BASEDIR=${1-.}
+TESTDIR=${BASEDIR}/ECDSA2
+COMMAND=${2-run}
+REQDIR=${TESTDIR}/req
+RSPDIR=${TESTDIR}/resp
+
+#
+# several of the ECDSA tests do not use known answer tests to verify the result.
+# In those cases, feed generated tests back into the fipstest tool and
+# see if we can verify those value. NOTE:  PQGVer and SigVer tests verify
+# the dsa pqgver and dsa sigver functions, so we know they can detect errors
+# in those PQGGen and SigGen. Only the KeyPair verify is potentially circular.
+#
+if [ ${COMMAND} = "verify" ]; then
+# verify generated keys
+    name=KeyPair
+    echo ">>>>>  $name"
+    fipstest ecdsa keyver ${RSPDIR}/$name.rsp | grep ^Result.=.F
+    sh ./validate1.sh ${TESTDIR} PKV.req ' ' '-e /^X.=/d -e /^Result.=.F/s;.(.*);; -e /^Result.=.P/s;.(.*);;'
+# verify signatures
+    name=SigGen
+    echo ">>>>>  $name"
+    fipstest ecdsa sigver ${RSPDIR}/$name.rsp | grep ^Result.=.F
+# verify SigVer with known answer
+    sh ./validate1.sh ${TESTDIR} SigVer.req ' ' '-e /^X.=/d -e /^Result.=.F/s;.(.*);; -e /^Result.=.P/s;.(.*);;'
+    exit 0
+fi
 
 request=KeyPair.req
 response=`echo $request | sed -e "s/req/rsp/"`
 echo $request $response
-fipstest ecdsa keypair $request > $response
+fipstest ecdsa keypair ${REQDIR}/$request > ${RSPDIR}/$response
 
 request=PKV.req
 response=`echo $request | sed -e "s/req/rsp/"`
 echo $request $response
-fipstest ecdsa pkv $request > $response
+fipstest ecdsa pkv ${REQDIR}/$request > ${RSPDIR}/$response
 
 request=SigGen.req
 response=`echo $request | sed -e "s/req/rsp/"`
 echo $request $response
-fipstest ecdsa siggen $request > $response
+fipstest ecdsa siggen ${REQDIR}/$request > ${RSPDIR}/$response
 
 request=SigVer.req
 response=`echo $request | sed -e "s/req/rsp/"`
 echo $request $response
-fipstest ecdsa sigver $request > $response
+fipstest ecdsa sigver ${REQDIR}/$request > ${RSPDIR}/$response
--- a/cmd/fipstest/hmac.sh
+++ b/cmd/fipstest/hmac.sh
@@ -1,24 +1,36 @@
 #!/bin/sh
+# 
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
 #
 # A Bourne shell script for running the NIST HMAC Algorithm Validation Suite
 #
 # Before you run the script, set your PATH, LD_LIBRARY_PATH, ... environment
 # variables appropriately so that the fipstest command and the NSPR and NSS
 # shared libraries/DLLs are on the search path.  Then run this script in the
 # directory where the REQUEST (.req) files reside.  The script generates the
 # RESPONSE (.rsp) files in the same directory.
+
+BASEDIR=${1-.}
+TESTDIR=${BASEDIR}/HMAC
+COMMAND=${2-run}
+REQDIR=${TESTDIR}/req
+RSPDIR=${TESTDIR}/resp
                                
 hmac_requests="
 HMAC.req
 "
 
+if [ ${COMMAND} = "verify" ]; then
+    for request in $hmac_requests; do
+	sh ./validate1.sh ${TESTDIR} $request
+    done
+    exit 0
+fi
 for request in $hmac_requests; do
     response=`echo $request | sed -e "s/req/rsp/"`
     echo $request $response
-    fipstest hmac $request > $response
+    fipstest hmac ${REQDIR}/$request > ${RSPDIR}/$response
 done
 
--- a/cmd/fipstest/rng.sh
+++ b/cmd/fipstest/rng.sh
@@ -1,23 +1,34 @@
 #!/bin/sh
+# 
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
 #
 # A Bourne shell script for running the NIST RNG Validation Suite
 #
 # Before you run the script, set your PATH, LD_LIBRARY_PATH, ... environment
 # variables appropriately so that the fipstest command and the NSPR and NSS
 # shared libraries/DLLs are on the search path.  Then run this script in the
 # directory where the REQUEST (.req) files reside.  The script generates the
 # RESPONSE (.rsp) files in the same directory.
+BASEDIR=${1-.}
+TESTDIR=${BASEDIR}/DRBG800-90A
+COMMAND=${2-run}
+REQDIR=${TESTDIR}/req
+RSPDIR=${TESTDIR}/resp
 
 drbg_requests="
-SHA256_DRBG.req
+Hash_DRBG.req
 "
 
+if [ ${COMMAND} = "verify" ]; then
+    for request in $drbg_requests; do
+	sh ./validate1.sh ${TESTDIR} $request
+    done
+    exit 0
+fi
 for request in $drbg_requests; do
     response=`echo $request | sed -e "s/req/rsp/"`
     echo $request $response
-    fipstest drbg $request > $response
+    fipstest drbg ${REQDIR}/$request > ${RSPDIR}/$response
 done
--- a/cmd/fipstest/rsa.sh
+++ b/cmd/fipstest/rsa.sh
@@ -1,24 +1,50 @@
 #!/bin/sh
+# 
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
 #
 # A Bourne shell script for running the NIST RSA Validation System
 #
 # Before you run the script, set your PATH, LD_LIBRARY_PATH, ... environment
 # variables appropriately so that the fipstest command and the NSPR and NSS
 # shared libraries/DLLs are on the search path.  Then run this script in the
 # directory where the REQUEST (.req) files reside.  The script generates the
 # RESPONSE (.rsp) files in the same directory.
-
+BASEDIR=${1-.}
+TESTDIR=${BASEDIR}/RSA2
+COMMAND=${2-run}
+REQDIR=${TESTDIR}/req
+RSPDIR=${TESTDIR}/resp
 
-request=SigGen15.req
+if [ ${COMMAND} = "verify" ]; then
+#verify the signatures. The fax file does not have any known answers, so
+#use our own verify function.
+    name=SigGen15_186-3
+    echo ">>>>>  $name"
+    fipstest rsa sigver ${RSPDIR}/$name.rsp | grep ^Result.=.F
+#    fipstest rsa sigver ${REQDIR}/SigVer15_186-3.req | grep ^Result.=.F
+#The Fax file has the private exponent and the salt value, remove it
+#also remove the false reason
+    sh ./validate1.sh ${TESTDIR} SigVer15_186-3.req ' ' '-e /^SaltVal/d -e/^d.=/d -e /^p.=/d -e /^q.=/d -e /^EM.with/d -e /^Result.=.F/s;.(.*);;'
+#
+# currently don't have a way to verify the RSA keygen
+#
+    exit 0
+fi
+
+request=SigGen15_186-3.req
 response=`echo $request | sed -e "s/req/rsp/"`
 echo $request $response
-fipstest rsa siggen $request > $response
+fipstest rsa siggen ${REQDIR}/$request > ${RSPDIR}/$response
 
-request=SigVer15.req
+request=SigVer15_186-3.req
 response=`echo $request | sed -e "s/req/rsp/"`
 echo $request $response
-fipstest rsa sigver $request > $response
+fipstest rsa sigver ${REQDIR}/$request > ${RSPDIR}/$response
+
+#request=KeyGen_186-3.req
+request=KeyGen_RandomProbablyPrime3_3.req
+response=`echo $request | sed -e "s/req/rsp/"`
+echo $request $response
+fipstest rsa keypair ${REQDIR}/$request > ${RSPDIR}/$response
new file mode 100644
--- /dev/null
+++ b/cmd/fipstest/runtest.sh
@@ -0,0 +1,17 @@
+#!/bin/sh
+# 
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+TESTDIR=${1-.}
+COMMAND=${2-run}
+TESTS="aes aesgcm dsa ecdsa hmac tls rng rsa sha tdea"
+if [ ${NSS_ENABLE_ECC}x = 1x ]; then
+   TESTS=${TESTS} ecdsa
+fi
+for i in $TESTS
+do
+    echo "********************Running $i tests"
+    sh ./${i}.sh ${TESTDIR} ${COMMAND}
+done
--- a/cmd/fipstest/sha.sh
+++ b/cmd/fipstest/sha.sh
@@ -1,50 +1,66 @@
 #!/bin/sh
+# 
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
 #
 # A Bourne shell script for running the NIST SHA Algorithm Validation Suite
 #
 # Before you run the script, set your PATH, LD_LIBRARY_PATH, ... environment
 # variables appropriately so that the fipstest command and the NSPR and NSS
 # shared libraries/DLLs are on the search path.  Then run this script in the
 # directory where the REQUEST (.req) files reside.  The script generates the
 # RESPONSE (.rsp) files in the same directory.
+BASEDIR=${1-.}
+TESTDIR=${BASEDIR}/SHA
+COMMAND=${2-run}
+REQDIR=${TESTDIR}/req
+RSPDIR=${TESTDIR}/resp
                                
 sha_ShortMsg_requests="
 SHA1ShortMsg.req
+SHA224ShortMsg.req
 SHA256ShortMsg.req
 SHA384ShortMsg.req
 SHA512ShortMsg.req
 "
 
 sha_LongMsg_requests="
 SHA1LongMsg.req
+SHA224LongMsg.req
 SHA256LongMsg.req
 SHA384LongMsg.req
 SHA512LongMsg.req
 "
 
 sha_Monte_requests="
 SHA1Monte.req
+SHA224Monte.req
 SHA256Monte.req
 SHA384Monte.req
 SHA512Monte.req
 "
+
+if [ ${COMMAND} = "verify" ]; then
+    for request in $sha_ShortMsg_requests $sha_LongMsg_requests $sha_Monte_requests; do
+	sh ./validate1.sh ${TESTDIR} $request
+    done
+    exit 0
+fi
+
 for request in $sha_ShortMsg_requests; do
     response=`echo $request | sed -e "s/req/rsp/"`
     echo $request $response
-    fipstest sha $request > $response
+    fipstest sha ${REQDIR}/$request > ${RSPDIR}/$response
 done
 for request in $sha_LongMsg_requests; do
     response=`echo $request | sed -e "s/req/rsp/"`
     echo $request $response
-    fipstest sha $request > $response
+    fipstest sha ${REQDIR}/$request > ${RSPDIR}/$response
 done
 for request in $sha_Monte_requests; do
     response=`echo $request | sed -e "s/req/rsp/"`
     echo $request $response
-    fipstest sha $request > $response
+    fipstest sha ${REQDIR}/$request > ${RSPDIR}/$response
 done
 
--- a/cmd/fipstest/tdea.sh
+++ b/cmd/fipstest/tdea.sh
@@ -1,22 +1,28 @@
 #!/bin/sh
+# 
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
 #
 # A Bourne shell script for running the NIST tdea Algorithm Validation Suite
 #
 # Before you run the script, set your PATH, LD_LIBRARY_PATH, ... environment
 # variables appropriately so that the fipstest command and the NSPR and NSS
 # shared libraries/DLLs are on the search path.  Then run this script in the
 # directory where the REQUEST (.req) files reside.  The script generates the
 # RESPONSE (.rsp) files in the same directory.
 
+BASEDIR=${1-.}
+TESTDIR=${BASEDIR}/TDES
+COMMAND=${2-run}
+REQDIR=${TESTDIR}/req
+RSPDIR=${TESTDIR}/resp
+
 #CBC_Known_Answer_tests
 #Initial Permutation KAT  
 #Permutation Operation KAT 
 #Subsitution Table KAT    
 #Variable Key KAT         
 #Variable PlainText KAT   
 cbc_kat_requests="
 TCBCinvperm.req   
@@ -54,38 +60,47 @@ TECBMonte3.req
 "
 
 ecb_mmt_requests="
 TECBMMT1.req
 TECBMMT2.req
 TECBMMT3.req
 "
 
-for request in $ecb_mmt_requests; do
+
+if [ ${COMMAND} = "verify" ]; then
+    for request in $cbc_kat_requests $cbc_monte_requests $cbc_mmt_requests $ecb_kat_requests $ecb_monte_requests $ecb_mmt_requests
+    do
+	sh ./validate1.sh ${TESTDIR} $request "-e /^NumKeys/d"
+    done
+    exit 0
+fi
+
+for request in $cbc_kat_requests; do
     response=`echo $request | sed -e "s/req/rsp/"`
     echo $request $response
-    fipstest tdea mmt ecb $request > $response
+    fipstest tdea kat cbc ${REQDIR}/$request > ${RSPDIR}/$response
+done
+for request in $cbc_mmt_requests; do
+    response=`echo $request | sed -e "s/req/rsp/"`
+    echo $request $response
+    fipstest tdea mmt cbc ${REQDIR}/$request > ${RSPDIR}/$response
+done
+for request in $cbc_monte_requests; do
+    response=`echo $request | sed -e "s/req/rsp/"`
+    echo $request $response
+    fipstest tdea mct cbc ${REQDIR}/$request > ${RSPDIR}/$response
 done
 for request in $ecb_kat_requests; do
     response=`echo $request | sed -e "s/req/rsp/"`
     echo $request $response
-    fipstest tdea kat ecb $request > $response
+    fipstest tdea kat ecb ${REQDIR}/$request > ${RSPDIR}/$response
+done
+for request in $ecb_mmt_requests; do
+    response=`echo $request | sed -e "s/req/rsp/"`
+    echo $request $response
+    fipstest tdea mmt ecb ${REQDIR}/$request > ${RSPDIR}/$response
 done
 for request in $ecb_monte_requests; do
     response=`echo $request | sed -e "s/req/rsp/"`
     echo $request $response
-    fipstest tdea mct ecb $request > $response
-done
-for request in $cbc_mmt_requests; do
-    response=`echo $request | sed -e "s/req/rsp/"`
-    echo $request $response
-    fipstest tdea mmt cbc $request > $response
+    fipstest tdea mct ecb ${REQDIR}/$request > ${RSPDIR}/$response
 done
-for request in $cbc_kat_requests; do
-    response=`echo $request | sed -e "s/req/rsp/"`
-    echo $request $response
-    fipstest tdea kat cbc $request > $response
-done
-for request in $cbc_monte_requests; do
-    response=`echo $request | sed -e "s/req/rsp/"`
-    echo $request $response
-    fipstest tdea mct cbc $request > $response
-done
new file mode 100644
--- /dev/null
+++ b/cmd/fipstest/tls.sh
@@ -0,0 +1,34 @@
+#!/bin/sh
+# 
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# A Bourne shell script for running the NIST RNG Validation Suite
+#
+# Before you run the script, set your PATH, LD_LIBRARY_PATH, ... environment
+# variables appropriately so that the fipstest command and the NSPR and NSS
+# shared libraries/DLLs are on the search path.  Then run this script in the
+# directory where the REQUEST (.req) files reside.  The script generates the
+# RESPONSE (.rsp) files in the same directory.
+BASEDIR=${1-.}
+TESTDIR=${BASEDIR}/KDF135
+COMMAND=${2-run}
+REQDIR=${TESTDIR}/req
+RSPDIR=${TESTDIR}/resp
+
+drbg_requests="
+tls.req
+"
+
+if [ ${COMMAND} = "verify" ]; then
+    for request in $drbg_requests; do
+	sh ./validate1.sh ${TESTDIR} $request
+    done
+    exit 0
+fi
+for request in $drbg_requests; do
+    response=`echo $request | sed -e "s/req/rsp/"`
+    echo $request $response
+    fipstest tls ${REQDIR}/$request > ${RSPDIR}/$response
+done
new file mode 100644
--- /dev/null
+++ b/cmd/fipstest/validate.sh
@@ -0,0 +1,7 @@
+#!/bin/sh
+# 
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+sh ./runtest.sh ${1-.} verify
new file mode 100644
--- /dev/null
+++ b/cmd/fipstest/validate1.sh
@@ -0,0 +1,30 @@
+#!/bin/sh
+# 
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# Validate1.sh is a helper shell script that each of the base test shell 
+# scripts call to help validate that the generated response (response) 
+# matches the known answer response (fax). Sometimes (depending on the 
+# individual tests) there are extraneous output in either or both response 
+# and fax files. These allow the caller to pass in additional sed commands 
+# to clear out those extraneous outputs before we compare the two files.
+# The sed line always clears out Windows line endings, replaces tabs with 
+# spaces, and removed comments.
+#
+TESTDIR=${1-.}
+request=${2}
+extraneous_response=${3}
+extraneous_fax=${4}
+name=`basename $request .req`
+echo ">>>>>  $name"
+sed -e 's;
;;g' -e 's;	; ;g' -e '/^#/d' $extraneous_response ${TESTDIR}/resp/${name}.rsp > /tmp/y1
+# if we didn't generate any output, flag that as an error 
+size=`sum /tmp/y1 | awk '{ print $NF }'`
+if [ $size -eq 0 ]; then
+   echo "${TESTDIR}/resp/${name}.rsp: empty"
+   exit 1;
+fi
+sed -e 's;
;;g' -e 's;	; ;g' -e '/^#/d' $extraneous_fax ${TESTDIR}/fax/${name}.fax > /tmp/y2
+diff -i -w -B /tmp/y1 /tmp/y2
--- a/lib/freebl/Makefile
+++ b/lib/freebl/Makefile
@@ -41,23 +41,34 @@ ifdef USE_ABI32_FPU
 endif
 
 ifeq ($(FREEBL_NO_DEPEND),1)
 	DEFINES += -DFREEBL_NO_DEPEND
 	STUBS_SRCS = stubs.c
 endif
 
 ifeq ($(FREEBL_LOWHASH),1)
+	DEFINES += -DFREEBL_LOWHASH
 	LOWHASH_SRCS = nsslowhash.c
 	LOWHASH_EXPORTS = nsslowhash.h
-	MAPFILE_SOURCE = freebl_hash.def
+	MAPFILE_SOURCE = freebl_hash_vector.def
+	NEED_STUB_BUILD = 1
 else
 	MAPFILE_SOURCE = freebl.def
 endif
 
+ifdef USE_STUB_BUILD
+	CSRCS           = lowhash_vector.c
+	SIMPLE_OBJS     = $(CSRCS:.c=$(OBJ_SUFFIX))
+	OBJS            = $(addprefix $(OBJDIR)/$(PROG_PREFIX), $(SIMPLE_OBJS))
+	ALL_TRASH :=    $(TARGETS) $(OBJS) $(OBJDIR) LOGS TAGS $(GARBAGE) \
+                $(NOSUCHFILE) so_locations
+	MAPFILE_SOURCE = freebl_hash.def
+endif
+
 # FREEBL_USE_PRELINK
 #
 # Most modern version of Linux support a speed optimization scheme where an
 # application called prelink modifies programs and shared libraries to quickly
 # load if they fit into an already designed address space. In short, prelink
 # scans the list of programs and libraries on your system, assigns them a
 # predefined space in the the address space, then provides the fixups to the
 # library.
@@ -82,16 +93,20 @@ endif
 # library itself, which can have imbedded spaces or special characters).
 #
 ifdef FREEBL_USE_PRELINK
 	DEFINES += -DFREEBL_USE_PRELINK
 ifdef LINUX
 	DEFINES += -D__GNU_SOURCE=1
 endif
 endif
+ifdef NSS_NO_INIT_SUPPORT
+    DEFINES += -DNSS_NO_INIT_SUPPORT
+endif
+
 ifdef FREEBL_PRELINK_COMMAND
 	DEFINES +=-DFREEBL_PRELINK_COMMAND=\"$(FREEBL_PRELINK_COMMAND)\"
 endif
 # NSS_X86 means the target is a 32-bits x86 CPU architecture
 # NSS_X64 means the target is a 64-bits 64 CPU architecture
 # NSS_X86_OR_X64 means the target is either x86 or x64
 ifeq (,$(filter-out i386 x386 x86 x86_64,$(CPU_ARCH)))
         DEFINES += -DNSS_X86_OR_X64
@@ -221,16 +236,21 @@ ifeq ($(CPU_ARCH),x86)
     #ECL_USE_FP = 1
 endif
 ifeq ($(CPU_ARCH),arm)
     DEFINES += -DMP_ASSEMBLY_MULTIPLY -DMP_ASSEMBLY_SQUARE 
     DEFINES += -DMP_USE_UINT_DIGIT
     DEFINES += -DSHA_NO_LONG_LONG # avoid 64-bit arithmetic in SHA512
     MPI_SRCS += mpi_arm.c
 endif
+ifeq ($(CPU_ARCH),ppc)
+ifdef USE_64
+    DEFINES += -DNSS_NO_INIT_SUPPORT
+endif # USE_64
+endif # ppc
 endif # Linux
 
 ifeq ($(OS_TARGET),AIX)
     DEFINES += -DMP_USE_UINT_DIGIT
     ifndef USE_64
 	DEFINES += -DMP_NO_DIV_WORD -DMP_NO_ADD_WORD -DMP_NO_SUB_WORD
     endif
 endif # AIX
@@ -593,16 +613,27 @@ ALL_TRASH += $(SINGLE_SHLIB_DIR)
 
 release_md libs:: $(SINGLE_SHLIB_DIR)
 	$(MAKE) FREEBL_CHILD_BUILD=1 \
  OBJDIR=$(SINGLE_SHLIB_DIR) $@
 ######################## common stuff #########################
 
 endif
 
+ifdef NEED_STUB_BUILD
+SINGLE_SHLIB_DIR = $(OBJDIR)/$(OS_TARGET)_SINGLE_SHLIB
+ALL_TRASH += $(SINGLE_SHLIB_DIR) 
+$(SINGLE_SHLIB_DIR):
+	-mkdir $(SINGLE_SHLIB_DIR)
+
+release_md libs:: $(SINGLE_SHLIB_DIR)
+	$(MAKE) FREEBL_CHILD_BUILD=1 USE_STUB_BUILD=1 \
+ OBJDIR=$(SINGLE_SHLIB_DIR) $@
+endif
+
 # multiple shared libraries
 
 ######################## ABI32_FPU stuff #########################
 ifdef HAVE_ABI32_FPU
 ABI32_FPU_DIR = $(OBJDIR)/$(OS_TARGET)_ABI32_FPU
 ALL_TRASH += $(ABI32_FPU_DIR) 
 
 $(ABI32_FPU_DIR):
--- a/lib/freebl/blapii.h
+++ b/lib/freebl/blapii.h
@@ -16,16 +16,19 @@
 typedef SECStatus (*freeblCipherFunc)(void *cx, unsigned char *output,
                           unsigned int *outputLen, unsigned int maxOutputLen,
                           const unsigned char *input, unsigned int inputLen,
 			  unsigned int blocksize);
 typedef void (*freeblDestroyFunc)(void *cx, PRBool freeit);
 
 SEC_BEGIN_PROTOS
 
+SECStatus BL_FIPSEntryOK(PRBool freeblOnly);
+PRBool BL_POSTRan(PRBool freeblOnly);
+
 #if defined(XP_UNIX) && !defined(NO_FORK_CHECK)
 
 extern PRBool bl_parentForkedAfterC_Initialize;
 
 #define SKIP_AFTER_FORK(x) if (!bl_parentForkedAfterC_Initialize) x
 
 #else
 
new file mode 100644
--- /dev/null
+++ b/lib/freebl/blname.c
@@ -0,0 +1,98 @@
+/*
+ *  * blname.c - determine the freebl library name.
+ *   *
+ *    * This Source Code Form is subject to the terms of the Mozilla Public
+ *     * License, v. 2.0. If a copy of the MPL was not distributed with this
+ *      * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#if defined(FREEBL_LOWHASH)
+static const char* default_name =
+    SHLIB_PREFIX"freeblpriv"SHLIB_VERSION"."SHLIB_SUFFIX;
+#else
+static const char* default_name =
+    SHLIB_PREFIX"freebl"SHLIB_VERSION"."SHLIB_SUFFIX;
+#endif
+
+/* getLibName() returns the name of the library to load. */
+
+#if defined(SOLARIS) && defined(__sparc)
+#include <stddef.h>
+#include <strings.h>
+#include <sys/systeminfo.h>
+
+
+#if defined(NSS_USE_64)
+
+const static char fpu_hybrid_shared_lib[] = "libfreebl_64fpu_3.so";
+const static char int_hybrid_shared_lib[] = "libfreebl_64int_3.so";
+const static char non_hybrid_shared_lib[] = "libfreebl_64fpu_3.so";
+
+const static char int_hybrid_isa[] = "sparcv9";
+const static char fpu_hybrid_isa[] = "sparcv9+vis";
+
+#else
+
+const static char fpu_hybrid_shared_lib[] = "libfreebl_32fpu_3.so";
+const static char int_hybrid_shared_lib[] = "libfreebl_32int64_3.so";
+/* This was for SPARC V8, now obsolete. */
+const static char *const non_hybrid_shared_lib = NULL;
+
+const static char int_hybrid_isa[] = "sparcv8plus";
+const static char fpu_hybrid_isa[] = "sparcv8plus+vis";
+
+#endif
+
+static const char *
+getLibName(void)
+{
+    char * found_int_hybrid;
+    char * found_fpu_hybrid;
+    long buflen;
+    char buf[256];
+
+    buflen = sysinfo(SI_ISALIST, buf, sizeof buf);
+    if (buflen <= 0) 
+	return NULL;
+    /* sysinfo output is always supposed to be NUL terminated, but ... */
+    if (buflen < sizeof buf) 
+    	buf[buflen] = '\0';
+    else
+    	buf[(sizeof buf) - 1] = '\0';
+    /* The ISA list is a space separated string of names of ISAs and
+     * ISA extensions, in order of decreasing performance.
+     * There are two different ISAs with which NSS's crypto code can be
+     * accelerated. If both are in the list, we take the first one.
+     * If one is in the list, we use it, and if neither then we use
+     * the base unaccelerated code.
+     */
+    found_int_hybrid = strstr(buf, int_hybrid_isa);
+    found_fpu_hybrid = strstr(buf, fpu_hybrid_isa);
+    if (found_fpu_hybrid && 
+	(!found_int_hybrid ||
+	 (found_int_hybrid - found_fpu_hybrid) >= 0)) {
+	return fpu_hybrid_shared_lib;
+    }
+    if (found_int_hybrid) {
+	return int_hybrid_shared_lib;
+    }
+    return non_hybrid_shared_lib;
+}
+
+#elif defined(HPUX) && !defined(NSS_USE_64) && !defined(__ia64)
+#include <unistd.h>
+
+/* This code tests to see if we're running on a PA2.x CPU.
+** It returns true (1) if so, and false (0) otherwise.
+*/
+static const char *
+getLibName(void)
+{
+    long cpu = sysconf(_SC_CPU_VERSION);
+    return (cpu == CPU_PA_RISC2_0) 
+		? "libfreebl_32fpu_3.sl"
+	        : "libfreebl_32int_3.sl" ;
+}
+#else
+/* default case, for platforms/ABIs that have only one freebl shared lib. */
+static const char * getLibName(void) { return default_name; }
+#endif
--- a/lib/freebl/ctr.c
+++ b/lib/freebl/ctr.c
@@ -25,26 +25,31 @@ CTR_InitContext(CTRContext *ctr, void *c
 
     if (ctrParams->ulCounterBits == 0 ||
 	ctrParams->ulCounterBits > blocksize * PR_BITS_PER_BYTE) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return SECFailure;
     }
 
     /* Invariant: 0 < ctr->bufPtr <= blocksize */
+    ctr->checkWrap = PR_FALSE;
     ctr->bufPtr = blocksize; /* no unused data in the buffer */
     ctr->cipher = cipher;
     ctr->context = context;
     ctr->counterBits = ctrParams->ulCounterBits;
     if (blocksize > sizeof(ctr->counter) ||
 	blocksize > sizeof(ctrParams->cb)) {
 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
 	return SECFailure;
     }
     PORT_Memcpy(ctr->counter, ctrParams->cb, blocksize);
+    if (ctr->counterBits < 64) {
+	PORT_Memcpy(ctr->counterFirst, ctr->counter, blocksize);
+	ctr->checkWrap = PR_TRUE;
+    }
     return SECSuccess;
 }
 
 CTRContext *
 CTR_CreateContext(void *context, freeblCipherFunc cipher,
 		  const unsigned char *param, unsigned int blocksize)
 {
     CTRContext *ctr;
@@ -142,31 +147,43 @@ CTR_Update(CTRContext *ctr, unsigned cha
 	}
 	PORT_Assert(ctr->bufPtr == blocksize);
     }
 
     while (inlen >= blocksize) {
 	rv = (*ctr->cipher)(ctr->context, ctr->buffer, &tmp, blocksize,
 			ctr->counter, blocksize, blocksize);
 	ctr_GetNextCtr(ctr->counter, ctr->counterBits, blocksize);
+	if (ctr->checkWrap) {
+	    if (PORT_Memcmp(ctr->counter, ctr->counterFirst, blocksize) == 0) {
+		PORT_SetError(SEC_ERROR_INVALID_ARGS);
+		return SECFailure;
+	    }
+	}
 	if (rv != SECSuccess) {
 	    return SECFailure;
 	}
 	ctr_xor(outbuf, inbuf, ctr->buffer, blocksize);
 	outbuf += blocksize;
 	inbuf += blocksize;
 	*outlen += blocksize;
 	inlen -= blocksize;
     }
     if (inlen == 0) {
 	return SECSuccess;
     }
     rv = (*ctr->cipher)(ctr->context, ctr->buffer, &tmp, blocksize,
 			ctr->counter, blocksize, blocksize);
     ctr_GetNextCtr(ctr->counter, ctr->counterBits, blocksize);
+    if (ctr->checkWrap) {
+	if (PORT_Memcmp(ctr->counter, ctr->counterFirst, blocksize) == 0) {
+	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
+	    return SECFailure;
+	}
+    }
     if (rv != SECSuccess) {
 	return SECFailure;
     }
     ctr_xor(outbuf, inbuf, ctr->buffer, inlen);
     ctr->bufPtr = inlen;
     *outlen += inlen;
     return SECSuccess;
 }
--- a/lib/freebl/ctr.h
+++ b/lib/freebl/ctr.h
@@ -9,16 +9,18 @@
 
 /* This structure is defined in this header because both ctr.c and gcm.c
  * need it. */
 struct CTRContextStr {
    freeblCipherFunc cipher;
    void *context;
    unsigned char counter[MAX_BLOCK_SIZE];
    unsigned char buffer[MAX_BLOCK_SIZE];
+   unsigned char counterFirst[MAX_BLOCK_SIZE];  /* counter overlfow value */
+   PRBool checkWrap;				/*check for counter overflow*/
    unsigned long counterBits;
    unsigned int bufPtr;
 };
 
 typedef struct CTRContextStr CTRContext;
 
 SECStatus CTR_InitContext(CTRContext *ctr, void *context,
 			freeblCipherFunc cipher, const unsigned char *param,
--- a/lib/freebl/cts.c
+++ b/lib/freebl/cts.c
@@ -92,16 +92,17 @@ CTS_EncryptUpdate(CTSContext *cts, unsig
 		unsigned int *outlen, unsigned int maxout,
 		const unsigned char *inbuf, unsigned int inlen,
 		unsigned int blocksize)
 {
     unsigned char lastBlock[MAX_BLOCK_SIZE];
     unsigned int tmp;
     int fullblocks;
     int written;
+    unsigned char *saveout = outbuf;
     SECStatus rv;
 
     if (inlen < blocksize) {
 	PORT_SetError(SEC_ERROR_INPUT_LEN);
 	return SECFailure;
     }
 
     if (maxout < inlen) {
@@ -136,16 +137,18 @@ CTS_EncryptUpdate(CTSContext *cts, unsig
      * below */
     PORT_Memcpy(lastBlock, inbuf, inlen);
     PORT_Memset(lastBlock + inlen, 0, blocksize - inlen);
     rv = (*cts->cipher)(cts->context, outbuf, &tmp, maxout, lastBlock,
 			blocksize, blocksize);
     PORT_Memset(lastBlock, 0, blocksize);
     if (rv == SECSuccess) {
 	*outlen = written + blocksize;
+    } else {
+	PORT_Memset(saveout, 0, written+blocksize);
     }
     return rv;
 }
 
 
 #define XOR_BLOCK(x,y,count) for(i=0; i < count; i++) x[i] = x[i] ^ y[i]
 
 /*
@@ -179,16 +182,17 @@ CTS_DecryptUpdate(CTSContext *cts, unsig
 		unsigned int blocksize)
 {
     unsigned char *Pn;
     unsigned char Cn_2[MAX_BLOCK_SIZE]; /* block Cn-2 */
     unsigned char Cn_1[MAX_BLOCK_SIZE]; /* block Cn-1 */
     unsigned char Cn[MAX_BLOCK_SIZE];   /* block Cn   */
     unsigned char lastBlock[MAX_BLOCK_SIZE];
     const unsigned char *tmp;
+    unsigned char *saveout = outbuf;
     unsigned int tmpLen;
     unsigned int fullblocks, pad;
     unsigned int i;
     SECStatus rv;
 
     if (inlen < blocksize) {
 	PORT_SetError(SEC_ERROR_INPUT_LEN);
 	return SECFailure;
@@ -275,16 +279,18 @@ CTS_DecryptUpdate(CTSContext *cts, unsig
     /* copy Cn-1* into last buf to recover Cn-1 */
     PORT_Memcpy(lastBlock, Cn_1, inlen);
     /* note: because Cn and Cn-1 were out of order, our pointer to Pn also
      * points to where Pn-1 needs to reside. From here on out read Pn in
      * the code as really Pn-1. */
     rv = (*cts->cipher)(cts->context, Pn, &tmpLen, blocksize, lastBlock,
 	 blocksize, blocksize);
     if (rv != SECSuccess) {
+	PORT_Memset(lastBlock, 0, blocksize);
+	PORT_Memset(saveout, 0, *outlen);
 	return SECFailure;
     }
     /* make up for the out of order CBC decryption */
     XOR_BLOCK(Pn, Cn_2, blocksize);
     XOR_BLOCK(Pn, Cn, blocksize);
     /* reset iv to Cn  */
     PORT_Memcpy(cts->iv, Cn, blocksize);
     /* This makes Cn the last block for the next decrypt operation, which
--- a/lib/freebl/dh.c
+++ b/lib/freebl/dh.c
@@ -168,36 +168,38 @@ DH_NewKey(DHParams *params, DHPrivateKey
     CHECK_SEC_OK( SECITEM_CopyItem(arena, &key->prime, &params->prime) );
     SECITEM_TO_MPINT(key->prime, &p);
     /* Set private key's g */
     CHECK_SEC_OK( SECITEM_CopyItem(arena, &key->base, &params->base) );
     SECITEM_TO_MPINT(key->base, &g);
     /* Generate private key xa */
     SECITEM_AllocItem(arena, &key->privateValue,
                       dh_GetSecretKeyLen(params->prime.len));
-    RNG_GenerateGlobalRandomBytes(key->privateValue.data, 
-                                  key->privateValue.len);
+    CHECK_SEC_OK(RNG_GenerateGlobalRandomBytes(key->privateValue.data, 
+                                  key->privateValue.len));
     SECITEM_TO_MPINT( key->privateValue, &xa );
     /* xa < p */
     CHECK_MPI_OK( mp_mod(&xa, &p, &xa) );
     /* Compute public key Ya = g ** xa mod p */
     CHECK_MPI_OK( mp_exptmod(&g, &xa, &p, &Ya) );
     MPINT_TO_SECITEM(&Ya, &key->publicValue, key->arena);
     *privKey = key;
 cleanup:
     mp_clear(&g);
     mp_clear(&xa);
     mp_clear(&p);
     mp_clear(&Ya);
     if (err) {
 	MP_TO_SEC_ERROR(err);
 	rv = SECFailure;
     }
-    if (rv)
+    if (rv) {
+	*privKey = NULL;
 	PORT_FreeArena(arena, PR_TRUE);
+    }
     return rv;
 }
 
 SECStatus 
 DH_Derive(SECItem *publicValue, 
           SECItem *prime, 
           SECItem *privateValue, 
           SECItem *derivedSecret, 
@@ -267,30 +269,37 @@ DH_Derive(SECItem *publicValue,
     if (mp_cmp_d(&ZZ, 1) == 0 ||
         mp_cmp(&ZZ, &psub1) == 0) {
         err = MP_BADARG;
         goto cleanup;
     }
 
     /* allocate a buffer which can hold the entire derived secret. */
     secret = PORT_Alloc(len);
+    if (secret == NULL) {
+	err = MP_MEM;
+	goto cleanup;
+    }
     /* grab the derived secret */
     err = mp_to_unsigned_octets(&ZZ, secret, len);
     if (err >= 0) err = MP_OKAY;
     /* 
     ** if outBytes is 0 take all of the bytes from the derived secret.
     ** if outBytes is not 0 take exactly outBytes from the derived secret, zero
     ** pad at the beginning if necessary, and truncate beginning bytes 
     ** if necessary.
     */
     if (outBytes > 0)
 	nb = outBytes;
     else
 	nb = len;
-    SECITEM_AllocItem(NULL, derivedSecret, nb);
+    if (SECITEM_AllocItem(NULL, derivedSecret, nb)  == NULL) {
+	err = MP_MEM;
+	goto cleanup;
+    }
     if (len < nb) {
 	unsigned int offset = nb - len;
 	memset(derivedSecret->data, 0, offset);
 	memcpy(derivedSecret->data + offset, secret, len);
     } else {
 	memcpy(derivedSecret->data, secret + len - nb, nb);
     }
 cleanup:
@@ -355,21 +364,29 @@ KEA_Derive(SECItem *prime,
     CHECK_MPI_OK( mp_exptmod(&Y, &r, &p, &t) );
     /* u = DH(R, x, p) = R ** x mod p */
     CHECK_MPI_OK( mp_exptmod(&R, &x, &p, &u) );
     /* w = (t + u) mod p */
     CHECK_MPI_OK( mp_addmod(&t, &u, &p, &w) );
     /* allocate a buffer for the full derived secret */
     len = mp_unsigned_octet_size(&w);
     secret = PORT_Alloc(len);
+    if (secret == NULL) {
+	err = MP_MEM;
+	goto cleanup;
+    }
     /* grab the secret */
     err = mp_to_unsigned_octets(&w, secret, len);
     if (err > 0) err = MP_OKAY;
     /* allocate output buffer */
-    SECITEM_AllocItem(NULL, derivedSecret, KEA_DERIVED_SECRET_LEN);
+    if (SECITEM_AllocItem(NULL, derivedSecret, KEA_DERIVED_SECRET_LEN)
+								  == NULL) {
+	err = MP_MEM;
+	goto cleanup;
+    }
     memset(derivedSecret->data, 0, derivedSecret->len);
     /* copy in the 128 lsb of the secret */
     if (len >= KEA_DERIVED_SECRET_LEN) {
 	memcpy(derivedSecret->data, secret + (len - KEA_DERIVED_SECRET_LEN),
 	       KEA_DERIVED_SECRET_LEN);
     } else {
 	offset = KEA_DERIVED_SECRET_LEN - len;
 	memcpy(derivedSecret->data + offset, secret, len);
@@ -382,16 +399,18 @@ cleanup:
     mp_clear(&x);
     mp_clear(&t);
     mp_clear(&u);
     mp_clear(&w);
     if (secret)
 	PORT_ZFree(secret, len);
     if (err) {
 	MP_TO_SEC_ERROR(err);
+	if (derivedSecret->data) 
+	    PORT_ZFree(derivedSecret->data, derivedSecret->len);
 	return SECFailure;
     }
     return SECSuccess;
 }
 
 PRBool 
 KEA_Verify(SECItem *Y, SECItem *prime, SECItem *subPrime)
 {
--- a/lib/freebl/drbg.c
+++ b/lib/freebl/drbg.c
@@ -71,17 +71,17 @@ struct RNGContextStr {
      * immediately after V_type to avoid extra copies. To accomplish this
      * in a way that compiliers can't perturb, we declare V_type and V
      * as a V_Data array and reference them by macros */
     PRUint8  V_Data[PRNG_SEEDLEN+1]; /* internal state variables */
 #define  V_type  V_Data[0]
 #define  V(rng)       (((rng)->V_Data)+1)
 #define  VSize(rng)   ((sizeof (rng)->V_Data) -1)
     PRUint8  C[PRNG_SEEDLEN];        /* internal state variables */
-    PRUint8  oldV[PRNG_SEEDLEN];     /* for continuous rng checking */
+    PRUint8  lastOutput[SHA256_LENGTH];     /* for continuous rng checking */
     /* If we get calls for the PRNG to return less than the length of our
      * hash, we extend the request for a full hash (since we'll be doing
      * the full hash anyway). Future requests for random numbers are fulfilled
      * from the remainder of the bytes we generated. Requests for bytes longer
      * than the hash size are fulfilled directly from the HashGen function
      * of the random number generator. */
     PRUint8  reseed_counter[RESEED_BYTE+1]; /* number of requests since the 
 					     * last reseed. Need only be
@@ -281,34 +281,47 @@ prng_reseed_test(RNGContext *rng, const 
  *
  * This function is specified in NIST SP 800-90 section 10.1.1.4, Hashgen
  */
 static void
 prng_Hashgen(RNGContext *rng, PRUint8 *returned_bytes, 
 	     unsigned int no_of_returned_bytes)
 {
     PRUint8 data[VSize(rng)];
+    PRUint8 thisHash[SHA256_LENGTH];
+    PRUint8 *lastHash = rng->lastOutput;
 
     PORT_Memcpy(data, V(rng), VSize(rng));
     while (no_of_returned_bytes) {
 	SHA256Context ctx;
 	unsigned int len;
 	unsigned int carry;
 
  	SHA256_Begin(&ctx);
  	SHA256_Update(&ctx, data, sizeof data);
-	SHA256_End(&ctx, returned_bytes, &len, no_of_returned_bytes);
+	SHA256_End(&ctx, thisHash, &len, SHA256_LENGTH);
+	if (PORT_Memcmp(lastHash, thisHash, len) == 0) {
+	    rng->isValid = PR_FALSE;
+	    break;
+	}
+	if (no_of_returned_bytes < SHA256_LENGTH) {
+	    len = no_of_returned_bytes;
+	}
+	PORT_Memcpy(returned_bytes, thisHash, len);
+	lastHash = returned_bytes;
 	returned_bytes += len;
 	no_of_returned_bytes -= len;
 	/* The carry parameter is a bool (increment or not). 
 	 * This increments data if no_of_returned_bytes is not zero */
         carry = no_of_returned_bytes;
 	PRNG_ADD_CARRY_ONLY(data, (sizeof data)- 1, carry);
     }
+    PORT_Memcpy(rng->lastOutput, thisHash, SHA256_LENGTH);
     PORT_Memset(data, 0, sizeof data); 
+    PORT_Memset(thisHash, 0, sizeof thisHash); 
 }
 
 /* 
  * Generates new random bytes and advances the internal prng state.	
  * additional bytes are only used in algorithm testing.
  * 
  * This function is specified in NIST SP 800-90 section 10.1.1.4
  */
@@ -342,38 +355,42 @@ prng_generateNewBytes(RNGContext *rng,
  	SHA256_Update(&ctx, additional_input, additional_input_len);
 	SHA256_End(&ctx, w, NULL, sizeof w);
 	PRNG_ADD_BITS_AND_CARRY(V(rng), VSize(rng), w, sizeof w, carry)
 	PORT_Memset(w, 0, sizeof w);
 #undef w 
     }
 
     if (no_of_returned_bytes == SHA256_LENGTH) {
-	/* short_cut to hashbuf and save a copy and a clear */
+	/* short_cut to hashbuf and a couple of copies and clears */
 	SHA256_HashBuf(returned_bytes, V(rng), VSize(rng) );
+	/* continuous rng check */
+	if (memcmp(rng->lastOutput, returned_bytes, SHA256_LENGTH) == 0) {
+	    rng->isValid = PR_FALSE;
+	}
+	PORT_Memcpy(rng->lastOutput, returned_bytes, sizeof rng->lastOutput);
     } else {
     	prng_Hashgen(rng, returned_bytes, no_of_returned_bytes);
     }
     /* advance our internal state... */
     rng->V_type = prngGenerateByteType;
     SHA256_HashBuf(H, rng->V_Data, sizeof rng->V_Data);
     PRNG_ADD_BITS_AND_CARRY(V(rng), VSize(rng), H, sizeof H, carry)
     PRNG_ADD_BITS(V(rng), VSize(rng), rng->C, sizeof rng->C, carry);
     PRNG_ADD_BITS_AND_CARRY(V(rng), VSize(rng), rng->reseed_counter, 
 					sizeof rng->reseed_counter, carry)
     carry = 1;
     PRNG_ADD_CARRY_ONLY(rng->reseed_counter,(sizeof rng->reseed_counter)-1, carry);
 
-    /* continuous rng check */
-    if (memcmp(V(rng), rng->oldV, sizeof rng->oldV) == 0) {
-	rng->isValid = PR_FALSE;
+    /* if the prng failed, don't return any output, signal softoken */
+    if (!rng->isValid) {
+	PORT_Memset(returned_bytes, 0,  no_of_returned_bytes);
 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
 	return SECFailure;
     }
-    PORT_Memcpy(rng->oldV, V(rng), sizeof rng->oldV);
     return SECSuccess;
 }
 
 /* Use NSPR to prevent RNG_RNGInit from being called from separate
  * threads, creating a race condition.
  */
 static const PRCallOnceType pristineCallOnce;
 static PRCallOnceType coRNGInit;
--- a/lib/freebl/ec.c
+++ b/lib/freebl/ec.c
@@ -371,17 +371,17 @@ cleanup:
     mp_clear(&privKeyVal);
     mp_clear(&order_1);
     mp_clear(&one);
     if (err < MP_OKAY) {
 	MP_TO_SEC_ERROR(err);
 	rv = SECFailure;
     }
     if (rv != SECSuccess && privKeyBytes) {
-	PORT_Free(privKeyBytes);
+	PORT_ZFree(privKeyBytes,2*len);
 	privKeyBytes = NULL;
     }
     return privKeyBytes;
 }
 #endif /* NSS_DISABLE_ECC */
 
 /* Generates a new EC key pair. The private key is a random value and
  * the public key is the result of performing a scalar point multiplication
@@ -1070,17 +1070,17 @@ cleanup:
     mp_clear(&s_);
     mp_clear(&c);
     mp_clear(&u1);
     mp_clear(&u2);
     mp_clear(&x1);
     mp_clear(&v);
     mp_clear(&n);
 
-    if (pointC.data) SECITEM_FreeItem(&pointC, PR_FALSE);
+    if (pointC.data) SECITEM_ZfreeItem(&pointC, PR_FALSE);
     if (err) {
 	MP_TO_SEC_ERROR(err);
 	rv = SECFailure;
     }
 
 #if EC_DEBUG
     printf("ECDSA verification %s\n",
 	(rv == SECSuccess) ? "succeeded" : "failed");
new file mode 100644
--- /dev/null
+++ b/lib/freebl/fipsfreebl.c
@@ -0,0 +1,1772 @@
+/*
+ * PKCS #11 FIPS Power-Up Self Test.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+/* $Id: fipstest.c,v 1.31 2012/06/28 17:55:06 rrelyea%redhat.com Exp $ */
+
+#ifdef FREEBL_NO_DEPEND
+#include "stubs.h"
+#endif
+
+#include "blapi.h"
+#include "seccomon.h"   /* Required for RSA and DSA. */
+#include "secerr.h"
+#include "prtypes.h"
+
+#ifdef NSS_ENABLE_ECC
+#include "ec.h"         /* Required for ECDSA */
+#endif
+
+/*
+ * different platforms have different ways of calling and initial entry point
+ * when the dll/.so is loaded. Most platforms support either a posix pragma
+ * or the GCC attribute. Some platforms suppor a pre-defined name, and some
+ * platforms have a link line way of invoking this function.
+ */
+
+/* The pragma */
+#if defined(USE_INIT_PRAGMA)
+#pragma init(bl_startup_tests)
+#endif
+
+
+/* GCC Attribute */
+#if defined(__GNUC__) && !defined(NSS_NO_INIT_SUPPORT)
+#define INIT_FUNCTION __attribute__((constructor))
+#else
+#define INIT_FUNCTION
+#endif
+
+static void INIT_FUNCTION bl_startup_tests(void);
+
+
+/* Windows pre-defined entry */
+#ifdef XP_WIN
+#include <windows.h>
+
+BOOL WINAPI DllMain(
+    HINSTANCE hinstDLL,  // handle to DLL module
+    DWORD fdwReason,     // reason for calling function
+    LPVOID lpReserved )  // reserved
+{
+    // Perform actions based on the reason for calling.
+    switch( fdwReason ) 
+    { 
+        case DLL_PROCESS_ATTACH:
+         // Initialize once for each new process.
+         // Return FALSE to fail DLL load.
+	bl_startup_tests();
+            break;
+
+        case DLL_THREAD_ATTACH:
+         // Do thread-specific initialization.
+            break;
+
+        case DLL_THREAD_DETACH:
+         // Do thread-specific cleanup.
+            break;
+
+        case DLL_PROCESS_DETACH:
+         // Perform any necessary cleanup.
+            break;
+    }
+    return TRUE;  // Successful DLL_PROCESS_ATTACH.
+}
+#endif
+
+/* insert other platform dependent init entry points here, or modify
+ * the linker line */
+
+
+/* FIPS preprocessor directives for RC2-ECB and RC2-CBC.        */
+#define FIPS_RC2_KEY_LENGTH                      5  /*  40-bits */
+#define FIPS_RC2_ENCRYPT_LENGTH                  8  /*  64-bits */
+#define FIPS_RC2_DECRYPT_LENGTH                  8  /*  64-bits */
+
+
+/* FIPS preprocessor directives for RC4.                        */
+#define FIPS_RC4_KEY_LENGTH                      5  /*  40-bits */
+#define FIPS_RC4_ENCRYPT_LENGTH                  8  /*  64-bits */
+#define FIPS_RC4_DECRYPT_LENGTH                  8  /*  64-bits */
+
+
+/* FIPS preprocessor directives for DES-ECB and DES-CBC.        */
+#define FIPS_DES_ENCRYPT_LENGTH                  8  /*  64-bits */
+#define FIPS_DES_DECRYPT_LENGTH                  8  /*  64-bits */
+
+
+/* FIPS preprocessor directives for DES3-CBC and DES3-ECB.      */
+#define FIPS_DES3_ENCRYPT_LENGTH                 8  /*  64-bits */
+#define FIPS_DES3_DECRYPT_LENGTH                 8  /*  64-bits */
+
+
+/* FIPS preprocessor directives for AES-ECB and AES-CBC.        */
+#define FIPS_AES_BLOCK_SIZE                     16  /* 128-bits */
+#define FIPS_AES_ENCRYPT_LENGTH                 16  /* 128-bits */
+#define FIPS_AES_DECRYPT_LENGTH                 16  /* 128-bits */
+#define FIPS_AES_128_KEY_SIZE                   16  /* 128-bits */
+#define FIPS_AES_192_KEY_SIZE                   24  /* 192-bits */
+#define FIPS_AES_256_KEY_SIZE                   32  /* 256-bits */
+
+
+/* FIPS preprocessor directives for message digests             */
+#define FIPS_KNOWN_HASH_MESSAGE_LENGTH          64  /* 512-bits */
+
+
+/* FIPS preprocessor directives for RSA.                         */
+#define FIPS_RSA_TYPE                           siBuffer
+#define FIPS_RSA_PUBLIC_EXPONENT_LENGTH           3 /*   24-bits */
+#define FIPS_RSA_PRIVATE_VERSION_LENGTH           1 /*    8-bits */
+#define FIPS_RSA_MESSAGE_LENGTH                 256 /* 2048-bits */
+#define FIPS_RSA_COEFFICIENT_LENGTH             128 /* 1024-bits */
+#define FIPS_RSA_PRIME0_LENGTH                  128 /* 1024-bits */
+#define FIPS_RSA_PRIME1_LENGTH                  128 /* 1024-bits */
+#define FIPS_RSA_EXPONENT0_LENGTH               128 /* 1024-bits */
+#define FIPS_RSA_EXPONENT1_LENGTH               128 /* 1024-bits */
+#define FIPS_RSA_PRIVATE_EXPONENT_LENGTH        256 /* 2048-bits */
+#define FIPS_RSA_ENCRYPT_LENGTH                 256 /* 2048-bits */
+#define FIPS_RSA_DECRYPT_LENGTH                 256 /* 2048-bits */
+#define FIPS_RSA_SIGNATURE_LENGTH               256 /* 2048-bits */
+#define FIPS_RSA_MODULUS_LENGTH                 256 /* 2048-bits */
+
+
+/* FIPS preprocessor directives for DSA.                        */
+#define FIPS_DSA_TYPE                           siBuffer
+#define FIPS_DSA_DIGEST_LENGTH                  20 /*  160-bits */
+#define FIPS_DSA_SUBPRIME_LENGTH                20 /*  160-bits */
+#define FIPS_DSA_SIGNATURE_LENGTH               40 /*  320-bits */
+#define FIPS_DSA_PRIME_LENGTH                  128 /* 1024-bits */
+#define FIPS_DSA_BASE_LENGTH                   128 /* 1024-bits */
+
+/* FIPS preprocessor directives for RNG.                        */
+#define FIPS_RNG_XKEY_LENGTH                    32  /* 256-bits */
+
+static SECStatus
+freebl_fips_DES3_PowerUpSelfTest( void )
+{
+    /* DES3 Known Key (56-bits). */
+    static const PRUint8 des3_known_key[] = { "ANSI Triple-DES Key Data" };
+
+    /* DES3-CBC Known Initialization Vector (64-bits). */
+    static const PRUint8 des3_cbc_known_initialization_vector[] = { "Security" };
+
+    /* DES3 Known Plaintext (64-bits). */
+    static const PRUint8 des3_ecb_known_plaintext[] = { "Netscape" };
+    static const PRUint8 des3_cbc_known_plaintext[] = { "Netscape" };
+
+    /* DES3 Known Ciphertext (64-bits). */
+    static const PRUint8 des3_ecb_known_ciphertext[] = {
+			   0x55,0x8e,0xad,0x3c,0xee,0x49,0x69,0xbe};
+    static const PRUint8 des3_cbc_known_ciphertext[] = {
+			   0x43,0xdc,0x6a,0xc1,0xaf,0xa6,0x32,0xf5};
+
+    /* DES3 variables. */
+    PRUint8        des3_computed_ciphertext[FIPS_DES3_ENCRYPT_LENGTH];
+    PRUint8        des3_computed_plaintext[FIPS_DES3_DECRYPT_LENGTH];
+    DESContext *   des3_context;
+    unsigned int   des3_bytes_encrypted;
+    unsigned int   des3_bytes_decrypted;
+    SECStatus      des3_status;
+
+
+    /*******************************************************/
+    /* DES3-ECB Single-Round Known Answer Encryption Test. */
+    /*******************************************************/
+
+    des3_context = DES_CreateContext( des3_known_key, NULL,
+                                     NSS_DES_EDE3, PR_TRUE );
+
+    if( des3_context == NULL ) {
+        PORT_SetError( SEC_ERROR_NO_MEMORY ); 
+        return( SECFailure );
+    }
+
+    des3_status = DES_Encrypt( des3_context, des3_computed_ciphertext,
+                               &des3_bytes_encrypted, FIPS_DES3_ENCRYPT_LENGTH,
+                               des3_ecb_known_plaintext,
+                               FIPS_DES3_DECRYPT_LENGTH );
+
+    DES_DestroyContext( des3_context, PR_TRUE );
+
+    if( ( des3_status != SECSuccess ) ||
+        ( des3_bytes_encrypted != FIPS_DES3_ENCRYPT_LENGTH ) ||
+        ( PORT_Memcmp( des3_computed_ciphertext, des3_ecb_known_ciphertext,
+                       FIPS_DES3_ENCRYPT_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+
+    /*******************************************************/
+    /* DES3-ECB Single-Round Known Answer Decryption Test. */
+    /*******************************************************/
+
+    des3_context = DES_CreateContext( des3_known_key, NULL,
+                                     NSS_DES_EDE3, PR_FALSE );
+
+    if( des3_context == NULL ) {
+        PORT_SetError( SEC_ERROR_NO_MEMORY ); 
+        return( SECFailure );
+    }
+
+    des3_status = DES_Decrypt( des3_context, des3_computed_plaintext,
+                               &des3_bytes_decrypted, FIPS_DES3_DECRYPT_LENGTH,
+                               des3_ecb_known_ciphertext,
+                               FIPS_DES3_ENCRYPT_LENGTH );
+
+    DES_DestroyContext( des3_context, PR_TRUE );
+
+    if( ( des3_status != SECSuccess ) ||
+        ( des3_bytes_decrypted != FIPS_DES3_DECRYPT_LENGTH ) ||
+        ( PORT_Memcmp( des3_computed_plaintext, des3_ecb_known_plaintext,
+                       FIPS_DES3_DECRYPT_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+
+    /*******************************************************/
+    /* DES3-CBC Single-Round Known Answer Encryption Test. */
+    /*******************************************************/
+
+    des3_context = DES_CreateContext( des3_known_key,
+                                      des3_cbc_known_initialization_vector,
+                                      NSS_DES_EDE3_CBC, PR_TRUE );
+
+    if( des3_context == NULL ) {
+        PORT_SetError( SEC_ERROR_NO_MEMORY ); 
+        return( SECFailure );
+    }
+
+    des3_status = DES_Encrypt( des3_context, des3_computed_ciphertext,
+                               &des3_bytes_encrypted, FIPS_DES3_ENCRYPT_LENGTH,
+                               des3_cbc_known_plaintext,
+                               FIPS_DES3_DECRYPT_LENGTH );
+
+    DES_DestroyContext( des3_context, PR_TRUE );
+
+    if( ( des3_status != SECSuccess ) ||
+        ( des3_bytes_encrypted != FIPS_DES3_ENCRYPT_LENGTH ) ||
+        ( PORT_Memcmp( des3_computed_ciphertext, des3_cbc_known_ciphertext,
+                       FIPS_DES3_ENCRYPT_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+
+    /*******************************************************/
+    /* DES3-CBC Single-Round Known Answer Decryption Test. */
+    /*******************************************************/
+
+    des3_context = DES_CreateContext( des3_known_key,
+                                      des3_cbc_known_initialization_vector,
+                                      NSS_DES_EDE3_CBC, PR_FALSE );
+
+    if( des3_context == NULL ) {
+        PORT_SetError( SEC_ERROR_NO_MEMORY ); 
+        return( SECFailure );
+    }
+
+    des3_status = DES_Decrypt( des3_context, des3_computed_plaintext,
+                               &des3_bytes_decrypted, FIPS_DES3_DECRYPT_LENGTH,
+                               des3_cbc_known_ciphertext,
+                               FIPS_DES3_ENCRYPT_LENGTH );
+
+    DES_DestroyContext( des3_context, PR_TRUE );
+
+    if( ( des3_status != SECSuccess ) ||
+        ( des3_bytes_decrypted != FIPS_DES3_DECRYPT_LENGTH ) ||
+        ( PORT_Memcmp( des3_computed_plaintext, des3_cbc_known_plaintext,
+                       FIPS_DES3_DECRYPT_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    return( SECSuccess );
+}
+
+
+/* AES self-test for 128-bit, 192-bit, or 256-bit key sizes*/
+static SECStatus
+freebl_fips_AES_PowerUpSelfTest( int aes_key_size )
+{
+    /* AES Known Key (up to 256-bits). */
+    static const PRUint8 aes_known_key[] = 
+        { "AES-128 RIJNDAELLEADNJIR 821-SEA" };
+
+    /* AES-CBC Known Initialization Vector (128-bits). */
+    static const PRUint8 aes_cbc_known_initialization_vector[] = 
+        { "SecurityytiruceS" };
+
+    /* AES Known Plaintext (128-bits). (blocksize is 128-bits) */
+    static const PRUint8 aes_known_plaintext[] = { "NetscapeepacsteN" };
+
+    /* AES Known Ciphertext (128-bit key). */
+    static const PRUint8 aes_ecb128_known_ciphertext[] = {
+        0x3c,0xa5,0x96,0xf3,0x34,0x6a,0x96,0xc1,
+        0x03,0x88,0x16,0x7b,0x20,0xbf,0x35,0x47 };
+
+    static const PRUint8 aes_cbc128_known_ciphertext[]  = {
+        0xcf,0x15,0x1d,0x4f,0x96,0xe4,0x4f,0x63,
+        0x15,0x54,0x14,0x1d,0x4e,0xd8,0xd5,0xea };
+
+    /* AES Known Ciphertext (192-bit key). */
+    static const PRUint8 aes_ecb192_known_ciphertext[] = { 
+        0xa0,0x18,0x62,0xed,0x88,0x19,0xcb,0x62,
+        0x88,0x1d,0x4d,0xfe,0x84,0x02,0x89,0x0e };
+
+    static const PRUint8 aes_cbc192_known_ciphertext[]  = { 
+        0x83,0xf7,0xa4,0x76,0xd1,0x6f,0x07,0xbe,
+        0x07,0xbc,0x43,0x2f,0x6d,0xad,0x29,0xe1 };
+
+    /* AES Known Ciphertext (256-bit key). */
+    static const PRUint8 aes_ecb256_known_ciphertext[] = { 
+        0xdb,0xa6,0x52,0x01,0x8a,0x70,0xae,0x66,
+        0x3a,0x99,0xd8,0x95,0x7f,0xfb,0x01,0x67 };
+    
+    static const PRUint8 aes_cbc256_known_ciphertext[]  = { 
+        0x37,0xea,0x07,0x06,0x31,0x1c,0x59,0x27,
+        0xc5,0xc5,0x68,0x71,0x6e,0x34,0x40,0x16 };
+
+    const PRUint8 *aes_ecb_known_ciphertext =
+        ( aes_key_size == FIPS_AES_128_KEY_SIZE) ? aes_ecb128_known_ciphertext :
+        ( aes_key_size == FIPS_AES_192_KEY_SIZE) ? aes_ecb192_known_ciphertext :
+                                aes_ecb256_known_ciphertext;
+
+    const PRUint8 *aes_cbc_known_ciphertext =
+        ( aes_key_size == FIPS_AES_128_KEY_SIZE) ? aes_cbc128_known_ciphertext :
+        ( aes_key_size == FIPS_AES_192_KEY_SIZE) ? aes_cbc192_known_ciphertext :
+                                aes_cbc256_known_ciphertext;
+
+    /* AES variables. */
+    PRUint8        aes_computed_ciphertext[FIPS_AES_ENCRYPT_LENGTH];
+    PRUint8        aes_computed_plaintext[FIPS_AES_DECRYPT_LENGTH];
+    AESContext *   aes_context;
+    unsigned int   aes_bytes_encrypted;
+    unsigned int   aes_bytes_decrypted;
+    SECStatus      aes_status;
+
+    /*check if aes_key_size is 128, 192, or 256 bits */
+    if ((aes_key_size != FIPS_AES_128_KEY_SIZE) && 
+        (aes_key_size != FIPS_AES_192_KEY_SIZE) && 
+        (aes_key_size != FIPS_AES_256_KEY_SIZE))  {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    /******************************************************/
+    /* AES-ECB Single-Round Known Answer Encryption Test: */
+    /******************************************************/
+
+    aes_context = AES_CreateContext( aes_known_key, NULL, NSS_AES, PR_TRUE,
+                                     aes_key_size, FIPS_AES_BLOCK_SIZE );
+
+    if( aes_context == NULL ) {
+        PORT_SetError( SEC_ERROR_NO_MEMORY ); 
+        return( SECFailure );
+    }
+
+    aes_status = AES_Encrypt( aes_context, aes_computed_ciphertext,
+                              &aes_bytes_encrypted, FIPS_AES_ENCRYPT_LENGTH,
+                              aes_known_plaintext,
+                              FIPS_AES_DECRYPT_LENGTH );
+    
+    AES_DestroyContext( aes_context, PR_TRUE );
+
+    if( ( aes_status != SECSuccess ) ||
+        ( aes_bytes_encrypted != FIPS_AES_ENCRYPT_LENGTH ) ||
+        ( PORT_Memcmp( aes_computed_ciphertext, aes_ecb_known_ciphertext,
+                       FIPS_AES_ENCRYPT_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+
+    /******************************************************/
+    /* AES-ECB Single-Round Known Answer Decryption Test: */
+    /******************************************************/
+
+    aes_context = AES_CreateContext( aes_known_key, NULL, NSS_AES, PR_FALSE,
+                                     aes_key_size, FIPS_AES_BLOCK_SIZE );
+
+    if( aes_context == NULL ) {
+        PORT_SetError( SEC_ERROR_NO_MEMORY ); 
+        return( SECFailure );
+    }
+
+    aes_status = AES_Decrypt( aes_context, aes_computed_plaintext,
+                              &aes_bytes_decrypted, FIPS_AES_DECRYPT_LENGTH,
+                              aes_ecb_known_ciphertext,
+                              FIPS_AES_ENCRYPT_LENGTH );
+
+    AES_DestroyContext( aes_context, PR_TRUE );
+
+    if( ( aes_status != SECSuccess ) ||         
+        ( aes_bytes_decrypted != FIPS_AES_DECRYPT_LENGTH ) ||
+        ( PORT_Memcmp( aes_computed_plaintext, aes_known_plaintext,
+                       FIPS_AES_DECRYPT_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+
+    /******************************************************/
+    /* AES-CBC Single-Round Known Answer Encryption Test. */
+    /******************************************************/
+
+    aes_context = AES_CreateContext( aes_known_key,
+                                     aes_cbc_known_initialization_vector,
+                                     NSS_AES_CBC, PR_TRUE, aes_key_size, 
+                                     FIPS_AES_BLOCK_SIZE );
+
+    if( aes_context == NULL ) {
+        PORT_SetError( SEC_ERROR_NO_MEMORY ); 
+        return( SECFailure );
+    }
+
+    aes_status = AES_Encrypt( aes_context, aes_computed_ciphertext,
+                              &aes_bytes_encrypted, FIPS_AES_ENCRYPT_LENGTH,
+                              aes_known_plaintext,
+                              FIPS_AES_DECRYPT_LENGTH );
+
+    AES_DestroyContext( aes_context, PR_TRUE );
+
+    if( ( aes_status != SECSuccess ) ||
+        ( aes_bytes_encrypted != FIPS_AES_ENCRYPT_LENGTH ) ||
+        ( PORT_Memcmp( aes_computed_ciphertext, aes_cbc_known_ciphertext,
+                       FIPS_AES_ENCRYPT_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+
+    /******************************************************/
+    /* AES-CBC Single-Round Known Answer Decryption Test. */
+    /******************************************************/
+
+    aes_context = AES_CreateContext( aes_known_key,
+                                     aes_cbc_known_initialization_vector,
+                                     NSS_AES_CBC, PR_FALSE, aes_key_size, 
+                                     FIPS_AES_BLOCK_SIZE );
+
+    if( aes_context == NULL ) {
+        PORT_SetError( SEC_ERROR_NO_MEMORY ); 
+        return( SECFailure );
+    }
+
+    aes_status = AES_Decrypt( aes_context, aes_computed_plaintext,
+                              &aes_bytes_decrypted, FIPS_AES_DECRYPT_LENGTH,
+                              aes_cbc_known_ciphertext,
+                              FIPS_AES_ENCRYPT_LENGTH );
+
+    AES_DestroyContext( aes_context, PR_TRUE );
+
+    if( ( aes_status != SECSuccess ) ||
+        ( aes_bytes_decrypted != FIPS_AES_DECRYPT_LENGTH ) ||
+        ( PORT_Memcmp( aes_computed_plaintext, aes_known_plaintext,
+                       FIPS_AES_DECRYPT_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    return( SECSuccess );
+}
+
+/* Known Hash Message (512-bits).  Used for all hashes (incl. SHA-N [N>1]). */
+static const PRUint8 known_hash_message[] = {
+  "The test message for the MD2, MD5, and SHA-1 hashing algorithms." };
+
+/****************************************************/
+/* Single Round HMAC SHA-X test                     */
+/****************************************************/
+static SECStatus
+freebl_fips_HMAC(unsigned char *hmac_computed,
+               const PRUint8 *secret_key,
+               unsigned int secret_key_length,
+               const PRUint8 *message,
+               unsigned int message_length,
+               HASH_HashType hashAlg )
+{
+    SECStatus hmac_status = SECFailure;
+    HMACContext *cx = NULL;
+    SECHashObject *hashObj = NULL;
+    unsigned int bytes_hashed = 0;
+
+    hashObj = (SECHashObject *) HASH_GetRawHashObject(hashAlg);
+ 
+    if (!hashObj) 
+        return( SECFailure );
+
+    cx = HMAC_Create(hashObj, secret_key, 
+                     secret_key_length, 
+                     PR_TRUE);  /* PR_TRUE for in FIPS mode */
+
+    if (cx == NULL) 
+        return( SECFailure );
+
+    HMAC_Begin(cx);
+    HMAC_Update(cx, message, message_length);
+    hmac_status = HMAC_Finish(cx, hmac_computed, &bytes_hashed, 
+                              hashObj->length);
+
+    HMAC_Destroy(cx, PR_TRUE);
+
+    return( hmac_status );
+}
+
+static SECStatus
+freebl_fips_HMAC_PowerUpSelfTest( void )
+{
+    static const PRUint8 HMAC_known_secret_key[] = {
+                         "Firefox and ThunderBird are awesome!"};
+
+    static const PRUint8 HMAC_known_secret_key_length 
+                         = sizeof HMAC_known_secret_key;
+
+    /* known SHA1 hmac (20 bytes) */
+    static const PRUint8 known_SHA1_hmac[] = {
+        0xd5, 0x85, 0xf6, 0x5b, 0x39, 0xfa, 0xb9, 0x05, 
+        0x3b, 0x57, 0x1d, 0x61, 0xe7, 0xb8, 0x84, 0x1e, 
+        0x5d, 0x0e, 0x1e, 0x11};
+
+    /* known SHA224 hmac (28 bytes) */
+    static const PRUint8 known_SHA224_hmac[] = {
+        0x1c, 0xc3, 0x06, 0x8e, 0xce, 0x37, 0x68, 0xfb, 
+        0x1a, 0x82, 0x4a, 0xbe, 0x2b, 0x00, 0x51, 0xf8,
+        0x9d, 0xb6, 0xe0, 0x90, 0x0d, 0x00, 0xc9, 0x64,
+        0x9a, 0xb8, 0x98, 0x4e};
+
+    /* known SHA256 hmac (32 bytes) */
+    static const PRUint8 known_SHA256_hmac[] = {
+        0x05, 0x75, 0x9a, 0x9e, 0x70, 0x5e, 0xe7, 0x44, 
+        0xe2, 0x46, 0x4b, 0x92, 0x22, 0x14, 0x22, 0xe0, 
+        0x1b, 0x92, 0x8a, 0x0c, 0xfe, 0xf5, 0x49, 0xe9, 
+        0xa7, 0x1b, 0x56, 0x7d, 0x1d, 0x29, 0x40, 0x48};        
+
+    /* known SHA384 hmac (48 bytes) */
+    static const PRUint8 known_SHA384_hmac[] = {
+        0xcd, 0x56, 0x14, 0xec, 0x05, 0x53, 0x06, 0x2b,
+        0x7e, 0x9c, 0x8a, 0x18, 0x5e, 0xea, 0xf3, 0x91,
+        0x33, 0xfb, 0x64, 0xf6, 0xe3, 0x9f, 0x89, 0x0b,
+        0xaf, 0xbe, 0x83, 0x4d, 0x3f, 0x3c, 0x43, 0x4d,
+        0x4a, 0x0c, 0x56, 0x98, 0xf8, 0xca, 0xb4, 0xaa,
+        0x9a, 0xf4, 0x0a, 0xaf, 0x4f, 0x69, 0xca, 0x87};
+
+    /* known SHA512 hmac (64 bytes) */
+    static const PRUint8 known_SHA512_hmac[] = {
+        0xf6, 0x0e, 0x97, 0x12, 0x00, 0x67, 0x6e, 0xb9,
+        0x0c, 0xb2, 0x63, 0xf0, 0x60, 0xac, 0x75, 0x62,
+        0x70, 0x95, 0x2a, 0x52, 0x22, 0xee, 0xdd, 0xd2,
+        0x71, 0xb1, 0xe8, 0x26, 0x33, 0xd3, 0x13, 0x27,
+        0xcb, 0xff, 0x44, 0xef, 0x87, 0x97, 0x16, 0xfb,
+        0xd3, 0x0b, 0x48, 0xbe, 0x12, 0x4e, 0xda, 0xb1,
+        0x89, 0x90, 0xfb, 0x06, 0x0c, 0xbe, 0xe5, 0xc4,
+        0xff, 0x24, 0x37, 0x3d, 0xc7, 0xe4, 0xe4, 0x37};
+
+    SECStatus    hmac_status;
+    PRUint8      hmac_computed[HASH_LENGTH_MAX]; 
+
+    /***************************************************/
+    /* HMAC SHA-1 Single-Round Known Answer HMAC Test. */
+    /***************************************************/
+
+    hmac_status = freebl_fips_HMAC(hmac_computed, 
+                                 HMAC_known_secret_key,
+                                 HMAC_known_secret_key_length,
+                                 known_hash_message,
+                                 FIPS_KNOWN_HASH_MESSAGE_LENGTH,
+                                 HASH_AlgSHA1); 
+
+    if( ( hmac_status != SECSuccess ) || 
+        ( PORT_Memcmp( hmac_computed, known_SHA1_hmac,
+                       SHA1_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    /***************************************************/
+    /* HMAC SHA-224 Single-Round Known Answer Test.    */
+    /***************************************************/
+
+    hmac_status = freebl_fips_HMAC(hmac_computed, 
+                                 HMAC_known_secret_key,
+                                 HMAC_known_secret_key_length,
+                                 known_hash_message,
+                                 FIPS_KNOWN_HASH_MESSAGE_LENGTH,
+                                 HASH_AlgSHA224);
+
+    if( ( hmac_status != SECSuccess ) || 
+        ( PORT_Memcmp( hmac_computed, known_SHA224_hmac,
+                       SHA224_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    /***************************************************/
+    /* HMAC SHA-256 Single-Round Known Answer Test.    */
+    /***************************************************/
+
+    hmac_status = freebl_fips_HMAC(hmac_computed, 
+                                 HMAC_known_secret_key,
+                                 HMAC_known_secret_key_length,
+                                 known_hash_message,
+                                 FIPS_KNOWN_HASH_MESSAGE_LENGTH,
+                                 HASH_AlgSHA256); 
+
+    if( ( hmac_status != SECSuccess ) || 
+        ( PORT_Memcmp( hmac_computed, known_SHA256_hmac,
+                       SHA256_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    /***************************************************/
+    /* HMAC SHA-384 Single-Round Known Answer Test.    */
+    /***************************************************/
+
+    hmac_status = freebl_fips_HMAC(hmac_computed,
+                                 HMAC_known_secret_key,
+                                 HMAC_known_secret_key_length,
+                                 known_hash_message,
+                                 FIPS_KNOWN_HASH_MESSAGE_LENGTH,
+                                 HASH_AlgSHA384);
+
+    if( ( hmac_status != SECSuccess ) ||
+        ( PORT_Memcmp( hmac_computed, known_SHA384_hmac,
+                       SHA384_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    /***************************************************/
+    /* HMAC SHA-512 Single-Round Known Answer Test.    */
+    /***************************************************/
+
+    hmac_status = freebl_fips_HMAC(hmac_computed,
+                                 HMAC_known_secret_key,
+                                 HMAC_known_secret_key_length,
+                                 known_hash_message,
+                                 FIPS_KNOWN_HASH_MESSAGE_LENGTH,
+                                 HASH_AlgSHA512);
+
+    if( ( hmac_status != SECSuccess ) ||
+        ( PORT_Memcmp( hmac_computed, known_SHA512_hmac,
+                       SHA512_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    return( SECSuccess );
+}
+
+static SECStatus
+freebl_fips_SHA_PowerUpSelfTest( void )
+{
+    /* SHA-1 Known Digest Message (160-bits). */
+    static const PRUint8 sha1_known_digest[] = {
+			       0x0a,0x6d,0x07,0xba,0x1e,0xbd,0x8a,0x1b,
+			       0x72,0xf6,0xc7,0x22,0xf1,0x27,0x9f,0xf0,
+			       0xe0,0x68,0x47,0x7a};
+
+    /* SHA-224 Known Digest Message (224-bits). */
+    static const PRUint8 sha224_known_digest[] = {
+        0x89,0x5e,0x7f,0xfd,0x0e,0xd8,0x35,0x6f,
+        0x64,0x6d,0xf2,0xde,0x5e,0xed,0xa6,0x7f, 
+        0x29,0xd1,0x12,0x73,0x42,0x84,0x95,0x4f, 
+        0x8e,0x08,0xe5,0xcb};
+
+    /* SHA-256 Known Digest Message (256-bits). */
+    static const PRUint8 sha256_known_digest[] = {
+        0x38,0xa9,0xc1,0xf0,0x35,0xf6,0x5d,0x61,
+        0x11,0xd4,0x0b,0xdc,0xce,0x35,0x14,0x8d,
+        0xf2,0xdd,0xaf,0xaf,0xcf,0xb7,0x87,0xe9,
+        0x96,0xa5,0xd2,0x83,0x62,0x46,0x56,0x79};
+ 
+    /* SHA-384 Known Digest Message (384-bits). */
+    static const PRUint8 sha384_known_digest[] = {
+        0x11,0xfe,0x1c,0x00,0x89,0x48,0xde,0xb3,
+        0x99,0xee,0x1c,0x18,0xb4,0x10,0xfb,0xfe,
+        0xe3,0xa8,0x2c,0xf3,0x04,0xb0,0x2f,0xc8,
+        0xa3,0xc4,0x5e,0xea,0x7e,0x60,0x48,0x7b,
+        0xce,0x2c,0x62,0xf7,0xbc,0xa7,0xe8,0xa3,
+        0xcf,0x24,0xce,0x9c,0xe2,0x8b,0x09,0x72};
+
+    /* SHA-512 Known Digest Message (512-bits). */
+    static const PRUint8 sha512_known_digest[] = {
+        0xc8,0xb3,0x27,0xf9,0x0b,0x24,0xc8,0xbf,
+        0x4c,0xba,0x33,0x54,0xf2,0x31,0xbf,0xdb,
+        0xab,0xfd,0xb3,0x15,0xd7,0xfa,0x48,0x99,
+        0x07,0x60,0x0f,0x57,0x41,0x1a,0xdd,0x28,
+        0x12,0x55,0x25,0xac,0xba,0x3a,0x99,0x12,
+        0x2c,0x7a,0x8f,0x75,0x3a,0xe1,0x06,0x6f,
+        0x30,0x31,0xc9,0x33,0xc6,0x1b,0x90,0x1a,
+        0x6c,0x98,0x9a,0x87,0xd0,0xb2,0xf8,0x07};
+
+    /* SHA-X variables. */
+    PRUint8        sha_computed_digest[HASH_LENGTH_MAX];
+    SECStatus      sha_status;
+
+    /*************************************************/
+    /* SHA-1 Single-Round Known Answer Hashing Test. */
+    /*************************************************/
+
+    sha_status = SHA1_HashBuf( sha_computed_digest, known_hash_message,
+                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
+ 
+    if( ( sha_status != SECSuccess ) ||
+        ( PORT_Memcmp( sha_computed_digest, sha1_known_digest,
+                       SHA1_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    /***************************************************/
+    /* SHA-224 Single-Round Known Answer Hashing Test. */
+    /***************************************************/
+
+    sha_status = SHA224_HashBuf( sha_computed_digest, known_hash_message,
+                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
+
+    if( ( sha_status != SECSuccess ) ||
+        ( PORT_Memcmp( sha_computed_digest, sha224_known_digest,
+                       SHA224_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    /***************************************************/
+    /* SHA-256 Single-Round Known Answer Hashing Test. */
+    /***************************************************/
+
+    sha_status = SHA256_HashBuf( sha_computed_digest, known_hash_message,
+                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
+
+    if( ( sha_status != SECSuccess ) ||
+        ( PORT_Memcmp( sha_computed_digest, sha256_known_digest,
+                       SHA256_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    /***************************************************/
+    /* SHA-384 Single-Round Known Answer Hashing Test. */
+    /***************************************************/
+
+    sha_status = SHA384_HashBuf( sha_computed_digest, known_hash_message,
+                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
+
+    if( ( sha_status != SECSuccess ) ||
+        ( PORT_Memcmp( sha_computed_digest, sha384_known_digest,
+                       SHA384_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    /***************************************************/
+    /* SHA-512 Single-Round Known Answer Hashing Test. */
+    /***************************************************/
+
+    sha_status = SHA512_HashBuf( sha_computed_digest, known_hash_message,
+                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
+
+    if( ( sha_status != SECSuccess ) ||
+        ( PORT_Memcmp( sha_computed_digest, sha512_known_digest,
+                       SHA512_LENGTH ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    return( SECSuccess );
+}
+
+
+static SECStatus
+freebl_fips_RSA_PowerUpSelfTest( void )
+{
+    /* RSA Known Modulus used in both Public/Private Key Values (2048-bits). */
+    static const PRUint8 rsa_modulus[FIPS_RSA_MODULUS_LENGTH] = {
+                            0xb8, 0x15, 0x00, 0x33, 0xda, 0x0c, 0x9d, 0xa5,
+                            0x14, 0x8c, 0xde, 0x1f, 0x23, 0x07, 0x54, 0xe2,
+                            0xc6, 0xb9, 0x51, 0x04, 0xc9, 0x65, 0x24, 0x6e,
+                            0x0a, 0x46, 0x34, 0x5c, 0x37, 0x86, 0x6b, 0x88,
+                            0x24, 0x27, 0xac, 0xa5, 0x02, 0x79, 0xfb, 0xed,
+                            0x75, 0xc5, 0x3f, 0x6e, 0xdf, 0x05, 0x5f, 0x0f,
+                            0x20, 0x70, 0xa0, 0x5b, 0x85, 0xdb, 0xac, 0xb9,
+                            0x5f, 0x02, 0xc2, 0x64, 0x1e, 0x84, 0x5b, 0x3e,
+                            0xad, 0xbf, 0xf6, 0x2e, 0x51, 0xd6, 0xad, 0xf7,
+                            0xa7, 0x86, 0x75, 0x86, 0xec, 0xa7, 0xe1, 0xf7,
+                            0x08, 0xbf, 0xdc, 0x56, 0xb1, 0x3b, 0xca, 0xd8,
+                            0xfc, 0x51, 0xdf, 0x9a, 0x2a, 0x37, 0x06, 0xf2,
+                            0xd1, 0x6b, 0x9a, 0x5e, 0x2a, 0xe5, 0x20, 0x57,
+                            0x35, 0x9f, 0x1f, 0x98, 0xcf, 0x40, 0xc7, 0xd6,
+                            0x98, 0xdb, 0xde, 0xf5, 0x64, 0x53, 0xf7, 0x9d,
+                            0x45, 0xf3, 0xd6, 0x78, 0xb9, 0xe3, 0xa3, 0x20,
+                            0xcd, 0x79, 0x43, 0x35, 0xef, 0xd7, 0xfb, 0xb9,
+                            0x80, 0x88, 0x27, 0x2f, 0x63, 0xa8, 0x67, 0x3d,
+                            0x4a, 0xfa, 0x06, 0xc6, 0xd2, 0x86, 0x0b, 0xa7,
+                            0x28, 0xfd, 0xe0, 0x1e, 0x93, 0x4b, 0x17, 0x2e,
+                            0xb0, 0x11, 0x6f, 0xc6, 0x2b, 0x98, 0x0f, 0x15,
+                            0xe3, 0x87, 0x16, 0x7a, 0x7c, 0x67, 0x3e, 0x12,
+                            0x2b, 0xf8, 0xbe, 0x48, 0xc1, 0x97, 0x47, 0xf4,
+                            0x1f, 0x81, 0x80, 0x12, 0x28, 0xe4, 0x7b, 0x1e,
+                            0xb7, 0x00, 0xa4, 0xde, 0xaa, 0xfb, 0x0f, 0x77,
+                            0x84, 0xa3, 0xd6, 0xb2, 0x03, 0x48, 0xdd, 0x53,
+                            0x8b, 0x46, 0x41, 0x28, 0x52, 0xc4, 0x53, 0xf0,
+                            0x1c, 0x95, 0xd9, 0x36, 0xe0, 0x0f, 0x26, 0x46,
+                            0x9c, 0x61, 0x0e, 0x80, 0xca, 0x86, 0xaf, 0x39,
+                            0x95, 0xe5, 0x60, 0x43, 0x61, 0x3e, 0x2b, 0xb4,
+                            0xe8, 0xbd, 0x8d, 0x77, 0x62, 0xf5, 0x32, 0x43,
+                            0x2f, 0x4b, 0x65, 0x82, 0x14, 0xdd, 0x29, 0x5b};
+
+    /* RSA Known Public Key Values (24-bits). */
+    static const PRUint8 rsa_public_exponent[FIPS_RSA_PUBLIC_EXPONENT_LENGTH] 
+                                                       = { 0x01, 0x00, 0x01 };
+    /* RSA Known Private Key Values (version                 is    8-bits), */
+    /*                              (private exponent        is 2048-bits), */
+    /*                              (private prime0          is 1024-bits), */
+    /*                              (private prime1          is 1024-bits), */
+    /*                              (private prime exponent0 is 1024-bits), */
+    /*                              (private prime exponent1 is 1024-bits), */
+    /*                          and (private coefficient     is 1024-bits). */
+    static const PRUint8 rsa_version[] = { 0x00 };
+
+    static const PRUint8 rsa_private_exponent[FIPS_RSA_PRIVATE_EXPONENT_LENGTH]
+                         = {0x29, 0x08, 0x05, 0x53, 0x89, 0x76, 0xe6, 0x6c,
+                            0xb5, 0x77, 0xf0, 0xca, 0xdf, 0xf3, 0xf2, 0x67,
+                            0xda, 0x03, 0xd4, 0x9b, 0x4c, 0x88, 0xce, 0xe5,
+                            0xf8, 0x44, 0x4d, 0xc7, 0x80, 0x58, 0xe5, 0xff,
+                            0x22, 0x8f, 0xf5, 0x5b, 0x92, 0x81, 0xbe, 0x35,
+                            0xdf, 0xda, 0x67, 0x99, 0x3e, 0xfc, 0xe3, 0x83,
+                            0x6b, 0xa7, 0xaf, 0x16, 0xb7, 0x6f, 0x8f, 0xc0,
+                            0x81, 0xfd, 0x0b, 0x77, 0x65, 0x95, 0xfb, 0x00,
+                            0xad, 0x99, 0xec, 0x35, 0xc6, 0xe8, 0x23, 0x3e,
+                            0xe0, 0x88, 0x88, 0x09, 0xdb, 0x16, 0x50, 0xb7,
+                            0xcf, 0xab, 0x74, 0x61, 0x9e, 0x7f, 0xc5, 0x67,
+                            0x38, 0x56, 0xc7, 0x90, 0x85, 0x78, 0x5e, 0x84,
+                            0x21, 0x49, 0xea, 0xce, 0xb2, 0xa0, 0xff, 0xe4,
+                            0x70, 0x7f, 0x57, 0x7b, 0xa8, 0x36, 0xb8, 0x54,
+                            0x8d, 0x1d, 0xf5, 0x44, 0x9d, 0x68, 0x59, 0xf9,
+                            0x24, 0x6e, 0x85, 0x8f, 0xc3, 0x5f, 0x8a, 0x2c,
+                            0x94, 0xb7, 0xbc, 0x0e, 0xa5, 0xef, 0x93, 0x06,
+                            0x38, 0xcd, 0x07, 0x0c, 0xae, 0xb8, 0x44, 0x1a,
+                            0xd8, 0xe7, 0xf5, 0x9a, 0x1e, 0x9c, 0x18, 0xc7,
+                            0x6a, 0xc2, 0x7f, 0x28, 0x01, 0x4f, 0xb4, 0xb8,
+                            0x90, 0x97, 0x5a, 0x43, 0x38, 0xad, 0xe8, 0x95,
+                            0x68, 0x83, 0x1a, 0x1b, 0x10, 0x07, 0xe6, 0x02,
+                            0x52, 0x1f, 0xbf, 0x76, 0x6b, 0x46, 0xd6, 0xfb,
+                            0xc3, 0xbe, 0xb5, 0xac, 0x52, 0x53, 0x01, 0x1c,
+                            0xf3, 0xc5, 0xeb, 0x64, 0xf2, 0x1e, 0xc4, 0x38,
+                            0xe9, 0xaa, 0xd9, 0xc3, 0x72, 0x51, 0xa5, 0x44,
+                            0x58, 0x69, 0x0b, 0x1b, 0x98, 0x7f, 0xf2, 0x23,
+                            0xff, 0xeb, 0xf0, 0x75, 0x24, 0xcf, 0xc5, 0x1e,
+                            0xb8, 0x6a, 0xc5, 0x2f, 0x4f, 0x23, 0x50, 0x7d,
+                            0x15, 0x9d, 0x19, 0x7a, 0x0b, 0x82, 0xe0, 0x21,
+                            0x5b, 0x5f, 0x9d, 0x50, 0x2b, 0x83, 0xe4, 0x48,
+                            0xcc, 0x39, 0xe5, 0xfb, 0x13, 0x7b, 0x6f, 0x81 };
+
+    static const PRUint8 rsa_prime0[FIPS_RSA_PRIME0_LENGTH]   = {
+                            0xe4, 0xbf, 0x21, 0x62, 0x9b, 0xa9, 0x77, 0x40,
+                            0x8d, 0x2a, 0xce, 0xa1, 0x67, 0x5a, 0x4c, 0x96,
+                            0x45, 0x98, 0x67, 0xbd, 0x75, 0x22, 0x33, 0x6f,
+                            0xe6, 0xcb, 0x77, 0xde, 0x9e, 0x97, 0x7d, 0x96,
+                            0x8c, 0x5e, 0x5d, 0x34, 0xfb, 0x27, 0xfc, 0x6d,
+                            0x74, 0xdb, 0x9d, 0x2e, 0x6d, 0xf6, 0xea, 0xfc,
+                            0xce, 0x9e, 0xda, 0xa7, 0x25, 0xa2, 0xf4, 0x58,
+                            0x6d, 0x0a, 0x3f, 0x01, 0xc2, 0xb4, 0xab, 0x38,
+                            0xc1, 0x14, 0x85, 0xb6, 0xfa, 0x94, 0xc3, 0x85,
+                            0xf9, 0x3c, 0x2e, 0x96, 0x56, 0x01, 0xe7, 0xd6,
+                            0x14, 0x71, 0x4f, 0xfb, 0x4c, 0x85, 0x52, 0xc4,
+                            0x61, 0x1e, 0xa5, 0x1e, 0x96, 0x13, 0x0d, 0x8f,
+                            0x66, 0xae, 0xa0, 0xcd, 0x7d, 0x25, 0x66, 0x19,
+                            0x15, 0xc2, 0xcf, 0xc3, 0x12, 0x3c, 0xe8, 0xa4,
+                            0x52, 0x4c, 0xcb, 0x28, 0x3c, 0xc4, 0xbf, 0x95,
+                            0x33, 0xe3, 0x81, 0xea, 0x0c, 0x6c, 0xa2, 0x05};
+    static const PRUint8 rsa_prime1[FIPS_RSA_PRIME1_LENGTH]   = {
+                            0xce, 0x03, 0x94, 0xf4, 0xa9, 0x2c, 0x1e, 0x06,
+                            0xe7, 0x40, 0x30, 0x01, 0xf7, 0xbb, 0x68, 0x8c,
+                            0x27, 0xd2, 0x15, 0xe3, 0x28, 0x49, 0x5b, 0xa8,
+                            0xc1, 0x9a, 0x42, 0x7e, 0x31, 0xf9, 0x08, 0x34,
+                            0x81, 0xa2, 0x0f, 0x04, 0x61, 0x34, 0xe3, 0x36,
+                            0x92, 0xb1, 0x09, 0x2b, 0xe9, 0xef, 0x84, 0x88,
+                            0xbe, 0x9c, 0x98, 0x60, 0xa6, 0x60, 0x84, 0xe9,
+                            0x75, 0x6f, 0xcc, 0x81, 0xd1, 0x96, 0xef, 0xdd,
+                            0x2e, 0xca, 0xc4, 0xf5, 0x42, 0xfb, 0x13, 0x2b,
+                            0x57, 0xbf, 0x14, 0x5e, 0xc2, 0x7f, 0x77, 0x35,
+                            0x29, 0xc4, 0xe5, 0xe0, 0xf9, 0x6d, 0x15, 0x4a,
+                            0x42, 0x56, 0x1c, 0x3e, 0x0c, 0xc5, 0xce, 0x70,
+                            0x08, 0x63, 0x1e, 0x73, 0xdb, 0x7e, 0x74, 0x05,
+                            0x32, 0x01, 0xc6, 0x36, 0x32, 0x75, 0x6b, 0xed,
+                            0x9d, 0xfe, 0x7c, 0x7e, 0xa9, 0x57, 0xb4, 0xe9,
+                            0x22, 0xe4, 0xe7, 0xfe, 0x36, 0x07, 0x9b, 0xdf};
+    static const PRUint8 rsa_exponent0[FIPS_RSA_EXPONENT0_LENGTH] = {
+                            0x04, 0x5a, 0x3a, 0xa9, 0x64, 0xaa, 0xd9, 0xd1,
+                            0x09, 0x9e, 0x99, 0xe5, 0xea, 0x50, 0x86, 0x8a,
+                            0x89, 0x72, 0x77, 0xee, 0xdb, 0xee, 0xb5, 0xa9,
+                            0xd8, 0x6b, 0x60, 0xb1, 0x84, 0xb4, 0xff, 0x37,
+                            0xc1, 0x1d, 0xfe, 0x8a, 0x06, 0x89, 0x61, 0x3d,
+                            0x37, 0xef, 0x01, 0xd3, 0xa3, 0x56, 0x02, 0x6c,
+                            0xa3, 0x05, 0xd4, 0xc5, 0x3f, 0x6b, 0x15, 0x59,
+                            0x25, 0x61, 0xff, 0x86, 0xea, 0x0c, 0x84, 0x01,
+                            0x85, 0x72, 0xfd, 0x84, 0x58, 0xca, 0x41, 0xda,
+                            0x27, 0xbe, 0xe4, 0x68, 0x09, 0xe4, 0xe9, 0x63,
+                            0x62, 0x6a, 0x31, 0x8a, 0x67, 0x8f, 0x55, 0xde,
+                            0xd4, 0xb6, 0x3f, 0x90, 0x10, 0x6c, 0xf6, 0x62,
+                            0x17, 0x23, 0x15, 0x7e, 0x33, 0x76, 0x65, 0xb5,
+                            0xee, 0x7b, 0x11, 0x76, 0xf5, 0xbe, 0xe0, 0xf2,
+                            0x57, 0x7a, 0x8c, 0x97, 0x0c, 0x68, 0xf5, 0xf8,
+                            0x41, 0xcf, 0x7f, 0x66, 0x53, 0xac, 0x31, 0x7d};
+    static const PRUint8 rsa_exponent1[FIPS_RSA_EXPONENT1_LENGTH] = {
+                            0x93, 0x54, 0x14, 0x6e, 0x73, 0x9d, 0x4d, 0x4b,
+                            0xfa, 0x8c, 0xf8, 0xc8, 0x2f, 0x76, 0x22, 0xea,
+                            0x38, 0x80, 0x11, 0x8f, 0x05, 0xfc, 0x90, 0x44,
+                            0x3b, 0x50, 0x2a, 0x45, 0x3d, 0x4f, 0xaf, 0x02,
+                            0x7d, 0xc2, 0x7b, 0xa2, 0xd2, 0x31, 0x94, 0x5c,
+                            0x2e, 0xc3, 0xd4, 0x9f, 0x47, 0x09, 0x37, 0x6a,
+                            0xe3, 0x85, 0xf1, 0xa3, 0x0c, 0xd8, 0xf1, 0xb4,
+                            0x53, 0x7b, 0xc4, 0x71, 0x02, 0x86, 0x42, 0xbb,
+                            0x96, 0xff, 0x03, 0xa3, 0xb2, 0x67, 0x03, 0xea,
+                            0x77, 0x31, 0xfb, 0x4b, 0x59, 0x24, 0xf7, 0x07,
+                            0x59, 0xfb, 0xa9, 0xba, 0x1e, 0x26, 0x58, 0x97,
+                            0x66, 0xa1, 0x56, 0x49, 0x39, 0xb1, 0x2c, 0x55,
+                            0x0a, 0x6a, 0x78, 0x18, 0xba, 0xdb, 0xcf, 0xf4,
+                            0xf7, 0x32, 0x35, 0xa2, 0x04, 0xab, 0xdc, 0xa7,
+                            0x6d, 0xd9, 0xd5, 0x06, 0x6f, 0xec, 0x7d, 0x40,
+                            0x4c, 0xe8, 0x0e, 0xd0, 0xc9, 0xaa, 0xdf, 0x59};
+    static const PRUint8 rsa_coefficient[FIPS_RSA_COEFFICIENT_LENGTH] = {
+                            0x17, 0xd7, 0xf5, 0x0a, 0xf0, 0x68, 0x97, 0x96,
+                            0xc4, 0x29, 0x18, 0x77, 0x9a, 0x1f, 0xe3, 0xf3,
+                            0x12, 0x13, 0x0f, 0x7e, 0x7b, 0xb9, 0xc1, 0x91,
+                            0xf9, 0xc7, 0x08, 0x56, 0x5c, 0xa4, 0xbc, 0x83,
+                            0x71, 0xf9, 0x78, 0xd9, 0x2b, 0xec, 0xfe, 0x6b,
+                            0xdc, 0x2f, 0x63, 0xc9, 0xcd, 0x50, 0x14, 0x5b,
+                            0xd3, 0x6e, 0x85, 0x4d, 0x0c, 0xa2, 0x0b, 0xa0,
+                            0x09, 0xb6, 0xca, 0x34, 0x9c, 0xc2, 0xc1, 0x4a,
+                            0xb0, 0xbc, 0x45, 0x93, 0xa5, 0x7e, 0x99, 0xb5,
+                            0xbd, 0xe4, 0x69, 0x29, 0x08, 0x28, 0xd2, 0xcd,
+                            0xab, 0x24, 0x78, 0x48, 0x41, 0x26, 0x0b, 0x37,
+                            0xa3, 0x43, 0xd1, 0x95, 0x1a, 0xd6, 0xee, 0x22,
+                            0x1c, 0x00, 0x0b, 0xc2, 0xb7, 0xa4, 0xa3, 0x21,
+                            0xa9, 0xcd, 0xe4, 0x69, 0xd3, 0x45, 0x02, 0xb1,
+                            0xb7, 0x3a, 0xbf, 0x51, 0x35, 0x1b, 0x78, 0xc2,
+                            0xcf, 0x0c, 0x0d, 0x60, 0x09, 0xa9, 0x44, 0x02};
+
+    /* RSA Known Plaintext Message (1024-bits). */
+    static const PRUint8 rsa_known_plaintext_msg[FIPS_RSA_MESSAGE_LENGTH] = {
+                                         "Known plaintext message utilized"
+                                         "for RSA Encryption &  Decryption"
+                                         "blocks SHA256, SHA384  and      "
+                                         "SHA512 RSA Signature KAT tests. "
+                                         "Known plaintext message utilized"
+                                         "for RSA Encryption &  Decryption"
+                                         "blocks SHA256, SHA384  and      "
+                                         "SHA512 RSA Signature KAT  tests."};
+
+    /* RSA Known Ciphertext (2048-bits). */
+    static const PRUint8 rsa_known_ciphertext[] = {
+                            0x04, 0x12, 0x46, 0xe3, 0x6a, 0xee, 0xde, 0xdd,
+                            0x49, 0xa1, 0xd9, 0x83, 0xf7, 0x35, 0xf9, 0x70,
+                            0x88, 0x03, 0x2d, 0x01, 0x8b, 0xd1, 0xbf, 0xdb,
+                            0xe5, 0x1c, 0x85, 0xbe, 0xb5, 0x0b, 0x48, 0x45,
+                            0x7a, 0xf0, 0xa0, 0xe3, 0xa2, 0xbb, 0x4b, 0xf6,
+                            0x27, 0xd0, 0x1b, 0x12, 0xe3, 0x77, 0x52, 0x34,
+                            0x9e, 0x8e, 0x03, 0xd2, 0xf8, 0x79, 0x6e, 0x39,
+                            0x79, 0x53, 0x3c, 0x44, 0x14, 0x94, 0xbb, 0x8d,
+                            0xaa, 0x14, 0x44, 0xa0, 0x7b, 0xa5, 0x8c, 0x93,
+                            0x5f, 0x99, 0xa4, 0xa3, 0x6e, 0x7a, 0x38, 0x40,
+                            0x78, 0xfa, 0x36, 0x91, 0x5e, 0x9a, 0x9c, 0xba,
+                            0x1e, 0xd4, 0xf9, 0xda, 0x4b, 0x0f, 0xa8, 0xa3,
+                            0x1c, 0xf3, 0x3a, 0xd1, 0xa5, 0xb4, 0x51, 0x16,
+                            0xed, 0x4b, 0xcf, 0xec, 0x93, 0x7b, 0x90, 0x21,
+                            0xbc, 0x3a, 0xf4, 0x0b, 0xd1, 0x3a, 0x2b, 0xba,
+                            0xa6, 0x7d, 0x5b, 0x53, 0xd8, 0x64, 0xf9, 0x29,
+                            0x7b, 0x7f, 0x77, 0x3e, 0x51, 0x4c, 0x9a, 0x94,
+                            0xd2, 0x4b, 0x4a, 0x8d, 0x61, 0x74, 0x97, 0xae,
+                            0x53, 0x6a, 0xf4, 0x90, 0xc2, 0x2c, 0x49, 0xe2,
+                            0xfa, 0xeb, 0x91, 0xc5, 0xe5, 0x83, 0x13, 0xc9,
+                            0x44, 0x4b, 0x95, 0x2c, 0x57, 0x70, 0x15, 0x5c,
+                            0x64, 0x8d, 0x1a, 0xfd, 0x2a, 0xc7, 0xb2, 0x9c,
+                            0x5c, 0x99, 0xd3, 0x4a, 0xfd, 0xdd, 0xf6, 0x82,
+                            0x87, 0x8c, 0x5a, 0xc4, 0xa8, 0x0d, 0x2a, 0xef,
+                            0xc3, 0xa2, 0x7e, 0x8e, 0x67, 0x9f, 0x6f, 0x63,
+                            0xdb, 0xbb, 0x1d, 0x31, 0xc4, 0xbb, 0xbc, 0x13,
+                            0x3f, 0x54, 0xc6, 0xf6, 0xc5, 0x28, 0x32, 0xab,
+                            0x96, 0x42, 0x10, 0x36, 0x40, 0x92, 0xbb, 0x57,
+                            0x55, 0x38, 0xf5, 0x43, 0x7e, 0x43, 0xc4, 0x65,
+                            0x47, 0x64, 0xaa, 0x0f, 0x4c, 0xe9, 0x49, 0x16,
+                            0xec, 0x6a, 0x50, 0xfd, 0x14, 0x49, 0xca, 0xdb,
+                            0x44, 0x54, 0xca, 0xbe, 0xa3, 0x0e, 0x5f, 0xef};
+
+
+    static const RSAPublicKey    bl_public_key = { NULL,
+      { FIPS_RSA_TYPE, (unsigned char *)rsa_modulus,         
+                                        FIPS_RSA_MODULUS_LENGTH },
+      { FIPS_RSA_TYPE, (unsigned char *)rsa_public_exponent, 
+                                        FIPS_RSA_PUBLIC_EXPONENT_LENGTH }
+    };
+    static const RSAPrivateKey   bl_private_key = { NULL,
+      { FIPS_RSA_TYPE, (unsigned char *)rsa_version,          
+                                        FIPS_RSA_PRIVATE_VERSION_LENGTH },
+      { FIPS_RSA_TYPE, (unsigned char *)rsa_modulus,          
+                                        FIPS_RSA_MODULUS_LENGTH },
+      { FIPS_RSA_TYPE, (unsigned char *)rsa_public_exponent,  
+                                        FIPS_RSA_PUBLIC_EXPONENT_LENGTH },
+      { FIPS_RSA_TYPE, (unsigned char *)rsa_private_exponent, 
+                                        FIPS_RSA_PRIVATE_EXPONENT_LENGTH },
+      { FIPS_RSA_TYPE, (unsigned char *)rsa_prime0,           
+                                        FIPS_RSA_PRIME0_LENGTH },
+      { FIPS_RSA_TYPE, (unsigned char *)rsa_prime1,           
+                                        FIPS_RSA_PRIME1_LENGTH },
+      { FIPS_RSA_TYPE, (unsigned char *)rsa_exponent0,        
+                                        FIPS_RSA_EXPONENT0_LENGTH },
+      { FIPS_RSA_TYPE, (unsigned char *)rsa_exponent1,        
+                                        FIPS_RSA_EXPONENT1_LENGTH },
+      { FIPS_RSA_TYPE, (unsigned char *)rsa_coefficient,      
+                                        FIPS_RSA_COEFFICIENT_LENGTH }
+    };
+
+    /* RSA variables. */
+    SECStatus             rsa_status;
+    RSAPublicKey	 rsa_public_key;
+    RSAPrivateKey	 rsa_private_key;
+
+    PRUint8               rsa_computed_ciphertext[FIPS_RSA_ENCRYPT_LENGTH];
+    PRUint8               rsa_computed_plaintext[FIPS_RSA_DECRYPT_LENGTH];
+
+    rsa_public_key = bl_public_key;
+    rsa_private_key = bl_private_key;
+
+    /**************************************************/
+    /* RSA Single-Round Known Answer Encryption Test. */
+    /**************************************************/
+
+    /* Perform RSA Public Key Encryption. */
+    rsa_status = RSA_PublicKeyOp(&rsa_public_key,
+                                 rsa_computed_ciphertext,
+                                 rsa_known_plaintext_msg);
+
+    if( ( rsa_status != SECSuccess ) ||
+        ( PORT_Memcmp( rsa_computed_ciphertext, rsa_known_ciphertext,
+                       FIPS_RSA_ENCRYPT_LENGTH ) != 0 ) )
+        goto rsa_loser;
+
+    /**************************************************/
+    /* RSA Single-Round Known Answer Decryption Test. */
+    /**************************************************/
+
+    /* Perform RSA Private Key Decryption. */
+    rsa_status = RSA_PrivateKeyOp(&rsa_private_key,
+                                  rsa_computed_plaintext,
+                                  rsa_known_ciphertext);
+
+    if( ( rsa_status != SECSuccess ) ||
+        ( PORT_Memcmp( rsa_computed_plaintext, rsa_known_plaintext_msg,
+                       FIPS_RSA_DECRYPT_LENGTH ) != 0 ) )
+        goto rsa_loser;
+
+    return( SECSuccess );
+
+rsa_loser:
+
+    PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+    return( SECFailure );
+}
+
+#ifdef NSS_ENABLE_ECC
+
+static SECStatus
+freebl_fips_ECDSA_Test(ECParams *ecparams, 
+                     const PRUint8 *knownSignature, 
+                     unsigned int knownSignatureLen) {
+
+    /* ECDSA Known Seed info for curves nistp256 and nistk283  */
+    static const PRUint8 ecdsa_Known_Seed[] = {
+                            0x6a, 0x9b, 0xf6, 0xf7, 0xce, 0xed, 0x79, 0x11,
+                            0xf0, 0xc7, 0xc8, 0x9a, 0xa5, 0xd1, 0x57, 0xb1,
+                            0x7b, 0x5a, 0x3b, 0x76, 0x4e, 0x7b, 0x7c, 0xbc,
+                            0xf2, 0x76, 0x1c, 0x1c, 0x7f, 0xc5, 0x53, 0x2f};
+
+    static const PRUint8 msg[] = {
+                            "Firefox and ThunderBird are awesome!"};
+
+    unsigned char sha1[SHA1_LENGTH];  /* SHA-1 hash (160 bits) */
+    unsigned char sig[2*MAX_ECKEY_LEN];
+    SECItem signature, digest;
+    ECPrivateKey *ecdsa_private_key = NULL;
+    ECPublicKey ecdsa_public_key;
+    SECStatus ecdsaStatus = SECSuccess;
+
+    /* Generates a new EC key pair. The private key is a supplied
+     * random value (in seed) and the public key is the result of 
+     * performing a scalar point multiplication of that value with 
+     * the curve's base point.
+     */
+    ecdsaStatus = EC_NewKeyFromSeed(ecparams, &ecdsa_private_key, 
+                                   ecdsa_Known_Seed, 
+                                   sizeof(ecdsa_Known_Seed));
+    if (ecdsaStatus != SECSuccess) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+
+    /* construct public key from private key. */
+    ecdsa_public_key.ecParams = ecdsa_private_key->ecParams;
+    ecdsa_public_key.publicValue = ecdsa_private_key->publicValue;
+
+    /* validate public key value */
+    ecdsaStatus = EC_ValidatePublicKey(&ecdsa_public_key.ecParams, 
+                                       &ecdsa_public_key.publicValue);
+    if (ecdsaStatus != SECSuccess) {
+        goto loser;
+    }
+
+    /* validate public key value */
+    ecdsaStatus = EC_ValidatePublicKey(&ecdsa_private_key->ecParams, 
+                                       &ecdsa_private_key->publicValue);
+    if (ecdsaStatus != SECSuccess) {
+        goto loser;
+    }
+
+    /***************************************************/
+    /* ECDSA Single-Round Known Answer Signature Test. */
+    /***************************************************/
+    
+    ecdsaStatus = SHA1_HashBuf(sha1, msg, sizeof msg);
+    if (ecdsaStatus != SECSuccess) {
+        goto loser;
+    }
+    digest.type = siBuffer;
+    digest.data = sha1;
+    digest.len = SHA1_LENGTH;
+    
+    memset(sig, 0, sizeof sig);
+    signature.type = siBuffer;
+    signature.data = sig;
+    signature.len = sizeof sig;
+    
+    ecdsaStatus = ECDSA_SignDigestWithSeed(ecdsa_private_key, &signature, 
+                         &digest, ecdsa_Known_Seed, sizeof ecdsa_Known_Seed);
+    if (ecdsaStatus != SECSuccess) {
+        goto loser;
+    }
+
+    if( ( signature.len != knownSignatureLen ) ||
+        ( PORT_Memcmp( signature.data, knownSignature,
+                    knownSignatureLen ) != 0 ) ) {
+        ecdsaStatus = SECFailure;
+        goto loser;
+    }
+    
+    /******************************************************/
+    /* ECDSA Single-Round Known Answer Verification Test. */
+    /******************************************************/
+
+    /* Perform ECDSA verification process. */
+    ecdsaStatus = ECDSA_VerifyDigest(&ecdsa_public_key, &signature, &digest);
+
+loser:
+    /* free the memory for the private key arena*/
+    if (ecdsa_private_key != NULL) {
+        PORT_FreeArena(ecdsa_private_key->ecParams.arena, PR_FALSE);
+    }
+
+    if (ecdsaStatus != SECSuccess) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+        return( SECFailure );
+    }
+    return( SECSuccess );
+}
+
+static SECStatus
+freebl_fips_ECDSA_PowerUpSelfTest() {
+    
+    /* ECDSA Known curve nistp256 == ECCCurve_X9_62_PRIME_256V1 params */
+    static const unsigned char p256_prime[] = {
+	0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,
+	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
+	0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
+    static const unsigned char p256_a[] = {
+	0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,
+	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
+	0xFF,0xFF,0xFF,0xFF,0xFF,0xFC};
+    static const unsigned char p256_b[] = {
+	0x5A,0xC6,0x35,0xD8,0xAA,0x3A,0x93,0xE7,0xB3,0xEB,0xBD,0x55,0x76,
+	0x98,0x86,0xBC,0x65,0x1D,0x06,0xB0,0xCC,0x53,0xB0,0xF6,0x3B,0xCE,
+	0x3C,0x3E,0x27,0xD2,0x60,0x4B};
+    static const unsigned char p256_base[] = { 0x04,
+	0x6B,0x17,0xD1,0xF2,0xE1,0x2C,0x42,0x47,0xF8,0xBC,0xE6,0xE5,0x63,
+	0xA4,0x40,0xF2,0x77,0x03,0x7D,0x81,0x2D,0xEB,0x33,0xA0,0xF4,0xA1,
+	0x39,0x45,0xD8,0x98,0xC2,0x96,
+	0x4F,0xE3,0x42,0xE2,0xFE,0x1A,0x7F,0x9B,0x8E,0xE7,0xEB,0x4A,0x7C,
+	0x0F,0x9E,0x16,0x2B,0xCE,0x33,0x57,0x6B,0x31,0x5E,0xCE,0xCB,0xB6,
+	0x40,0x68,0x37,0xBF,0x51,0xF5};
+    static const unsigned char p256_order[] = {
+	0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,
+	0xFF,0xFF,0xFF,0xBC,0xE6,0xFA,0xAD,0xA7,0x17,0x9E,0x84,0xF3,0xB9,
+	0xCA,0xC2,0xFC,0x63,0x25,0x51};
+    static const unsigned char p256_encoding[] = {
+	0x06,0x08,0x2a,0x86,0x48,0xce,0x3d,0x03, 0x01,0x07 };
+    static const ECParams ecdsa_known_P256_Params = {
+		NULL, ec_params_named,       /* arena, type */
+		/* fieldID */ 
+                {   256 , ec_field_GFp,   /* size and type */
+		    {{siBuffer, (unsigned char*)p256_prime, sizeof(p256_prime)}}, /* u.prime */
+		    0, 0, 0 },
+		/* curve */
+		{ 
+		/* a = curvea b = curveb */
+		    /* curve.a */
+		    { siBuffer, (unsigned char*)p256_a, sizeof(p256_a) },
+		    /* curve.b */
+		    { siBuffer, (unsigned char*)p256_b, sizeof(p256_b) },
+		    /* curve.seed */
+		    { siBuffer, NULL, 0}
+		},
+		/* base  = 04xy*/
+		{ siBuffer, (unsigned char*)p256_base, sizeof(p256_base) },
+		/* order */
+		{ siBuffer, (unsigned char*)p256_order, sizeof(p256_order) },
+		1,/* cofactor */
+		/* DEREncoding */
+		{ siBuffer, (unsigned char*)p256_encoding, sizeof(p256_encoding)}, 
+		ECCurve_X9_62_PRIME_256V1,
+		/* curveOID */
+		{ siBuffer, (unsigned char*)(p256_encoding)+2, sizeof(p256_encoding)-2}, 
+    };
+	
+
+    static const PRUint8 ecdsa_known_P256_signature[] = {
+                            0x07,0xb1,0xcb,0x57,0x20,0xa7,0x10,0xd6, 
+                            0x9d,0x37,0x4b,0x1c,0xdc,0x35,0x90,0xff, 
+                            0x1a,0x2d,0x98,0x95,0x1b,0x2f,0xeb,0x7f, 
+                            0xbb,0x81,0xca,0xc0,0x69,0x75,0xea,0xc5,
+                            0x59,0x6a,0x62,0x49,0x3d,0x50,0xc9,0xe1, 
+                            0x27,0x3b,0xff,0x9b,0x13,0x66,0x67,0xdd, 
+                            0x7d,0xd1,0x0d,0x2d,0x7c,0x44,0x04,0x1b, 
+                            0x16,0x21,0x12,0xc5,0xcb,0xbd,0x9e,0x75};
+
+#ifdef NSS_ECC_MORE_THAN_SUITE_B
+    /* ECDSA Known curve nistk283 == SEC_OID_SECG_EC_SECT283K1 params */
+    static const unsigned char k283_poly[] = {
+	0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0xA1};
+    static const unsigned char k283_a[] = {
+	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+    static const unsigned char k283_b[] = {
+	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
+	0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01};
+    static const unsigned char k283_base[] = { 0x04,
+	0x05,0x03,0x21,0x3F,0x78,0xCA,0x44,0x88,0x3F,0x1A,0x3B,0x81,0x62,
+	0xF1,0x88,0xE5,0x53,0xCD,0x26,0x5F,0x23,0xC1,0x56,0x7A,0x16,0x87,
+	0x69,0x13,0xB0,0xC2,0xAC,0x24,0x58,0x49,0x28,0x36,
+        0x01,0xCC,0xDA,0x38,0x0F,0x1C,0x9E,0x31,0x8D,0x90,0xF9,0x5D,0x07,
+	0xE5,0x42,0x6F,0xE8,0x7E,0x45,0xC0,0xE8,0x18,0x46,0x98,0xE4,0x59,
+	0x62,0x36,0x4E,0x34,0x11,0x61,0x77,0xDD,0x22,0x59};
+    static const unsigned char k283_order[] = {
+ 	0x01,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
+	0xFF,0xFF,0xFF,0xFF,0xFF,0xE9,0xAE,0x2E,0xD0,0x75,0x77,0x26,0x5D,
+	0xFF,0x7F,0x94,0x45,0x1E,0x06,0x1E,0x16,0x3C,0x61};
+    static const PRUint8 k283_encoding[] = {
+	0x06,0x05,0x2b,0x81,0x04,0x00,0x10};
+
+    static const ECParams ecdsa_known_K283_Params = {
+		NULL, ec_params_named,       /* arena, type */
+		/* fieldID */ 
+                {   283 , ec_field_GF2m,   /* size and type */
+		    {{siBuffer, p283_poly, sizeof(p283_poly)}},   /* u.poly */
+		    0, 0, 0 },
+		/* curve */
+		{ 
+		/* a = curvea b = curveb */
+		    /* curve.a */
+		    { siBuffer, p283_a, sizeof(p283_a) },
+		    /* curve.b */
+		    { siBuffer, p283_b, sizeof(p283_b) },
+		    /* curve.seed */
+		    { siBuffer, NULL, 0}
+		},
+		/* base  = 04xy*/
+		{ siBuffer, p283_base, sizeof(p283_base) },
+		/* order */
+		{ siBuffer, p283_order, sizeof(p283_order) },
+		4,/* cofactor */
+		/* DEREncoding */
+		{ siBuffer, k283_encoding, sizeof(k283_encoding)}, 
+		/* name */
+		ECCurve_SECG_CHAR2_283K1,
+		/* curveOID */
+		{ siBuffer, k283_encoding+2, sizeof(k283_encoding)-2}, 
+    };
+                         
+    static const PRUint8 ecdsa_known_K283_signature[] = {
+                            0x00,0x45,0x88,0xc0,0x79,0x09,0x07,0xd1, 
+                            0x4e,0x88,0xe6,0xd5,0x2f,0x22,0x04,0x74, 
+                            0x35,0x24,0x65,0xe8,0x15,0xde,0x90,0x66, 
+                            0x94,0x70,0xdd,0x3a,0x14,0x70,0x02,0xd1,
+                            0xef,0x86,0xbd,0x15,0x00,0xd9,0xdc,0xfc, 
+                            0x87,0x2e,0x7c,0x99,0xe2,0xe3,0x79,0xb8, 
+                            0xd9,0x10,0x49,0x78,0x4b,0x59,0x8b,0x05, 
+                            0x77,0xec,0x6c,0xe8,0x35,0xe6,0x2e,0xa9,
+                            0xf9,0x77,0x1f,0x71,0x86,0xa5,0x4a,0xd0};
+#endif
+    ECParams ecparams;
+
+    SECStatus rv;
+
+    /* ECDSA GF(p) prime field curve test */
+    ecparams = ecdsa_known_P256_Params;
+    rv = freebl_fips_ECDSA_Test(&ecparams,
+                               ecdsa_known_P256_signature,
+                               sizeof ecdsa_known_P256_signature );
+    if (rv != SECSuccess) {
+        return( SECFailure );
+    }
+
+#ifdef NSS_ECC_MORE_THAN_SUITE_B
+    /* ECDSA GF(2m) binary field curve test */
+    ecparams = ecdsa_known_K283_Params;
+    rv = freebl_fips_ECDSA_Test(&ecparams,
+                               ecdsa_known_K283_signature,
+                               sizeof ecdsa_known_K283_signature );
+    if (rv != SECSuccess) {
+        return( SECFailure );
+    }
+#endif
+
+    return( SECSuccess );
+}
+
+#endif    /* NSS_ENABLE_ECC */
+
+static SECStatus
+freebl_fips_DSA_PowerUpSelfTest( void )
+{
+    /* DSA Known P (1024-bits), Q (160-bits), and G (1024-bits) Values. */
+    static const PRUint8 dsa_P[] = {
+         0x80,0xb0,0xd1,0x9d,0x6e,0xa4,0xf3,0x28, 
+         0x9f,0x24,0xa9,0x8a,0x49,0xd0,0x0c,0x63, 
+         0xe8,0x59,0x04,0xf9,0x89,0x4a,0x5e,0xc0, 
+         0x6d,0xd2,0x67,0x6b,0x37,0x81,0x83,0x0c,
+         0xfe,0x3a,0x8a,0xfd,0xa0,0x3b,0x08,0x91, 
+         0x1c,0xcb,0xb5,0x63,0xb0,0x1c,0x70,0xd0, 
+         0xae,0xe1,0x60,0x2e,0x12,0xeb,0x54,0xc7, 
+         0xcf,0xc6,0xcc,0xae,0x97,0x52,0x32,0x63,
+         0xd3,0xeb,0x55,0xea,0x2f,0x4c,0xd5,0xd7, 
+         0x3f,0xda,0xec,0x49,0x27,0x0b,0x14,0x56, 
+         0xc5,0x09,0xbe,0x4d,0x09,0x15,0x75,0x2b, 
+         0xa3,0x42,0x0d,0x03,0x71,0xdf,0x0f,0xf4,
+         0x0e,0xe9,0x0c,0x46,0x93,0x3d,0x3f,0xa6, 
+         0x6c,0xdb,0xca,0xe5,0xac,0x96,0xc8,0x64, 
+         0x5c,0xec,0x4b,0x35,0x65,0xfc,0xfb,0x5a, 
+         0x1b,0x04,0x1b,0xa1,0x0e,0xfd,0x88,0x15};
+        
+    static const PRUint8 dsa_Q[] = {
+         0xad,0x22,0x59,0xdf,0xe5,0xec,0x4c,0x6e, 
+         0xf9,0x43,0xf0,0x4b,0x2d,0x50,0x51,0xc6, 
+         0x91,0x99,0x8b,0xcf};
+        
+    static const PRUint8 dsa_G[] = {
+         0x78,0x6e,0xa9,0xd8,0xcd,0x4a,0x85,0xa4, 
+         0x45,0xb6,0x6e,0x5d,0x21,0x50,0x61,0xf6, 
+         0x5f,0xdf,0x5c,0x7a,0xde,0x0d,0x19,0xd3, 
+         0xc1,0x3b,0x14,0xcc,0x8e,0xed,0xdb,0x17,
+         0xb6,0xca,0xba,0x86,0xa9,0xea,0x51,0x2d, 
+         0xc1,0xa9,0x16,0xda,0xf8,0x7b,0x59,0x8a, 
+         0xdf,0xcb,0xa4,0x67,0x00,0x44,0xea,0x24, 
+         0x73,0xe5,0xcb,0x4b,0xaf,0x2a,0x31,0x25,
+         0x22,0x28,0x3f,0x16,0x10,0x82,0xf7,0xeb, 
+         0x94,0x0d,0xdd,0x09,0x22,0x14,0x08,0x79, 
+         0xba,0x11,0x0b,0xf1,0xff,0x2d,0x67,0xac, 
+         0xeb,0xb6,0x55,0x51,0x69,0x97,0xa7,0x25,
+         0x6b,0x9c,0xa0,0x9b,0xd5,0x08,0x9b,0x27, 
+         0x42,0x1c,0x7a,0x69,0x57,0xe6,0x2e,0xed, 
+         0xa9,0x5b,0x25,0xe8,0x1f,0xd2,0xed,0x1f, 
+         0xdf,0xe7,0x80,0x17,0xba,0x0d,0x4d,0x38};
+
+    /* DSA Known Random Values (known random key block       is 160-bits)  */
+    /*                     and (known random signature block is 160-bits). */
+    static const PRUint8 dsa_known_random_key_block[] = {
+                                                      "Mozilla Rules World!"};
+    static const PRUint8 dsa_known_random_signature_block[] = {
+                                                      "Random DSA Signature"};
+
+    /* DSA Known Digest (160-bits) */
+    static const PRUint8 dsa_known_digest[] = { "DSA Signature Digest" };
+
+    /* DSA Known Signature (320-bits). */
+    static const PRUint8 dsa_known_signature[] = {
+        0x25,0x7c,0x3a,0x79,0x32,0x45,0xb7,0x32, 
+        0x70,0xca,0x62,0x63,0x2b,0xf6,0x29,0x2c, 
+        0x22,0x2a,0x03,0xce,0x48,0x15,0x11,0x72, 
+        0x7b,0x7e,0xf5,0x7a,0xf3,0x10,0x3b,0xde,
+        0x34,0xc1,0x9e,0xd7,0x27,0x9e,0x77,0x38};
+
+    /* DSA variables. */
+    DSAPrivateKey *        dsa_private_key;
+    SECStatus              dsa_status;
+    SECItem                dsa_signature_item;
+    SECItem                dsa_digest_item;
+    DSAPublicKey           dsa_public_key;
+    PRUint8                dsa_computed_signature[FIPS_DSA_SIGNATURE_LENGTH];
+    static const PQGParams dsa_pqg = { NULL,
+			    { FIPS_DSA_TYPE, (unsigned char *)dsa_P, FIPS_DSA_PRIME_LENGTH },
+			    { FIPS_DSA_TYPE, (unsigned char *)dsa_Q, FIPS_DSA_SUBPRIME_LENGTH },
+			    { FIPS_DSA_TYPE, (unsigned char *)dsa_G, FIPS_DSA_BASE_LENGTH }};
+
+    /*******************************************/
+    /* Generate a DSA public/private key pair. */
+    /*******************************************/
+
+    /* Generate a DSA public/private key pair. */
+    dsa_status = DSA_NewKeyFromSeed(&dsa_pqg, dsa_known_random_key_block,
+                                    &dsa_private_key);
+
+    if( dsa_status != SECSuccess ) {
+        PORT_SetError( SEC_ERROR_NO_MEMORY );
+        return( SECFailure );
+    }
+
+    /* construct public key from private key. */
+    dsa_public_key.params      = dsa_private_key->params;
+    dsa_public_key.publicValue = dsa_private_key->publicValue;
+
+    /*************************************************/
+    /* DSA Single-Round Known Answer Signature Test. */
+    /*************************************************/
+
+    dsa_signature_item.data = dsa_computed_signature;
+    dsa_signature_item.len  = sizeof dsa_computed_signature;
+
+    dsa_digest_item.data    = (unsigned char *)dsa_known_digest;
+    dsa_digest_item.len     = SHA1_LENGTH;
+
+    /* Perform DSA signature process. */
+    dsa_status = DSA_SignDigestWithSeed( dsa_private_key, 
+                                         &dsa_signature_item,
+                                         &dsa_digest_item,
+                                         dsa_known_random_signature_block );
+
+    if( ( dsa_status != SECSuccess ) ||
+        ( dsa_signature_item.len != FIPS_DSA_SIGNATURE_LENGTH ) ||
+        ( PORT_Memcmp( dsa_computed_signature, dsa_known_signature,
+                       FIPS_DSA_SIGNATURE_LENGTH ) != 0 ) ) {
+        dsa_status = SECFailure;
+    } else {
+
+    /****************************************************/
+    /* DSA Single-Round Known Answer Verification Test. */
+    /****************************************************/
+
+    /* Perform DSA verification process. */
+    dsa_status = DSA_VerifyDigest( &dsa_public_key, 
+                                   &dsa_signature_item,
+                                   &dsa_digest_item);
+    }
+
+    PORT_FreeArena(dsa_private_key->params.arena, PR_TRUE);
+    /* Don't free public key, it uses same arena as private key */
+
+    /* Verify DSA signature. */
+    if( dsa_status != SECSuccess ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+	return SECFailure;
+    }
+
+    return( SECSuccess );
+
+
+}
+
+static SECStatus
+freebl_fips_RNG_PowerUpSelfTest( void )
+{
+   static const PRUint8 Q[] = {
+			0x85,0x89,0x9c,0x77,0xa3,0x79,0xff,0x1a,
+			0x86,0x6f,0x2f,0x3e,0x2e,0xf9,0x8c,0x9c,
+			0x9d,0xef,0xeb,0xed};
+   static const PRUint8 GENX[] = {
+			0x65,0x48,0xe3,0xca,0xac,0x64,0x2d,0xf7,
+			0x7b,0xd3,0x4e,0x79,0xc9,0x7d,0xa6,0xa8,
+			0xa2,0xc2,0x1f,0x8f,0xe9,0xb9,0xd3,0xa1,
+			0x3f,0xf7,0x0c,0xcd,0xa6,0xca,0xbf,0xce,
+			0x84,0x0e,0xb6,0xf1,0x0d,0xbe,0xa9,0xa3};
+   static const PRUint8 rng_known_DSAX[] = {
+			0x7a,0x86,0xf1,0x7f,0xbd,0x4e,0x6e,0xd9,
+			0x0a,0x26,0x21,0xd0,0x19,0xcb,0x86,0x73,
+			0x10,0x1f,0x60,0xd7};
+
+
+
+   SECStatus rng_status = SECSuccess;
+   PRUint8 DSAX[FIPS_DSA_SUBPRIME_LENGTH];
+
+   /*******************************************/
+   /*   Run the SP 800-90 Health tests        */
+   /*******************************************/
+   rng_status = PRNGTEST_RunHealthTests();
+   if (rng_status != SECSuccess) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+	return SECFailure;
+   }
+  
+   /*******************************************/
+   /* Generate DSAX fow given Q.              */
+   /*******************************************/
+
+   rng_status = FIPS186Change_ReduceModQForDSA(GENX, Q, DSAX);
+
+   /* Verify DSAX to perform the RNG integrity check */
+   if( ( rng_status != SECSuccess ) ||
+       ( PORT_Memcmp( DSAX, rng_known_DSAX,
+                      (FIPS_DSA_SUBPRIME_LENGTH) ) != 0 ) ) {
+        PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+	return SECFailure;
+   }
+       
+   return( SECSuccess ); 
+}
+
+static SECStatus
+freebl_fipsSoftwareIntegrityTest(const char *libname)
+{
+    SECStatus rv = SECSuccess;
+
+    /* make sure that our check file signatures are OK */
+    if( !BLAPI_VerifySelf(libname) ) {
+	rv = SECFailure;
+    }
+    return rv;
+}
+
+#define DO_FREEBL 1
+#define DO_REST 2
+
+static SECStatus
+freebl_fipsPowerUpSelfTest( unsigned int tests )
+{
+    SECStatus rv;
+
+    /*
+     * stand alone freebl. Test hash, and rng
+     */
+    if (tests & DO_FREEBL) {
+
+    /* SHA-X Power-Up SelfTest(s). */
+    rv = freebl_fips_SHA_PowerUpSelfTest();
+
+    if( rv != SECSuccess )
+        return rv;
+
+    /* RNG Power-Up SelfTest(s). */
+    rv = freebl_fips_RNG_PowerUpSelfTest();
+
+    if( rv != SECSuccess )
+        return rv;
+    }
+
+    /*
+     * test the rest of the algorithms not accessed through freebl
+     * standalone */
+    if (tests & DO_REST) {
+
+    /* DES3 Power-Up SelfTest(s). */
+    rv = freebl_fips_DES3_PowerUpSelfTest();
+
+    if( rv != SECSuccess )
+        return rv;
+ 
+    /* AES Power-Up SelfTest(s) for 128-bit key. */
+    rv = freebl_fips_AES_PowerUpSelfTest(FIPS_AES_128_KEY_SIZE);
+
+    if( rv != SECSuccess )
+        return rv;
+
+    /* AES Power-Up SelfTest(s) for 192-bit key. */
+    rv = freebl_fips_AES_PowerUpSelfTest(FIPS_AES_192_KEY_SIZE);
+
+    if( rv != SECSuccess )
+        return rv;
+
+    /* AES Power-Up SelfTest(s) for 256-bit key. */
+    rv = freebl_fips_AES_PowerUpSelfTest(FIPS_AES_256_KEY_SIZE);
+
+    if( rv != SECSuccess )
+        return rv;
+
+    /* HMAC SHA-X Power-Up SelfTest(s). */
+    rv = freebl_fips_HMAC_PowerUpSelfTest();
+ 
+    if( rv != SECSuccess )
+        return rv;
+
+    /* NOTE: RSA can only be tested in full freebl. It requires access to
+     * the locking primitives */
+    /* RSA Power-Up SelfTest(s). */
+    rv = freebl_fips_RSA_PowerUpSelfTest();
+
+    if( rv != SECSuccess )
+        return rv;
+
+    /* DSA Power-Up SelfTest(s). */
+    rv = freebl_fips_DSA_PowerUpSelfTest();
+
+    if( rv != SECSuccess )
+        return rv;
+    
+#ifdef NSS_ENABLE_ECC
+    /* ECDSA Power-Up SelfTest(s). */
+    rv = freebl_fips_ECDSA_PowerUpSelfTest();
+
+    if( rv != SECSuccess )
+        return rv;
+#endif
+    }
+    /* Passed Power-Up SelfTest(s). */
+    return( SECSuccess );
+}
+
+/*
+ * state variables. NOTE: freebl has two uses: a standalone use which
+ * provided limitted access to the hash functions throught the NSSLOWHASH_
+ * interface and an joint use from softoken, using the function pointer
+ * table. The standalone use can operation without nspr or nss-util, while
+ * the joint use requires both to be loaded. Certain functions (like RSA)
+ * needs locking from NSPR, for instance.
+ *
+ * At load time, we need to handle the two uses separately. If nspr and 
+ * nss-util  are loaded, then we can run all the selftests, but if nspr and 
+ * nss-util are not loaded, then we can't run all the selftests, and we need
+ * to prevent the softoken function pointer table from operating until the
+ * libraries are loaded and we try to use them.
+ */
+static PRBool self_tests_freebl_ran = PR_FALSE;
+static PRBool self_tests_ran = PR_FALSE;
+static PRBool self_tests_freebl_success = PR_FALSE;
+static PRBool self_tests_success = PR_FALSE;
+static PRBool fips_mode_available = PR_FALSE;
+
+/*
+ * accessors for freebl
+ */
+PRBool BL_POSTRan(PRBool freebl_only) 
+{ 
+    SECStatus rv;
+    /* if the freebl self tests didn't run, there is something wrong with 
+     * our on load tests */
+    if (!self_tests_freebl_ran) {
+	return PR_FALSE;
+    }
+    /* if all the self tests have run, we are good */
+    if (self_tests_ran) {
+	return PR_TRUE;
+    }
+    /* if we only care about the freebl tests, we are good */
+    if (freebl_only) {
+	return PR_TRUE;
+    }
+    /* run the rest of the self tests */
+    /* We could get there if freebl was loaded without the rest of the support
+     * libraries, but now we want to use more than just a standalone freebl.
+     * This requires the other libraries to be loaded.
+     * If they are now loaded, Try to run the rest of the selftests,
+     * otherwise fail (disabling access to these algorithms)  */
+    self_tests_ran = PR_TRUE; 
+    BL_Init(); /* required by RSA */
+    RNG_RNGInit(); /* required by RSA */
+    rv = freebl_fipsPowerUpSelfTest(DO_REST);
+    if (rv == SECSuccess) {
+        self_tests_success = PR_TRUE;
+    }
+    return PR_TRUE;
+}
+
+#include "blname.c"
+
+/*
+ * This function is called at dll load time, the code tha makes this 
+ * happen is platform specific on defined above.
+ */ 
+static void
+bl_startup_tests(void)
+{
+    const char *libraryName;
+    PRBool freebl_only = PR_FALSE;
+    SECStatus rv; 
+
+    PORT_Assert(self_tests_freebl_ran == PR_FALSE);
+    PORT_Assert(self_tests_success == PR_FALSE);
+    PORT_Assert(fips_mode_available == PR_FALSE);
+    self_tests_freebl_ran = PR_TRUE;  /* we are running the tests */
+    self_tests_success = PR_FALSE; /* force it just in case */
+    self_tests_freebl_success = PR_FALSE; /* force it just in case */
+
+#ifdef FREEBL_NO_DEPEND
+    rv = FREEBL_InitStubs();
+    if (rv != SECSuccess) {
+	freebl_only = PR_TRUE;
+    }
+#endif
+
+
+    self_tests_freebl_ran = PR_TRUE;  /* we are running the tests */
+
+    if (!freebl_only) {
+	self_tests_ran = PR_TRUE; /* we're running all the tests */
+	BL_Init(); /* needs to be called before RSA can be used */
+	RNG_RNGInit();
+    }
+
+    /* always run the post tests */
+    rv = freebl_fipsPowerUpSelfTest(freebl_only? DO_FREEBL : DO_FREEBL|DO_REST);
+    if (rv != SECSuccess) {
+	return;
+    }
+
+    libraryName = getLibName();
+    rv = freebl_fipsSoftwareIntegrityTest(libraryName);
+    if (rv != SECSuccess) {
+	return;
+    }
+
+    /* posts are happy, allow the fips module to function now */
+    self_tests_freebl_success = PR_TRUE; /* we always test the freebl stuff */
+    if (!freebl_only) {
+        self_tests_success = PR_TRUE;
+    }
+}
+
+/*
+ * this is called from the freebl init entry points that controll access to 
+ * all other freebl functions. This prevents freebl from operating if our
+ * power on selftest failed.
+ */
+SECStatus
+BL_FIPSEntryOK(PRBool freebl_only) {
+#ifdef NSS_NO_INIT_SUPPORT
+   /* this should only be set on platforms that can't handle one of the INIT
+    * schemes.  This code allows those platforms to continue to function, 
+    * though they don't meet the strict NIST requirements. If NSS_NO_INIT_SUPPORT
+    * is not set, and init support has not been properly enabled, freebl
+    * will always fail because of the test below
+    */
+    if (!self_tests_freebl_ran) {
+	bl_startup_tests();
+    }
+#endif
+    /* if the general self tests succeeded, we're done */
+    if (self_tests_success) {
+	return SECSuccess;
+    }
+    /* standalone freebl can initialize */
+    if (freebl_only & self_tests_freebl_success) {
+	return SECSuccess;
+    }
+    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+    return SECFailure;
+}
+
new file mode 100644
--- /dev/null
+++ b/lib/freebl/freebl_hash_vector.def
@@ -0,0 +1,34 @@
+;+#
+;+# This Source Code Form is subject to the terms of the Mozilla Public
+;+# License, v. 2.0. If a copy of the MPL was not distributed with this
+;+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+;+#
+;+# OK, this file is meant to support SUN, LINUX, AIX and WINDOWS
+;+#   1. For all unix platforms, the string ";-"  means "remove this line"
+;+#   2. For all unix platforms, the string " DATA " will be removed from any 
+;+#	line on which it occurs.
+;+#   3. Lines containing ";+" will have ";+" removed on SUN and LINUX.
+;+#      On AIX, lines containing ";+" will be removed.  
+;+#   4. For all unix platforms, the string ";;" will thave the ";;" removed.
+;+#   5. For all unix platforms, after the above processing has taken place,
+;+#    all characters after the first ";" on the line will be removed.  
+;+#    And for AIX, the first ";" will also be removed.
+;+#  This file is passed directly to windows. Since ';' is a comment, all UNIX
+;+#   directives are hidden behind ";", ";+", and ";-"
+;+
+;+NSSprivate_3.11 {               # NSS 3.11 release
+;+    global:
+LIBRARY freebl3 ;-
+EXPORTS	;-
+FREEBL_GetVector;
+;+    local:
+;+       *;
+;+};
+;+NSSprivate_3.16 {               # NSS 3.11 release
+;+    global:
+LIBRARY freebl3 ;-
+EXPORTS	;-
+NSSLOW_GetVector;
+;+    local:
+;+       *;
+;+};
--- a/lib/freebl/gcm.c
+++ b/lib/freebl/gcm.c
@@ -187,19 +187,17 @@ cleanup:
 /* Destroy a HashContext (Note we zero the digits so this function
  * is idempotent if called with freeit == PR_FALSE */
 static void
 gcmHash_DestroyContext(gcmHashContext *ghash, PRBool freeit)
 {
     mp_clear(&ghash->H);
     mp_clear(&ghash->X);
     mp_clear(&ghash->C_i);
-    MP_DIGITS(&ghash->H) = 0;
-    MP_DIGITS(&ghash->X) = 0;
-    MP_DIGITS(&ghash->C_i) = 0;
+    PORT_Memset(ghash, 0, sizeof(gcmHashContext));
     if (freeit) {
 	PORT_Free(ghash);
     }
 }
 
 static SECStatus
 gcm_getX(gcmHashContext *ghash, unsigned char *T, unsigned int blocksize)
 {
@@ -262,16 +260,17 @@ gcm_HashMult(gcmHashContext *ghash, cons
 	 * the builtin bmulmod from mpi
 	 */
         CHECK_MPI_OK(mp_bmulmod(&ghash->C_i, &ghash->H,
 					ghash->poly, &ghash->X));
 	GCM_TRACE_X(ghash, "X%d = ")
     }
     rv = SECSuccess;
 cleanup:
+    PORT_Memset(tmp_buf, 0, sizeof(tmp_buf));
     if (rv != SECSuccess) {
 	MP_TO_SEC_ERROR(err);
     }
     return rv;
 }
 
 static void
 gcm_zeroX(gcmHashContext *ghash)
@@ -361,16 +360,17 @@ cleanup:
     return SECFailure;
 }
 
 /* Destroy a HashContext (Note we zero the digits so this function
  * is idempotent if called with freeit == PR_FALSE */
 static void
 gcmHash_DestroyContext(gcmHashContext *ghash, PRBool freeit)
 {
+    PORT_Memset(ghash, 0, sizeof(gcmHashContext));
     if (freeit) {
 	PORT_Free(ghash);
     }
 }
 
 static unsigned long
 gcm_shift_one(unsigned long *t, unsigned int count)
 {
@@ -418,16 +418,17 @@ gcm_HashMult(gcmHashContext *ghash, cons
 		if (gcm_shift_one(C_i, arraysize)) {
 		    C_i[0] = C_i[0] ^ ghash->R;
 		}
 		H = H >> 1;
 	    }
 	}
 	GCM_TRACE_X(ghash, "X%d = ")
     }
+    PORT_Memset(C_i, 0, sizeof(C_i));
     return SECSuccess;
 }
 
 
 static void
 gcm_zeroX(gcmHashContext *ghash)
 {
     PORT_Memset(ghash->X, 0, sizeof(ghash->X));
@@ -533,36 +534,40 @@ gcmHash_Final(gcmHashContext *ghash, uns
 		unsigned int *outlen, unsigned int maxout,
 		unsigned int blocksize)
 {
     unsigned char T[MAX_BLOCK_SIZE];
     SECStatus rv;
 
     rv = gcmHash_Sync(ghash, blocksize);
     if (rv != SECSuccess) {
-	return SECFailure;
+	goto cleanup;
     }
 
     rv = gcm_HashMult(ghash, ghash->counterBuf, (GCM_HASH_LEN_LEN*2)/blocksize,
 								blocksize);
     if (rv != SECSuccess) {
-	return SECFailure;
+	goto cleanup;
     }
 
     GCM_TRACE_X(ghash, "GHASH(H,A,C) = ")
 
     rv = gcm_getX(ghash, T, blocksize);
     if (rv != SECSuccess) {
-	return SECFailure;
+	goto cleanup;
     }
 
     if (maxout > blocksize) maxout = blocksize;
     PORT_Memcpy(outbuf, T, maxout);
     *outlen = maxout;
-    return SECSuccess;
+    rv = SECSuccess;
+
+cleanup:
+    PORT_Memset(T, 0, sizeof(T));
+    return rv;
 }
 
 SECStatus
 gcmHash_Reset(gcmHashContext *ghash, const unsigned char *AAD,
 	      unsigned int AADLen, unsigned int blocksize)
 {
     SECStatus rv;
 
@@ -690,16 +695,18 @@ loser:
 void
 GCM_DestroyContext(GCMContext *gcm, PRBool freeit)
 {
     /* these two are statically allocated and will be freed when we free
      * gcm. call their destroy functions to free up any locally
      * allocated data (like mp_int's) */
     CTR_DestroyContext(&gcm->ctr_context, PR_FALSE);
     gcmHash_DestroyContext(&gcm->ghash_context, PR_FALSE);
+    PORT_Memset(&gcm->tagBits, 0, sizeof(gcm->tagBits));
+    PORT_Memset(gcm->tagKey, 0, sizeof(gcm->tagKey));
     if (freeit) {
 	PORT_Free(gcm);
     }
 }
 
 static SECStatus
 gcm_GetTag(GCMContext *gcm, unsigned char *outbuf,
 	unsigned int *outlen, unsigned int maxout,
@@ -833,14 +840,16 @@ GCM_DecryptUpdate(GCMContext *gcm, unsig
 	return SECFailure;
     }
     /* Don't decrypt if we can't authenticate the encrypted data!
      * This assumes that if tagBits is not a multiple of 8, intag will
      * preserve the masked off missing bits.  */
     if (NSS_SecureMemcmp(tag, intag, tagBytes) != 0) {
 	/* force a CKR_ENCRYPTED_DATA_INVALID error at in softoken */
 	PORT_SetError(SEC_ERROR_BAD_DATA);
+	PORT_Memset(tag, 0, sizeof(tag));
 	return SECFailure;
     }
+    PORT_Memset(tag, 0, sizeof(tag));
     /* finish the decryption */
     return CTR_Update(&gcm->ctr_context, outbuf, outlen, maxout,
 			  inbuf, inlen, blocksize);
 }
--- a/lib/freebl/ldvector.c
+++ b/lib/freebl/ldvector.c
@@ -7,17 +7,17 @@
 
 #ifdef FREEBL_NO_DEPEND
 extern int FREEBL_InitStubs(void);
 #endif
 
 #include "loader.h"
 #include "alghmac.h"
 #include "hmacct.h"
-
+#include "blapii.h"
 
 static const struct FREEBLVectorStr vector = 
 {
 
     sizeof vector,
     FREEBL_VERSION,
 
     RSA_NewKey,
@@ -294,20 +294,59 @@ static const struct FREEBLVectorStr vect
     ChaCha20Poly1305_CreateContext,
     ChaCha20Poly1305_DestroyContext,
     ChaCha20Poly1305_Seal,
     ChaCha20Poly1305_Open
 
     /* End of Version 3.018 */
 };
 
+
+
 const FREEBLVector *
 FREEBL_GetVector(void)
 {
+#ifdef FREEBL_NO_DEPEND
+    SECStatus rv;
+#endif
+
 #define NSS_VERSION_VARIABLE __nss_freebl_version
 #include "verref.h"
 
 #ifdef FREEBL_NO_DEPEND
-    FREEBL_InitStubs();
+    /* this entry point is only valid if nspr and nss-util has been loaded */
+    rv = FREEBL_InitStubs();
+    if (rv != SECSuccess) {
+	return NULL;
+    }
 #endif
+    /* make sure the Full self tests have been run before continuing */
+    BL_POSTRan(PR_FALSE);
+
     return &vector;
 }
 
+#ifdef FREEBL_LOWHASH
+static const struct NSSLOWVectorStr nssvector = 
+{
+    sizeof nssvector,
+    NSSLOW_VERSION,
+    FREEBL_GetVector,
+    NSSLOW_Init,
+    NSSLOW_Shutdown,
+    NSSLOW_Reset,
+    NSSLOWHASH_NewContext,
+    NSSLOWHASH_Begin,
+    NSSLOWHASH_Update,
+    NSSLOWHASH_End,
+    NSSLOWHASH_Destroy,
+    NSSLOWHASH_Length
+};
+
+const NSSLOWVector *
+NSSLOW_GetVector(void)
+{
+    /* POST check and  stub init happens in FREEBL_GetVector() and 
+     * NSSLOW_Init() respectively */
+    return &nssvector;
+}
+#endif
+
--- a/lib/freebl/loader.c
+++ b/lib/freebl/loader.c
@@ -5,113 +5,27 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "loader.h"
 #include "prmem.h"
 #include "prerror.h"
 #include "prinit.h"
 #include "prenv.h"
-
-static const char* default_name =
-    SHLIB_PREFIX"freebl"SHLIB_VERSION"."SHLIB_SUFFIX;
-
-/* getLibName() returns the name of the library to load. */
-
-#if defined(SOLARIS) && defined(__sparc)
-#include <stddef.h>
-#include <strings.h>
-#include <sys/systeminfo.h>
-
-
-#if defined(NSS_USE_64)
-
-const static char fpu_hybrid_shared_lib[] = "libfreebl_64fpu_3.so";
-const static char int_hybrid_shared_lib[] = "libfreebl_64int_3.so";
-const static char non_hybrid_shared_lib[] = "libfreebl_64fpu_3.so";
-
-const static char int_hybrid_isa[] = "sparcv9";
-const static char fpu_hybrid_isa[] = "sparcv9+vis";
-
-#else
-
-const static char fpu_hybrid_shared_lib[] = "libfreebl_32fpu_3.so";
-const static char int_hybrid_shared_lib[] = "libfreebl_32int64_3.so";
-/* This was for SPARC V8, now obsolete. */
-const static char *const non_hybrid_shared_lib = NULL;
-
-const static char int_hybrid_isa[] = "sparcv8plus";
-const static char fpu_hybrid_isa[] = "sparcv8plus+vis";
-
-#endif
-
-static const char *
-getLibName(void)
-{
-    char * found_int_hybrid;
-    char * found_fpu_hybrid;
-    long buflen;
-    char buf[256];
-
-    buflen = sysinfo(SI_ISALIST, buf, sizeof buf);
-    if (buflen <= 0) 
-	return NULL;
-    /* sysinfo output is always supposed to be NUL terminated, but ... */
-    if (buflen < sizeof buf) 
-    	buf[buflen] = '\0';
-    else
-    	buf[(sizeof buf) - 1] = '\0';
-    /* The ISA list is a space separated string of names of ISAs and
-     * ISA extensions, in order of decreasing performance.
-     * There are two different ISAs with which NSS's crypto code can be
-     * accelerated. If both are in the list, we take the first one.
-     * If one is in the list, we use it, and if neither then we use
-     * the base unaccelerated code.
-     */
-    found_int_hybrid = strstr(buf, int_hybrid_isa);
-    found_fpu_hybrid = strstr(buf, fpu_hybrid_isa);
-    if (found_fpu_hybrid && 
-	(!found_int_hybrid ||
-	 (found_int_hybrid - found_fpu_hybrid) >= 0)) {
-	return fpu_hybrid_shared_lib;
-    }
-    if (found_int_hybrid) {
-	return int_hybrid_shared_lib;
-    }
-    return non_hybrid_shared_lib;
-}
-
-#elif defined(HPUX) && !defined(NSS_USE_64) && !defined(__ia64)
-#include <unistd.h>
-
-/* This code tests to see if we're running on a PA2.x CPU.
-** It returns true (1) if so, and false (0) otherwise.
-*/
-static const char *
-getLibName(void)
-{
-    long cpu = sysconf(_SC_CPU_VERSION);
-    return (cpu == CPU_PA_RISC2_0) 
-		? "libfreebl_32fpu_3.sl"
-	        : "libfreebl_32int_3.sl" ;
-}
-#else
-/* default case, for platforms/ABIs that have only one freebl shared lib. */
-static const char * getLibName(void) { return default_name; }
-#endif
+#include "blname.c"
 
 #include "prio.h"
 #include "prprf.h"
 #include <stdio.h>
 #include "prsystem.h"
 
 static const char *NameOfThisSharedLib = 
   SHLIB_PREFIX"softokn"SOFTOKEN_SHLIB_VERSION"."SHLIB_SUFFIX;
 
-static PRLibrary* blLib;
+static PRLibrary* blLib = NULL;
 
 #define LSB(x) ((x)&0xff)
 #define MSB(x) ((x)>>8)
 
 static const FREEBLVector *vector;
 static const char *libraryName = NULL;
 
 #include "genload.c"
@@ -144,22 +58,22 @@ freebl_LoadDSO( void )
           vector = dsoVector;
 	  libraryName = name;
 	  blLib = handle;
 	  return PR_SUCCESS;
 	}
       }
     }
 #ifdef DEBUG
-    {
+    if (blLib) {
       PRStatus status = PR_UnloadLibrary(blLib);
       PORT_Assert(PR_SUCCESS == status);
     }
 #else
-    PR_UnloadLibrary(blLib);
+    if (blLib) PR_UnloadLibrary(blLib);
 #endif
   }
   return PR_FAILURE;
 }
 
 static const PRCallOnceType pristineCallOnce;
 static PRCallOnceType loadFreeBLOnce;
 
@@ -2179,8 +2093,9 @@ ChaCha20Poly1305_Open(const ChaCha20Poly
                       const unsigned char *ad, unsigned int adLen)
 {
   if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
       return SECFailure;
   return (vector->p_ChaCha20Poly1305_Open)(
       ctx, output, outputLen, maxOutputLen, input, inputLen,
       nonce, nonceLen, ad, adLen);
 }
+
--- a/lib/freebl/loader.h
+++ b/lib/freebl/loader.h
@@ -5,16 +5,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef _LOADER_H_
 #define _LOADER_H_ 1
 
 #include "blapi.h"
 
+
 #define FREEBL_VERSION 0x0312
 
 struct FREEBLVectorStr {
 
   unsigned short length;  /* of this struct in bytes */
   unsigned short version; /* of this struct. */
 
   RSAPrivateKey * (* p_RSA_NewKey)(int         keySizeInBits,
@@ -735,17 +736,52 @@ struct FREEBLVectorStr {
   /* Version 3.018 came to here */
 
   /* Add new function pointers at the end of this struct and bump
    * FREEBL_VERSION at the beginning of this file. */
  };
 
 typedef struct FREEBLVectorStr FREEBLVector;
 
+#ifdef FREEBL_LOWHASH
+#include "nsslowhash.h"
+
+#define NSSLOW_VERSION 0x0300
+
+struct NSSLOWVectorStr {
+  unsigned short length;  /* of this struct in bytes */
+  unsigned short version; /* of this struct. */
+  const FREEBLVector *(*p_FREEBL_GetVector)(void);
+  NSSLOWInitContext *(*p_NSSLOW_Init)(void);
+  void (*p_NSSLOW_Shutdown)(NSSLOWInitContext *context);
+  void (*p_NSSLOW_Reset)(NSSLOWInitContext *context);
+  NSSLOWHASHContext *(*p_NSSLOWHASH_NewContext)(
+			NSSLOWInitContext *initContext, 
+			HASH_HashType hashType);
+  void (*p_NSSLOWHASH_Begin)(NSSLOWHASHContext *context);
+  void (*p_NSSLOWHASH_Update)(NSSLOWHASHContext *context, 
+			const unsigned char *buf, 
+			unsigned int len);
+  void (*p_NSSLOWHASH_End)(NSSLOWHASHContext *context, 
+			unsigned char *buf, 
+			unsigned int *ret, unsigned int len);
+  void (*p_NSSLOWHASH_Destroy)(NSSLOWHASHContext *context);
+  unsigned int (*p_NSSLOWHASH_Length)(NSSLOWHASHContext *context);
+};
+
+typedef struct NSSLOWVectorStr NSSLOWVector;
+#endif
+
 SEC_BEGIN_PROTOS
 
+#ifdef FREEBL_LOWHASH
+typedef const NSSLOWVector * NSSLOWGetVectorFn(void);
+
+extern NSSLOWGetVectorFn NSSLOW_GetVector;
+#endif
+
 typedef const FREEBLVector * FREEBLGetVectorFn(void);
 
 extern FREEBLGetVectorFn FREEBL_GetVector;
 
 SEC_END_PROTOS
 
 #endif
new file mode 100644
--- /dev/null
+++ b/lib/freebl/lowhash_vector.c
@@ -0,0 +1,217 @@
+/*
+ * loader.c - load platform dependent DSO containing freebl implementation.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#define _GNU_SOURCE 1
+#include "loader.h"
+#include "prmem.h"
+#include "prerror.h"
+#include "prinit.h"
+#include "prenv.h"
+#include "blname.c"
+
+#include "prio.h"
+#include "prprf.h"
+#include <stdio.h>
+#include "prsystem.h"
+#include "nsslowhash.h"
+#include <dlfcn.h>
+#include "pratom.h"
+
+
+static PRLibrary* blLib;
+
+#define LSB(x) ((x)&0xff)
+#define MSB(x) ((x)>>8)
+
+static const NSSLOWVector *vector;
+static const char *libraryName = NULL;
+
+/* pretty much only glibc uses this, make sure we don't have any depenencies 
+ * on nspr.. */
+#undef PORT_Alloc
+#undef PORT_Free
+#define PORT_Alloc malloc
+#define PR_Malloc malloc
+#define PORT_Free free
+#define PR_Free free
+#define PR_GetDirectorySeparator() '/'
+#define PR_LoadLibraryWithFlags(libspec,flags) \
+	(PRLibrary*)dlopen(libSpec.value.pathname,RTLD_NOW|RTLD_LOCAL)
+#define PR_GetLibraryFilePathname(name,addr) \
+	freebl_lowhash_getLibraryFilePath(addr)
+
+static char *
+freebl_lowhash_getLibraryFilePath(void *addr)
+{
+    Dl_info dli;
+    if (dladdr(addr, &dli) == 0) {
+	return NULL;
+    }
+    return strdup(dli.dli_fname);
+}
+
+/*
+ * The PR_LoadLibraryWithFlags call above defines this variable away, so we
+ * don't need it..
+ */
+#ifdef nodef
+static const char *NameOfThisSharedLib = 
+  SHLIB_PREFIX"freebl"SHLIB_VERSION"."SHLIB_SUFFIX;
+#endif
+
+#include "genload.c"
+
+
+/* This function must be run only once. */
+/*  determine if hybrid platform, then actually load the DSO. */
+static PRStatus
+freebl_LoadDSO( void ) 
+{
+  PRLibrary *  handle;
+  const char * name = getLibName();
+
+  if (!name) {
+    /*PR_SetError(PR_LOAD_LIBRARY_ERROR,0); */
+    return PR_FAILURE;
+  }
+  handle = loader_LoadLibrary(name);
+  if (handle) {
+    void *address = dlsym(handle, "NSSLOW_GetVector");
+    if (address) {
+      NSSLOWGetVectorFn  * getVector = (NSSLOWGetVectorFn *)address;
+      const NSSLOWVector * dsoVector = getVector();
+      if (dsoVector) {
+	unsigned short dsoVersion = dsoVector->version;
+	unsigned short  myVersion = NSSLOW_VERSION;
+	if (MSB(dsoVersion) == MSB(myVersion) && 
+	    LSB(dsoVersion) >= LSB(myVersion) &&
+	    dsoVector->length >= sizeof(NSSLOWVector)) {
+          vector = dsoVector;
+	  libraryName = name;
+	  blLib = handle;
+	  return PR_SUCCESS;
+	}
+      }
+    }
+    (void)dlclose(handle);
+  }
+  return PR_FAILURE;
+}
+
+static PRCallOnceType loadFreeBLOnce;
+/* remove when NSPR pratom.h is updated. s390 has atomic intrinsics,
+ * but nspr doesn't know it. */
+#if defined(__s390__) || defined(__s390x__)
+#undef PR_ATOMIC_SET
+#define PR_ATOMIC_SET(val, newval) __sync_lock_test_and_set(val, newval)
+#endif
+
+static PRStatus
+freebl_RunLoaderOnce( void )
+{
+  /* Don't have NSPR, so can use the real PR_CallOnce, implement a stripped
+   * down version. */
+  if (loadFreeBLOnce.initialized) {
+	return loadFreeBLOnce.status;
+  }
+  /* PR_ATOMIC_SET macro is implemented with compiler intrinsics, if we don't
+   * have the intrinsic, it will be set to an NSPR PR_Atomic function, which
+   * will show up as missing at build time. If we get that missing function,
+   * Then we'll need to implement a PR_AtomicSet() function for that platform
+   */
+  if (PR_ATOMIC_SET(&loadFreeBLOnce.inProgress,1) == 0) {
+	loadFreeBLOnce.status = freebl_LoadDSO();
+	loadFreeBLOnce.initialized = 1;
+  } else {
+	/* shouldn't have a lot of takers on the else clause, which is good
+ 	 * since we don't have condition variables yet.
+	 * 'initialized' only ever gets set (not cleared) so we don't
+	 * need the traditional locks. */
+	while (!loadFreeBLOnce.initialized) {
+	    sleep(1); /* don't have condition variables, just give up the CPU */
+	}
+  }
+
+  return loadFreeBLOnce.status;
+}
+
+const FREEBLVector *FREEBL_GetVector(void)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return NULL;
+  return (vector->p_FREEBL_GetVector)();
+}
+
+NSSLOWInitContext *NSSLOW_Init(void) 
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return NULL;
+  return (vector->p_NSSLOW_Init)();
+}
+
+void NSSLOW_Shutdown(NSSLOWInitContext *context)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return;
+  (vector->p_NSSLOW_Shutdown)(context);
+}
+
+void NSSLOW_Reset(NSSLOWInitContext *context)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return;
+  (vector->p_NSSLOW_Reset)(context);
+}
+
+NSSLOWHASHContext *NSSLOWHASH_NewContext(
+			NSSLOWInitContext *initContext, 
+			HASH_HashType hashType)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return NULL;
+  return (vector->p_NSSLOWHASH_NewContext)(initContext, hashType);
+}
+
+void NSSLOWHASH_Begin(NSSLOWHASHContext *context)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return;
+  (vector->p_NSSLOWHASH_Begin)(context);
+}
+
+void NSSLOWHASH_Update(NSSLOWHASHContext *context, 
+			const unsigned char *buf, 
+			unsigned int len)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return;
+  (vector->p_NSSLOWHASH_Update)(context, buf, len);
+}
+
+void NSSLOWHASH_End(NSSLOWHASHContext *context, 
+			unsigned char *buf, 
+			unsigned int *ret, unsigned int len)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return;
+  (vector->p_NSSLOWHASH_End)(context, buf, ret, len);
+}
+
+void NSSLOWHASH_Destroy(NSSLOWHASHContext *context)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return;
+  (vector->p_NSSLOWHASH_Destroy)(context);
+}
+
+unsigned int NSSLOWHASH_Length(NSSLOWHASHContext *context)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return -1;
+  return (vector->p_NSSLOWHASH_Length)(context);
+}
+
--- a/lib/freebl/manifest.mn
+++ b/lib/freebl/manifest.mn
@@ -5,16 +5,40 @@
 
 # NOTE: any ifdefs in this file must be defined on the gmake command line
 # (if anywhere).  They cannot come from Makefile or config.mk 
 
 CORE_DEPTH = ../..
 
 MODULE = nss
 
+# copied from Linux.mk. We have a chicken and egg issue here. We need to set
+# Library name before we call the platform code in coreconf, but we need to
+# Pick up the automatic setting of FREEBL_LOWHASH before we  can set the
+# Library name... so for now we mimic the code in Linux.mk to get the
+# automatic setting early...
+#
+# On Linux 2.6 or later, build libfreebl3.so with no NSPR and libnssutil3.so
+# dependencies by default.  Set FREEBL_NO_DEPEND to 0 in the environment to
+# override this.
+#
+#
+include $(CORE_DEPTH)/coreconf/arch.mk
+ifeq ($(OS_ARCH),Linux)
+ifneq ($(OS_TARGET),Android)
+ifeq (2.6,$(firstword $(sort 2.6 $(OS_RELEASE))))
+ifndef FREEBL_NO_DEPEND
+FREEBL_NO_DEPEND = 1
+FREEBL_LOWHASH = 1
+endif
+endif
+endif
+endif
+
+
 LIBRARY_NAME = freebl
 LIBRARY_VERSION = 3
 
 ifdef FREEBL_CHILD_BUILD
   ifdef USE_ABI32_INT32
     LIBRARY_NAME = freebl_32int
   endif
   ifdef USE_ABI32_INT64
@@ -24,16 +48,23 @@ ifdef FREEBL_CHILD_BUILD
     LIBRARY_NAME = freebl_32fpu
   endif
   ifdef USE_ABI64_INT
     LIBRARY_NAME = freebl_64int
   endif
   ifdef USE_ABI64_FPU
     LIBRARY_NAME = freebl_64fpu
   endif
+  ifdef FREEBL_LOWHASH
+    LIBRARY_NAME = freeblpriv
+  endif
+  ifdef USE_STUB_BUILD
+    # for the stub build, reset name to the default (from freeblpriv)
+    LIBRARY_NAME = freebl
+  endif
 endif
 
 # if the library name contains _, we prefix the version with _
 ifneq (,$(findstring _,$(LIBRARY_NAME)))
   LIBRARY_VERSION := _$(LIBRARY_VERSION)
 endif
 
 MAPFILE = $(OBJDIR)/$(LIBRARY_NAME).def
@@ -100,16 +131,17 @@ CSRCS = \
 	arcfour.c \
 	arcfive.c \
 	desblapi.c \
 	des.c \
 	drbg.c \
 	chacha20poly1305.c \
 	cts.c \
 	ctr.c \
+	fipsfreebl.c \
 	gcm.c \
 	hmacct.c \
 	rijndael.c \
 	aeskeywrap.c \
 	camellia.c \
 	dh.c \
 	ec.c \
 	ecdecode.c \
--- a/lib/freebl/mpi/mpprime.c
+++ b/lib/freebl/mpi/mpprime.c
@@ -405,41 +405,42 @@ mp_err mpp_make_prime(mp_int *start, mp_
 
   sieve = malloc(SIEVE_SIZE);
   ARGCHK(sieve != NULL, MP_MEM);
 
   MP_DIGITS(&trial) = 0;
   MP_DIGITS(&q) = 0;
   MP_CHECKOK( mp_init(&trial) );
   MP_CHECKOK( mp_init(&q)     );
-  /* values taken from table 4.4, HandBook of Applied Cryptography */
-  if (nBits >= 1300) {
-    num_tests = 2;
-  } else if (nBits >= 850) {
+  /* values originally taken from table 4.4, 
+   * HandBook of Applied Cryptography, augmented by FIPS-186
+   * requirements, Table C.2 and C.3 */
+  if (nBits >= 2000) {
     num_tests = 3;
-  } else if (nBits >= 650) {
+  } else if (nBits >= 1536) {
     num_tests = 4;
-  } else if (nBits >= 550) {
+  } else if (nBits >= 1024) {
     num_tests = 5;
-  } else if (nBits >= 450) {
+  } else if (nBits >= 550) {
     num_tests = 6;
-  } else if (nBits >= 400) {
+  } else if (nBits >= 450) {
     num_tests = 7;
-  } else if (nBits >= 350) {
+  } else if (nBits >= 400) {
     num_tests = 8;
+  } else if (nBits >= 350) {
+    num_tests = 9;
   } else if (nBits >= 300) {
-    num_tests = 9;
+    num_tests = 10;
   } else if (nBits >= 250) {
-    num_tests = 12;
+    num_tests = 20;
   } else if (nBits >= 200) {
-    num_tests = 15;
-  } else if (nBits >= 150) {
-    num_tests = 18;
+    num_tests = 41;
   } else if (nBits >= 100) {
-    num_tests = 27;
+    num_tests = 38;  /* funny anomaly in the FIPS tables, for aux primes, the
+	              * required more iterations for larger aux primes */
   } else
     num_tests = 50;
 
   if (strong) 
     --nBits;
   MP_CHECKOK( mpl_set_bit(start, nBits - 1, 1) );
   MP_CHECKOK( mpl_set_bit(start,         0, 1) );
   for (i = mpl_significant_bits(start) - 1; i >= nBits; --i) {
--- a/lib/freebl/nsslowhash.c
+++ b/lib/freebl/nsslowhash.c
@@ -2,254 +2,21 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifdef FREEBL_NO_DEPEND
 #include "stubs.h"
 #endif
 #include "prtypes.h"
 #include "secerr.h"
-#include "pkcs11t.h"
 #include "blapi.h"
 #include "hasht.h"
 #include "plhash.h"
 #include "nsslowhash.h"
-
-/* FIPS preprocessor directives for message digests             */
-#define FIPS_KNOWN_HASH_MESSAGE_LENGTH          64  /* 512-bits */
-
-/* Known Hash Message (512-bits).  Used for all hashes (incl. SHA-N [N>1]). */
-static const PRUint8 known_hash_message[] = {
-  "The test message for the MD2, MD5, and SHA-1 hashing algorithms." };
-
-static CK_RV
-freebl_fips_MD2_PowerUpSelfTest( void )
-{
-    /* MD2 Known Digest Message (128-bits). */
-    static const PRUint8 md2_known_digest[]  = {
-                                   0x41,0x5a,0x12,0xb2,0x3f,0x28,0x97,0x17,
-                                   0x0c,0x71,0x4e,0xcc,0x40,0xc8,0x1d,0x1b};
-
-    /* MD2 variables. */
-    MD2Context * md2_context;
-    unsigned int md2_bytes_hashed;
-    PRUint8      md2_computed_digest[MD2_LENGTH];
-
-
-    /***********************************************/
-    /* MD2 Single-Round Known Answer Hashing Test. */
-    /***********************************************/
-
-    md2_context = MD2_NewContext();
-
-    if( md2_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    MD2_Begin( md2_context );
-
-    MD2_Update( md2_context, known_hash_message,
-                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
-
-    MD2_End( md2_context, md2_computed_digest, &md2_bytes_hashed, MD2_LENGTH );
-
-    MD2_DestroyContext( md2_context , PR_TRUE );
-    
-    if( ( md2_bytes_hashed != MD2_LENGTH ) ||
-        ( PORT_Memcmp( md2_computed_digest, md2_known_digest,
-                       MD2_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-}
-
-
-
-static CK_RV
-freebl_fips_MD5_PowerUpSelfTest( void )
-{
-    /* MD5 Known Digest Message (128-bits). */
-    static const PRUint8 md5_known_digest[]  = {
-				   0x25,0xc8,0xc0,0x10,0xc5,0x6e,0x68,0x28,
-				   0x28,0xa4,0xa5,0xd2,0x98,0x9a,0xea,0x2d};
-
-    /* MD5 variables. */
-    PRUint8        md5_computed_digest[MD5_LENGTH];
-    SECStatus      md5_status;
-
-
-    /***********************************************/
-    /* MD5 Single-Round Known Answer Hashing Test. */
-    /***********************************************/
-
-    md5_status = MD5_HashBuf( md5_computed_digest, known_hash_message,
-                              FIPS_KNOWN_HASH_MESSAGE_LENGTH );
-
-    if( ( md5_status != SECSuccess ) ||
-        ( PORT_Memcmp( md5_computed_digest, md5_known_digest,
-                       MD5_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-}
-
-static CK_RV
-freebl_fips_SHA_PowerUpSelfTest( void )
-{
-    /* SHA-1 Known Digest Message (160-bits). */
-    static const PRUint8 sha1_known_digest[] = {
-			       0x0a,0x6d,0x07,0xba,0x1e,0xbd,0x8a,0x1b,
-			       0x72,0xf6,0xc7,0x22,0xf1,0x27,0x9f,0xf0,
-			       0xe0,0x68,0x47,0x7a};
-
-    /* SHA-224 Known Digest Message (224-bits). */
-    static const PRUint8 sha224_known_digest[] = {
-        0x89,0x5e,0x7f,0xfd,0x0e,0xd8,0x35,0x6f,
-        0x64,0x6d,0xf2,0xde,0x5e,0xed,0xa6,0x7f,
-        0x29,0xd1,0x12,0x73,0x42,0x84,0x95,0x4f,
-        0x8e,0x08,0xe5,0xcb};
-
-    /* SHA-256 Known Digest Message (256-bits). */
-    static const PRUint8 sha256_known_digest[] = {
-        0x38,0xa9,0xc1,0xf0,0x35,0xf6,0x5d,0x61,
-        0x11,0xd4,0x0b,0xdc,0xce,0x35,0x14,0x8d,
-        0xf2,0xdd,0xaf,0xaf,0xcf,0xb7,0x87,0xe9,
-        0x96,0xa5,0xd2,0x83,0x62,0x46,0x56,0x79};
- 
-    /* SHA-384 Known Digest Message (384-bits). */
-    static const PRUint8 sha384_known_digest[] = {
-        0x11,0xfe,0x1c,0x00,0x89,0x48,0xde,0xb3,
-        0x99,0xee,0x1c,0x18,0xb4,0x10,0xfb,0xfe,
-        0xe3,0xa8,0x2c,0xf3,0x04,0xb0,0x2f,0xc8,
-        0xa3,0xc4,0x5e,0xea,0x7e,0x60,0x48,0x7b,
-        0xce,0x2c,0x62,0xf7,0xbc,0xa7,0xe8,0xa3,
-        0xcf,0x24,0xce,0x9c,0xe2,0x8b,0x09,0x72};
-
-    /* SHA-512 Known Digest Message (512-bits). */
-    static const PRUint8 sha512_known_digest[] = {
-        0xc8,0xb3,0x27,0xf9,0x0b,0x24,0xc8,0xbf,
-        0x4c,0xba,0x33,0x54,0xf2,0x31,0xbf,0xdb,
-        0xab,0xfd,0xb3,0x15,0xd7,0xfa,0x48,0x99,
-        0x07,0x60,0x0f,0x57,0x41,0x1a,0xdd,0x28,
-        0x12,0x55,0x25,0xac,0xba,0x3a,0x99,0x12,
-        0x2c,0x7a,0x8f,0x75,0x3a,0xe1,0x06,0x6f,
-        0x30,0x31,0xc9,0x33,0xc6,0x1b,0x90,0x1a,
-        0x6c,0x98,0x9a,0x87,0xd0,0xb2,0xf8,0x07};
-
-    /* SHA-X variables. */
-    PRUint8        sha_computed_digest[HASH_LENGTH_MAX];
-    SECStatus      sha_status;
-
-    /*************************************************/
-    /* SHA-1 Single-Round Known Answer Hashing Test. */
-    /*************************************************/
-
-    sha_status = SHA1_HashBuf( sha_computed_digest, known_hash_message,
-                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
- 
-    if( ( sha_status != SECSuccess ) ||
-        ( PORT_Memcmp( sha_computed_digest, sha1_known_digest,
-                       SHA1_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    /***************************************************/
-    /* SHA-224 Single-Round Known Answer Hashing Test. */
-    /***************************************************/
-
-    sha_status = SHA224_HashBuf( sha_computed_digest, known_hash_message,
-                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
-
-    if( ( sha_status != SECSuccess ) ||
-        ( PORT_Memcmp( sha_computed_digest, sha224_known_digest,
-                       SHA224_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    /***************************************************/
-    /* SHA-256 Single-Round Known Answer Hashing Test. */
-    /***************************************************/
-
-    sha_status = SHA256_HashBuf( sha_computed_digest, known_hash_message,
-                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
-
-    if( ( sha_status != SECSuccess ) ||
-        ( PORT_Memcmp( sha_computed_digest, sha256_known_digest,
-                       SHA256_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    /***************************************************/
-    /* SHA-384 Single-Round Known Answer Hashing Test. */
-    /***************************************************/
-
-    sha_status = SHA384_HashBuf( sha_computed_digest, known_hash_message,
-                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
-
-    if( ( sha_status != SECSuccess ) ||
-        ( PORT_Memcmp( sha_computed_digest, sha384_known_digest,
-                       SHA384_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    /***************************************************/
-    /* SHA-512 Single-Round Known Answer Hashing Test. */
-    /***************************************************/
-
-    sha_status = SHA512_HashBuf( sha_computed_digest, known_hash_message,
-                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
-
-    if( ( sha_status != SECSuccess ) ||
-        ( PORT_Memcmp( sha_computed_digest, sha512_known_digest,
-                       SHA512_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-}
-
-
-static CK_RV
-freebl_fipsSoftwareIntegrityTest(void)
-{
-    CK_RV crv = CKR_OK;
-
-    /* make sure that our check file signatures are OK */
-    if (!BLAPI_VerifySelf(SHLIB_PREFIX"freebl"SHLIB_VERSION"."SHLIB_SUFFIX)) {
-	crv = CKR_DEVICE_ERROR; /* better error code? checksum error? */
-    }
-    return crv;
-}
-
-CK_RV
-freebl_fipsPowerUpSelfTest( void )
-{
-    CK_RV rv;
-
-    /* MD2 Power-Up SelfTest(s). */
-    rv = freebl_fips_MD2_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* MD5 Power-Up SelfTest(s). */
-    rv = freebl_fips_MD5_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* SHA-X Power-Up SelfTest(s). */
-    rv = freebl_fips_SHA_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* Software/Firmware Integrity Test. */
-    rv = freebl_fipsSoftwareIntegrityTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* Passed Power-Up SelfTest(s). */
-    return( CKR_OK );
-}
+#include "blapii.h"
 
 struct NSSLOWInitContextStr {
    int count;
 };
 
 struct NSSLOWHASHContextStr {
     const SECHashObject *hashObj;
     void *hashCtxt;
@@ -271,61 +38,51 @@ static int nsslow_GetFIPSEnabled(void) {
     if (size != 1)
         return 0;
     if (d != '1')
         return 0;
 #endif
     return 1;
 }
 
-
-static int post = 0;
-static int post_failed = 0;
-
 static NSSLOWInitContext dummyContext = { 0 };
+static PRBool post_failed = PR_TRUE;
 
 NSSLOWInitContext *
 NSSLOW_Init(void)
 {
-    CK_RV crv;
 #ifdef FREEBL_NO_DEPEND
-    (void)FREEBL_InitStubs();
+    (void) FREEBL_InitStubs();
 #endif
 
-    if (post_failed) {
-	return NULL;
-    }
-	
-
-    if (!post && nsslow_GetFIPSEnabled()) {
-	crv = freebl_fipsPowerUpSelfTest();
-	if (crv != CKR_OK) {
-	    post_failed = 1;
+   /* make sure the FIPS product is installed if we are trying to
+    * go into FIPS mode */
+   if (nsslow_GetFIPSEnabled()) {
+	if (BL_FIPSEntryOK(PR_TRUE) != SECSuccess) {
+	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+	    post_failed = PR_TRUE;
 	    return NULL;
 	}
-    }
-    post = 1;
-
+   }
+   post_failed = PR_FALSE;
     
-    return &dummyContext;
+   return &dummyContext;
 }
 
 void
 NSSLOW_Shutdown(NSSLOWInitContext *context)
 {
    PORT_Assert(context == &dummyContext);
    return;
 }
 
 void
 NSSLOW_Reset(NSSLOWInitContext *context)
 {
    PORT_Assert(context == &dummyContext);
-   post_failed = 0;
-   post = 0;
    return;
 }
 
 NSSLOWHASHContext *
 NSSLOWHASH_NewContext(NSSLOWInitContext *initContext, 
 			HASH_HashType hashType)
 {
    NSSLOWHASHContext *context;
--- a/lib/freebl/pqg.c
+++ b/lib/freebl/pqg.c
@@ -696,16 +696,17 @@ step_23:
 	
 cleanup:
     mp_clear(&c);
     mp_clear(&c0_2);
     mp_clear(&t);
     mp_clear(&a);
     mp_clear(&z);
     mp_clear(&two_length_minus_1);
+    PORT_Memset(x, 0, sizeof(x));
     if (err) {
 	MP_TO_SEC_ERROR(err);
 	rv = SECFailure;
     }
     if (rv == SECFailure) {
 	mp_zero(prime);
 	if (prime_seed->data) {
 	    SECITEM_FreeItem(prime_seed, PR_FALSE);
@@ -851,16 +852,17 @@ step_5:
     }
     /* if (prime_gencont > 4*length), fall through to failure */
     rv = SECFailure; /* really is already set, but paranoia is good */
 	
 cleanup:
     mp_clear(&c);
     mp_clear(&c0);
     mp_clear(&one);
+    PORT_Memset(x, 0, sizeof(x));
     if (err) {
 	MP_TO_SEC_ERROR(err);
 	rv = SECFailure;
     }
     if (rv == SECFailure) {
 	mp_zero(prime);
 	if (prime_seed->data) {
 	    SECITEM_FreeItem(prime_seed, PR_FALSE);
@@ -1251,16 +1253,52 @@ pqg_ParamGen(unsigned int L, unsigned in
 
 
     /* Step 1. L and N already checked by caller*/
     /* Step 2. if (seedlen < N) return INVALID; */
     if (seedBytes < N/PR_BITS_PER_BYTE || !pParams || !pVfy) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return SECFailure;
     }
+
+    /* Initialize bignums */
+    MP_DIGITS(&P) = 0;
+    MP_DIGITS(&Q) = 0;
+    MP_DIGITS(&G) = 0;
+    MP_DIGITS(&H) = 0;
+    MP_DIGITS(&l) = 0;
+    MP_DIGITS(&p0) = 0;
+    CHECK_MPI_OK( mp_init(&P) );
+    CHECK_MPI_OK( mp_init(&Q) );
+    CHECK_MPI_OK( mp_init(&G) );
+    CHECK_MPI_OK( mp_init(&H) );
+    CHECK_MPI_OK( mp_init(&l) );
+    CHECK_MPI_OK( mp_init(&p0) );
+
+    /* parameters have been passed in, only generate G */
+    if (*pParams != NULL) {
+	/* we only support G index generation if generating separate from PQ */
+	if ((*pVfy != NULL) || (type == FIPS186_1_TYPE) || 
+	    ((*pVfy)->h.len != 1) || ((*pVfy)->h.data == NULL) || 
+	    ((*pVfy)->seed.data == NULL) || ((*pVfy)->seed.len == 0)) {
+	    PORT_SetError(SEC_ERROR_INVALID_ARGS);
+	    return SECFailure;
+	}
+	params = *pParams;
+	verify = *pVfy;
+
+	/* fill in P Q,  */
+	SECITEM_TO_MPINT((*pParams)->prime,    &P);
+	SECITEM_TO_MPINT((*pParams)->subPrime, &Q);
+    	hashtype = getFirstHash(L,N);
+	CHECK_SEC_OK(makeGfromIndex(hashtype, &P, &Q, &(*pVfy)->seed, 
+						(*pVfy)->h.data[0], &G) );
+	MPINT_TO_SECITEM(&G, &(*pParams)->base,     (*pParams)->arena);
+	goto cleanup;
+    }
     /* Initialize an arena for the params. */
     arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
     if (!arena) {
 	PORT_SetError(SEC_ERROR_NO_MEMORY);
 	return SECFailure;
     }
     params = (PQGParams *)PORT_ArenaZAlloc(arena, sizeof(PQGParams));
     if (!params) {
@@ -1508,18 +1546,22 @@ cleanup:
     mp_clear(&H);
     mp_clear(&l);
     mp_clear(&p0);
     if (err) {
 	MP_TO_SEC_ERROR(err);
 	rv = SECFailure;
     }
     if (rv) {
-	PORT_FreeArena(params->arena, PR_TRUE);
-	PORT_FreeArena(verify->arena, PR_TRUE);
+	if (params) {
+	    PORT_FreeArena(params->arena, PR_TRUE);
+	}
+	if (verify) {
+	    PORT_FreeArena(verify->arena, PR_TRUE);
+	}
     }
     if (hit.data) {
         SECITEM_FreeItem(&hit, PR_FALSE);
     }
     return rv;
 }
 
 SECStatus
--- a/lib/freebl/rijndael.c
+++ b/lib/freebl/rijndael.c
@@ -1163,16 +1163,17 @@ AES_InitContext(AESContext *cx, const un
     cx->worker_cx = NULL;
     cx->destroy = NULL;
     rv = aes_InitContext(cx, key, keysize, iv, basemode, 
 					baseencrypt, blocksize);
     if (rv != SECSuccess) {
 	AES_DestroyContext(cx, PR_FALSE);
 	return rv;
     }
+    cx->mode = mode;
 
     /* finally, set up any mode specific contexts */
     switch (mode) {
     case NSS_AES_CTS:
 	cx->worker_cx = CTS_CreateContext(cx, cx->worker, iv, blocksize);
 	cx->worker = (freeblCipherFunc) 
 			(encrypt ?  CTS_EncryptUpdate : CTS_DecryptUpdate);
 	cx->destroy = (freeblDestroyFunc) CTS_DestroyContext;
@@ -1286,16 +1287,33 @@ AES_Encrypt(AESContext *cx, unsigned cha
 	PORT_SetError(SEC_ERROR_INPUT_LEN);
 	return SECFailure;
     }
     if (maxOutputLen < inputLen) {
 	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
 	return SECFailure;
     }
     *outputLen = inputLen;
+#if  UINT_MAX > MP_32BIT_MAX
+    /*
+     * we can guarentee that GSM won't overlfow if we limit the input to
+     * 2^36 bytes. For simplicity, we are limiting it to 2^32 for now.
+     *
+     * We do it here to cover both hardware and software GCM operations.
+     */
+    PR_STATIC_ASSERT(sizeof(unsigned int) > 4);
+    if ((cx->mode == NSS_AES_GCM) && (inputLen > MP_32_BIT_MAX)) {
+	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+	return SECFailure;
+    }
+#else
+    /* if we can't pass in a 32_bit number, then no such check needed */
+    PR_STATIC_ASSERT(sizeof(unsigned int) <= 4);
+#endif
+
     return (*cx->worker)(cx->worker_cx, output, outputLen, maxOutputLen,	
                              input, inputLen, blocksize);
 }
 
 /*
  * AES_Decrypt
  *
  * Decrypt and arbitrary-length buffer.  The output buffer must already be
--- a/lib/freebl/rijndael.h
+++ b/lib/freebl/rijndael.h
@@ -57,11 +57,12 @@ struct AESContextStr
     freeblCipherFunc worker;
     /* NOTE: The offsets of iv and expandedKey are hardcoded in intel-aes.s.
      * Don't add new members before them without updating intel-aes.s. */
     unsigned char iv[RIJNDAEL_MAX_BLOCKSIZE];
     PRUint32      expandedKey[RIJNDAEL_MAX_EXP_KEY_SIZE];
     freeblDestroyFunc destroy;
     void	      *worker_cx;
     PRBool	      isBlock;
+    int           mode;
 };
 
 #endif /* _RIJNDAEL_H_ */
--- a/lib/freebl/rsa.c
+++ b/lib/freebl/rsa.c
@@ -133,17 +133,17 @@ rsa_build_from_primes(const mp_int *p, c
 
     /* at least one exponent must be given */
     PORT_Assert(!(needPublicExponent && needPrivateExponent));
 
     /* 2.  Compute phi = (p-1)*(q-1) */
     CHECK_MPI_OK( mp_sub_d(p, 1, &psub1) );
     CHECK_MPI_OK( mp_sub_d(q, 1, &qsub1) );
     if (needPublicExponent || needPrivateExponent) {
-	CHECK_MPI_OK( mp_mul(&psub1, &qsub1, &phi) );
+	CHECK_MPI_OK( mp_lcm(&psub1, &qsub1, &phi) );
 	/* 3.  Compute d = e**-1 mod(phi) */
 	/*     or      e = d**-1 mod(phi) as necessary */
 	if (needPublicExponent) {
 	    err = mp_invmod(d, &phi, e);
 	} else {
 	    err = mp_invmod(e, &phi, d);
 	}
     } else {
@@ -221,31 +221,71 @@ cleanup:
     if (err) {
 	MP_TO_SEC_ERROR(err);
 	rv = SECFailure;
     }
     return rv;
 }
 
 /*
+ *  make sure the key components meet fips186 requirements.
+ */
+static PRBool
+rsa_fips186_verify(mp_int *p, mp_int *q, mp_int *d, int keySizeInBits)
+{
+    mp_int pq_diff;
+    mp_err   err = MP_OKAY;
+    PRBool ret=PR_FALSE;
+
+    if (keySizeInBits < 250) {
+ 	/* not a valid FIPS length, no point in our other tests */
+	/* if you are here, and in FIPS mode, you are outside the security 
+  	 * policy */
+	return PR_TRUE;
+    }
+
+    /* p & q are already known to be greater then sqrt(2)*2^(keySize/2-1) */
+    /* we also know that gcd(p-1,e) = 1 and gcd(q-1,e) = 1 because the 
+     * mp_invmod() function will fail. */
+    /* now check p-q > 2^(keysize/2-100) */
+    MP_DIGITS(&pq_diff) = 0;
+    CHECK_MPI_OK( mp_init(&pq_diff) );
+    /* NSS always has p > q, so we know pq_diff is positive */
+    CHECK_MPI_OK( mp_sub(p,q,&pq_diff) );
+    if ((unsigned)mpl_significant_bits(&pq_diff) < (keySizeInBits/2 - 100)) {
+	goto cleanup;
+    }
+    /* now verify d is large enough*/
+    if ((unsigned)mpl_significant_bits(d) < (keySizeInBits/2)) {
+	goto cleanup;
+    }
+    ret = PR_TRUE;
+
+cleanup:
+    mp_clear(&pq_diff);
+    return ret;
+}
+
+/*
 ** Generate and return a new RSA public and private key.
 **	Both keys are encoded in a single RSAPrivateKey structure.
 **	"cx" is the random number generator context
 **	"keySizeInBits" is the size of the key to be generated, in bits.
 **	   512, 1024, etc.
 **	"publicExponent" when not NULL is a pointer to some data that
 **	   represents the public exponent to use. The data is a byte
 **	   encoded integer, in "big endian" order.
 */
 RSAPrivateKey *
 RSA_NewKey(int keySizeInBits, SECItem *publicExponent)
 {
     unsigned int primeLen;
     mp_int p, q, e, d;
     int kiter;
+    int max_attempts;
     mp_err   err = MP_OKAY;
     SECStatus rv = SECSuccess;
     int prerr = 0;
     RSAPrivateKey *key = NULL;
     PLArenaPool *arena = NULL;
     /* Require key size to be a multiple of 16 bits. */
     if (!publicExponent || keySizeInBits % 16 != 0 ||
 	    BAD_RSA_KEY_SIZE((unsigned int)keySizeInBits/8, publicExponent->len)) {
@@ -276,16 +316,17 @@ RSA_NewKey(int keySizeInBits, SECItem *p
     CHECK_MPI_OK( mp_init(&e) );
     CHECK_MPI_OK( mp_init(&d) );
     /* 2.  Set the version number (PKCS1 v1.5 says it should be zero) */
     SECITEM_AllocItem(arena, &key->version, 1);
     key->version.data[0] = 0;
     /* 3.  Set the public exponent */
     SECITEM_TO_MPINT(*publicExponent, &e);
     kiter = 0;
+    max_attempts = 5*(keySizeInBits/2); /* FIPS 186-4 B.3.3 steps 4.7 and 5.8 */
     do {
 	prerr = 0;
 	PORT_SetError(0);
 	CHECK_SEC_OK( generate_prime(&p, primeLen) );
 	CHECK_SEC_OK( generate_prime(&q, primeLen) );
 	/* Assure p > q */
 	/* NOTE: PKCS #1 does not require p > q, and NSS doesn't use any
 	 * implementation optimization that requires p > q. We can remove
@@ -293,22 +334,27 @@ RSA_NewKey(int keySizeInBits, SECItem *p
 	 */
 	if (mp_cmp(&p, &q) < 0)
 	    mp_exch(&p, &q);
 	/* Attempt to use these primes to generate a key */
 	rv = rsa_build_from_primes(&p, &q, 
 			&e, PR_FALSE,  /* needPublicExponent=false */
 			&d, PR_TRUE,   /* needPrivateExponent=true */
 			key, keySizeInBits);
-	if (rv == SECSuccess)
-	    break; /* generated two good primes */
-	prerr = PORT_GetError();
+	if (rv == SECSuccess) {
+	    if (rsa_fips186_verify(&p, &q, &d, keySizeInBits) ){
+		break;
+	    }
+	    prerr = SEC_ERROR_NEED_RANDOM; /* retry with different values */
+	} else {
+	    prerr = PORT_GetError();
+	}
 	kiter++;
 	/* loop until have primes */
-    } while (prerr == SEC_ERROR_NEED_RANDOM && kiter < MAX_KEY_GEN_ATTEMPTS);
+    } while (prerr == SEC_ERROR_NEED_RANDOM && kiter < max_attempts);
     if (prerr)
 	goto cleanup;
 cleanup:
     mp_clear(&p);
     mp_clear(&q);
     mp_clear(&e);
     mp_clear(&d);
     if (err) {
--- a/lib/freebl/shvfy.c
+++ b/lib/freebl/shvfy.c
@@ -11,16 +11,17 @@
 #include "prlink.h"
 #include "prio.h"
 #include "blapi.h"
 #include "seccomon.h"
 #include "stdio.h"
 #include "prmem.h"
 #include "hasht.h"
 #include "pqg.h"
+#include "blapii.h"
 
 /*
  * Most modern version of Linux support a speed optimization scheme where an
  * application called prelink modifies programs and shared libraries to quickly
  * load if they fit into an already designed address space. In short, prelink
  * scans the list of programs and libraries on your system, assigns them a
  * predefined space in the the address space, then provides the fixups to the
  * library.
@@ -268,39 +269,53 @@ readItem(PRFileDesc *fd, SECItem *item)
 	PORT_Free(item->data);
 	item->data = NULL;
 	item->len = 0;
 	return SECFailure;
     }
     return SECSuccess;
 }
 
-PRBool
-BLAPI_SHVerify(const char *name, PRFuncPtr addr)
+static PRBool blapi_SHVerifyFile(const char *shName, PRBool self);
+
+static PRBool
+blapi_SHVerify(const char *name, PRFuncPtr addr, PRBool self)
 {
     PRBool result = PR_FALSE; /* if anything goes wrong,
 			       * the signature does not verify */
     /* find our shared library name */
     char *shName = PR_GetLibraryFilePathname(name, addr);
     if (!shName) {
 	goto loser;
     }
-    result = BLAPI_SHVerifyFile(shName);
+    result = blapi_SHVerifyFile(shName, self);
 
 loser:
     if (shName != NULL) {
 	PR_Free(shName);
     }
 
     return result;
 }
 
 PRBool
+BLAPI_SHVerify(const char *name, PRFuncPtr addr)
+{
+    return blapi_SHVerify(name, addr, PR_FALSE);
+}
+
+PRBool
 BLAPI_SHVerifyFile(const char *shName)
 {
+    return blapi_SHVerifyFile(shName, PR_FALSE);
+}
+
+static PRBool
+blapi_SHVerifyFile(const char *shName, PRBool self)
+{
     char *checkName = NULL;
     PRFileDesc *checkFD = NULL;
     PRFileDesc *shFD = NULL;
     void  *hashcx = NULL;
     const SECHashObject *hashObj = NULL;
     SECItem signature = { 0, NULL, 0 };
     SECItem hash;
     int bytesRead, offset;
@@ -315,16 +330,22 @@ BLAPI_SHVerifyFile(const char *shName)
 			       * the signature does not verify */
     unsigned char buf[4096];
     unsigned char hashBuf[HASH_LENGTH_MAX];
 
     PORT_Memset(&key,0,sizeof(key));
     hash.data = hashBuf;
     hash.len = sizeof(hashBuf);
 
+    /* If our integrity check was never ran or failed, fail any other 
+     * integrity checks to prevent any token going into FIPS mode. */
+    if (!self && (BL_FIPSEntryOK(PR_FALSE) != SECSuccess)) {
+	return PR_FALSE;
+    }
+
     if (!shName) {
 	goto loser;
     }
 
     /* figure out the name of our check file */
     checkName = mkCheckFileName(shName);
     if (!checkName) {
 	goto loser;
@@ -499,10 +520,10 @@ BLAPI_VerifySelf(const char *name)
 {
     if (name == NULL) {
 	/*
 	 * If name is NULL, freebl is statically linked into softoken.
 	 * softoken will call BLAPI_SHVerify next to verify itself.
 	 */
 	return PR_TRUE;
     }
-    return BLAPI_SHVerify(name, (PRFuncPtr) decodeInt);
+    return blapi_SHVerify(name, (PRFuncPtr) decodeInt, PR_TRUE);
 }
--- a/lib/freebl/stubs.c
+++ b/lib/freebl/stubs.c
@@ -78,17 +78,17 @@
     if (ptr_##fn == NULL) { \
         return SECFailure; \
     }
 
 #else
 /*
  * this uses the loader weak attribute. it works automatically, but once
  * freebl is loaded, the symbols are 'fixed' (later loading of NSPR or 
- * libutil will not resolve these symbols.
+ * libutil will not resolve these symbols).
  */
 
 #define STUB_DECLARE(ret, fn,  args) \
    WEAK extern ret fn args
 
 #define STUB_SAFE_CALL0(fn) \
     if (fn) { return fn(); }
 #define STUB_SAFE_CALL1(fn,a1) \
@@ -111,16 +111,17 @@ STUB_DECLARE(void ,PORT_Free_Util,(void 
 STUB_DECLARE(void ,PORT_FreeArena_Util,(PLArenaPool *arena, PRBool zero));
 STUB_DECLARE(int,PORT_GetError_Util,(void));
 STUB_DECLARE(PLArenaPool *,PORT_NewArena_Util,(unsigned long chunksize));
 STUB_DECLARE(void,PORT_SetError_Util,(int value));
 STUB_DECLARE(void *,PORT_ZAlloc_Util,(size_t len));
 STUB_DECLARE(void,PORT_ZFree_Util,(void *ptr, size_t len));
 
 STUB_DECLARE(void,PR_Assert,(const char *s, const char *file, PRIntn ln));
+STUB_DECLARE(PRStatus,PR_Access,(const char *name, PRAccessHow how));
 STUB_DECLARE(PRStatus,PR_CallOnce,(PRCallOnceType *once, PRCallOnceFN func));
 STUB_DECLARE(PRStatus,PR_Close,(PRFileDesc *fd));
 STUB_DECLARE(void,PR_DestroyLock,(PRLock *lock));
 STUB_DECLARE(void,PR_DestroyCondVar,(PRCondVar *cvar));
 STUB_DECLARE(void,PR_Free,(void *ptr));
 STUB_DECLARE(char * ,PR_GetLibraryFilePathname,(const char *name,
 			PRFuncPtr addr));
 STUB_DECLARE(PRFileDesc *,PR_ImportPipe,(PROsfd osfd));
@@ -337,16 +338,38 @@ PR_Seek_stub(PRFileDesc *fd, PROffset32 
             break;
         case PR_SEEK_SET:
             break;
     }
 
     return lseek(*lfd, offset, lwhence);
 }
 
+PRStatus PR_Access_stub(const char *name, PRAccessHow how)
+{
+    int mode = F_OK;
+    int rv;
+    STUB_SAFE_CALL2(PR_Access, name, how);
+    switch (how) {
+    case PR_ACCESS_WRITE_OK:
+	mode = W_OK;
+	break;
+    case PR_ACCESS_READ_OK:
+	mode = R_OK;
+	break;
+    /* assume F_OK for all others */
+    default:
+	break;
+    }
+    rv = access(name, mode);
+    if (rv == 0) {
+	return PR_SUCCESS;
+    }
+    return PR_FAILURE;
+}
 
 /*
  * library 
  */
 extern char *
 PR_GetLibraryFilePathname_stub(const char *name, PRFuncPtr addr)
 {
     Dl_info dli;
@@ -562,16 +585,17 @@ freebl_InitNSPR(void *lib)
     STUB_FETCH_FUNCTION(PR_Free);
     STUB_FETCH_FUNCTION(PR_Open);
     STUB_FETCH_FUNCTION(PR_ImportPipe);
     STUB_FETCH_FUNCTION(PR_Close);
     STUB_FETCH_FUNCTION(PR_Read);
     STUB_FETCH_FUNCTION(PR_Seek);
     STUB_FETCH_FUNCTION(PR_GetLibraryFilePathname);
     STUB_FETCH_FUNCTION(PR_Assert);
+    STUB_FETCH_FUNCTION(PR_Access);
     STUB_FETCH_FUNCTION(PR_Sleep);
     STUB_FETCH_FUNCTION(PR_CallOnce);
     STUB_FETCH_FUNCTION(PR_NewCondVar);
     STUB_FETCH_FUNCTION(PR_NotifyCondVar);
     STUB_FETCH_FUNCTION(PR_NotifyAllCondVar);
     STUB_FETCH_FUNCTION(PR_WaitCondVar);
     STUB_FETCH_FUNCTION(PR_DestroyCondVar);
     STUB_FETCH_FUNCTION(PR_NewLock);
--- a/lib/freebl/stubs.h
+++ b/lib/freebl/stubs.h
@@ -35,16 +35,17 @@
 #define SECITEM_CompareItem  SECITEM_CompareItem_stub
 #define SECITEM_CopyItem  SECITEM_CopyItem_stub
 #define SECITEM_FreeItem  SECITEM_FreeItem_stub
 #define SECITEM_ZfreeItem  SECITEM_ZfreeItem_stub
 #define SECOID_FindOIDTag  SECOID_FindOIDTag_stub
 #define NSS_SecureMemcmp NSS_SecureMemcmp_stub
 
 #define PR_Assert  PR_Assert_stub
+#define PR_Access  PR_Access_stub
 #define PR_CallOnce  PR_CallOnce_stub
 #define PR_Close  PR_Close_stub
 #define PR_DestroyCondVar PR_DestroyCondVar_stub
 #define PR_DestroyLock  PR_DestroyLock_stub
 #define PR_Free  PR_Free_stub
 #define PR_GetLibraryFilePathname  PR_GetLibraryFilePathname_stub
 #define PR_ImportPipe  PR_ImportPipe_stub
 #define PR_Lock  PR_Lock_stub
--- a/lib/softoken/Makefile
+++ b/lib/softoken/Makefile
@@ -15,16 +15,26 @@ include manifest.mn
 #######################################################################
 
 include $(CORE_DEPTH)/coreconf/config.mk
 
 #######################################################################
 # (3) Include "component" configuration information. (OPTIONAL)       #
 #######################################################################
 
+ifdef NSS_NO_INIT_SUPPORT
+    DEFINES += -DNSS_NO_INIT_SUPPORT
+endif
+ifeq ($(OS_TARGET),Linux)
+ifeq ($(CPU_ARCH),ppc)
+ifdef USE_64
+    DEFINES += -DNSS_NO_INIT_SUPPORT
+endif # USE_64
+endif # ppc
+endif # Linux
 
 
 #######################################################################
 # (4) Include "local" platform-dependent assignments (OPTIONAL).      #
 #######################################################################
 
 include config.mk
 
--- a/lib/softoken/fipstest.c
+++ b/lib/softoken/fipstest.c
@@ -1,61 +1,77 @@
 /*
  * PKCS #11 FIPS Power-Up Self Test.
  *
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "softoken.h"   /* Required for RC2-ECB, RC2-CBC, RC4, DES-ECB,  */
-                        /*              DES-CBC, DES3-ECB, DES3-CBC, RSA */
-                        /*              and DSA.                         */
-#include "seccomon.h"   /* Required for RSA and DSA. */
-#include "lowkeyi.h"    /* Required for RSA and DSA. */
-#include "pkcs11.h"     /* Required for PKCS #11. */
+#include "seccomon.h"
+#include "blapi.h"
+#include "softoken.h"
+#include "lowkeyi.h"
+#include "secoid.h"
 #include "secerr.h"
 
-#ifndef NSS_DISABLE_ECC
-#include "ec.h"         /* Required for ECDSA */
+/*
+ * different platforms have different ways of calling and initial entry point
+ * when the dll/.so is loaded. Most platforms support either a posix pragma
+ * or the GCC attribute. Some platforms suppor a pre-defined name, and some
+ * platforms have a link line way of invoking this function.
+ */
+
+/* The pragma */
+#if defined(USE_INIT_PRAGMA)
+#pragma init(sftk_startup_tests)
+#endif
+
+/* GCC Attribute */
+#if defined(__GNUC__) && !defined(NSS_NO_INIT_SUPPORT)
+#define INIT_FUNCTION __attribute__((constructor))
+#else
+#define INIT_FUNCTION
 #endif
 
-
-/* FIPS preprocessor directives for RC2-ECB and RC2-CBC.        */
-#define FIPS_RC2_KEY_LENGTH                      5  /*  40-bits */
-#define FIPS_RC2_ENCRYPT_LENGTH                  8  /*  64-bits */
-#define FIPS_RC2_DECRYPT_LENGTH                  8  /*  64-bits */
-
+static void INIT_FUNCTION sftk_startup_tests(void);
 
-/* FIPS preprocessor directives for RC4.                        */
-#define FIPS_RC4_KEY_LENGTH                      5  /*  40-bits */
-#define FIPS_RC4_ENCRYPT_LENGTH                  8  /*  64-bits */
-#define FIPS_RC4_DECRYPT_LENGTH                  8  /*  64-bits */
-
-
-/* FIPS preprocessor directives for DES-ECB and DES-CBC.        */
-#define FIPS_DES_ENCRYPT_LENGTH                  8  /*  64-bits */
-#define FIPS_DES_DECRYPT_LENGTH                  8  /*  64-bits */
+/* Windows pre-defined entry */
+#ifdef XP_WIN
+#include <windows.h>
 
-
-/* FIPS preprocessor directives for DES3-CBC and DES3-ECB.      */
-#define FIPS_DES3_ENCRYPT_LENGTH                 8  /*  64-bits */
-#define FIPS_DES3_DECRYPT_LENGTH                 8  /*  64-bits */
-
+BOOL WINAPI DllMain(
+    HINSTANCE hinstDLL,  // handle to DLL module
+    DWORD fdwReason,     // reason for calling function
+    LPVOID lpReserved )  // reserved
+{
+    // Perform actions based on the reason for calling.
+    switch( fdwReason ) 
+    { 
+        case DLL_PROCESS_ATTACH:
+         // Initialize once for each new process.
+         // Return FALSE to fail DLL load.
+       sftk_startup_tests();
+            break;
 
-/* FIPS preprocessor directives for AES-ECB and AES-CBC.        */
-#define FIPS_AES_BLOCK_SIZE                     16  /* 128-bits */
-#define FIPS_AES_ENCRYPT_LENGTH                 16  /* 128-bits */
-#define FIPS_AES_DECRYPT_LENGTH                 16  /* 128-bits */
-#define FIPS_AES_128_KEY_SIZE                   16  /* 128-bits */
-#define FIPS_AES_192_KEY_SIZE                   24  /* 192-bits */
-#define FIPS_AES_256_KEY_SIZE                   32  /* 256-bits */
+        case DLL_THREAD_ATTACH:
+         // Do thread-specific initialization.
+            break;
+
+        case DLL_THREAD_DETACH:
+         // Do thread-specific cleanup.
+            break;
 
+        case DLL_PROCESS_DETACH:
+         // Perform any necessary cleanup.
+            break;
+    }
+    return TRUE;  // Successful DLL_PROCESS_ATTACH.
+}
+#endif
 
-/* FIPS preprocessor directives for message digests             */
-#define FIPS_KNOWN_HASH_MESSAGE_LENGTH          64  /* 512-bits */
 
 
 /* FIPS preprocessor directives for RSA.                         */
 #define FIPS_RSA_TYPE                           siBuffer
 #define FIPS_RSA_PUBLIC_EXPONENT_LENGTH           3 /*   24-bits */
 #define FIPS_RSA_PRIVATE_VERSION_LENGTH           1 /*    8-bits */
 #define FIPS_RSA_MESSAGE_LENGTH                 256 /* 2048-bits */
 #define FIPS_RSA_COEFFICIENT_LENGTH             128 /* 1024-bits */
@@ -64,1011 +80,18 @@
 #define FIPS_RSA_EXPONENT0_LENGTH               128 /* 1024-bits */
 #define FIPS_RSA_EXPONENT1_LENGTH               128 /* 1024-bits */
 #define FIPS_RSA_PRIVATE_EXPONENT_LENGTH        256 /* 2048-bits */
 #define FIPS_RSA_ENCRYPT_LENGTH                 256 /* 2048-bits */
 #define FIPS_RSA_DECRYPT_LENGTH                 256 /* 2048-bits */
 #define FIPS_RSA_SIGNATURE_LENGTH               256 /* 2048-bits */
 #define FIPS_RSA_MODULUS_LENGTH                 256 /* 2048-bits */
 
-
-/* FIPS preprocessor directives for DSA.                        */
-#define FIPS_DSA_TYPE                           siBuffer
-#define FIPS_DSA_DIGEST_LENGTH                  20 /*  160-bits */
-#define FIPS_DSA_SUBPRIME_LENGTH                20 /*  160-bits */
-#define FIPS_DSA_SIGNATURE_LENGTH               40 /*  320-bits */
-#define FIPS_DSA_PRIME_LENGTH                  128 /* 1024-bits */
-#define FIPS_DSA_BASE_LENGTH                   128 /* 1024-bits */
-
-/* FIPS preprocessor directives for RNG.                        */
-#define FIPS_RNG_XKEY_LENGTH                    32  /* 256-bits */
-
-static CK_RV
-sftk_fips_RC2_PowerUpSelfTest( void )
-{
-    /* RC2 Known Key (40-bits). */
-    static const PRUint8 rc2_known_key[] = { "RSARC" };
-
-    /* RC2-CBC Known Initialization Vector (64-bits). */
-    static const PRUint8 rc2_cbc_known_initialization_vector[] = {"Security"};
-
-    /* RC2 Known Plaintext (64-bits). */
-    static const PRUint8 rc2_ecb_known_plaintext[] = {"Netscape"};
-    static const PRUint8 rc2_cbc_known_plaintext[] = {"Netscape"};
-
-    /* RC2 Known Ciphertext (64-bits). */
-    static const PRUint8 rc2_ecb_known_ciphertext[] = {
-				  0x1a,0x71,0x33,0x54,0x8d,0x5c,0xd2,0x30};
-    static const PRUint8 rc2_cbc_known_ciphertext[] = {
-				  0xff,0x41,0xdb,0x94,0x8a,0x4c,0x33,0xb3};
-
-    /* RC2 variables. */
-    PRUint8        rc2_computed_ciphertext[FIPS_RC2_ENCRYPT_LENGTH];
-    PRUint8        rc2_computed_plaintext[FIPS_RC2_DECRYPT_LENGTH];
-    RC2Context *   rc2_context;
-    unsigned int   rc2_bytes_encrypted;
-    unsigned int   rc2_bytes_decrypted;
-    SECStatus      rc2_status;
-
-
-    /******************************************************/
-    /* RC2-ECB Single-Round Known Answer Encryption Test: */
-    /******************************************************/
-
-    rc2_context = RC2_CreateContext( rc2_known_key, FIPS_RC2_KEY_LENGTH,
-                                     NULL, NSS_RC2,
-                                     FIPS_RC2_KEY_LENGTH );
-
-    if( rc2_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    rc2_status = RC2_Encrypt( rc2_context, rc2_computed_ciphertext,
-                              &rc2_bytes_encrypted, FIPS_RC2_ENCRYPT_LENGTH,
-                              rc2_ecb_known_plaintext,
-                              FIPS_RC2_DECRYPT_LENGTH );
-
-    RC2_DestroyContext( rc2_context, PR_TRUE );
-
-    if( ( rc2_status != SECSuccess ) ||
-        ( rc2_bytes_encrypted != FIPS_RC2_ENCRYPT_LENGTH ) ||
-        ( PORT_Memcmp( rc2_computed_ciphertext, rc2_ecb_known_ciphertext,
-                       FIPS_RC2_ENCRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /******************************************************/
-    /* RC2-ECB Single-Round Known Answer Decryption Test: */
-    /******************************************************/
-
-    rc2_context = RC2_CreateContext( rc2_known_key, FIPS_RC2_KEY_LENGTH,
-                                     NULL, NSS_RC2,
-                                     FIPS_RC2_KEY_LENGTH );
-
-    if( rc2_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    rc2_status = RC2_Decrypt( rc2_context, rc2_computed_plaintext,
-                              &rc2_bytes_decrypted, FIPS_RC2_DECRYPT_LENGTH,
-                              rc2_ecb_known_ciphertext,
-                              FIPS_RC2_ENCRYPT_LENGTH );
-
-    RC2_DestroyContext( rc2_context, PR_TRUE );
-
-    if( ( rc2_status != SECSuccess ) ||
-        ( rc2_bytes_decrypted != FIPS_RC2_DECRYPT_LENGTH ) ||
-        ( PORT_Memcmp( rc2_computed_plaintext, rc2_ecb_known_plaintext,
-                       FIPS_RC2_DECRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /******************************************************/
-    /* RC2-CBC Single-Round Known Answer Encryption Test: */
-    /******************************************************/
-
-    rc2_context = RC2_CreateContext( rc2_known_key, FIPS_RC2_KEY_LENGTH,
-                                     rc2_cbc_known_initialization_vector,
-                                     NSS_RC2_CBC, FIPS_RC2_KEY_LENGTH );
-
-    if( rc2_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    rc2_status = RC2_Encrypt( rc2_context, rc2_computed_ciphertext,
-                              &rc2_bytes_encrypted, FIPS_RC2_ENCRYPT_LENGTH,
-                              rc2_cbc_known_plaintext,
-                              FIPS_RC2_DECRYPT_LENGTH );
-
-    RC2_DestroyContext( rc2_context, PR_TRUE );
-
-    if( ( rc2_status != SECSuccess ) ||
-        ( rc2_bytes_encrypted != FIPS_RC2_ENCRYPT_LENGTH ) ||
-        ( PORT_Memcmp( rc2_computed_ciphertext, rc2_cbc_known_ciphertext,
-                       FIPS_RC2_ENCRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /******************************************************/
-    /* RC2-CBC Single-Round Known Answer Decryption Test: */
-    /******************************************************/
-
-    rc2_context = RC2_CreateContext( rc2_known_key, FIPS_RC2_KEY_LENGTH,
-                                     rc2_cbc_known_initialization_vector,
-                                     NSS_RC2_CBC, FIPS_RC2_KEY_LENGTH );
-
-    if( rc2_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    rc2_status = RC2_Decrypt( rc2_context, rc2_computed_plaintext,
-                              &rc2_bytes_decrypted, FIPS_RC2_DECRYPT_LENGTH,
-                              rc2_cbc_known_ciphertext,
-                              FIPS_RC2_ENCRYPT_LENGTH );
-
-    RC2_DestroyContext( rc2_context, PR_TRUE );
-
-    if( ( rc2_status != SECSuccess ) ||
-        ( rc2_bytes_decrypted != FIPS_RC2_DECRYPT_LENGTH ) ||
-        ( PORT_Memcmp( rc2_computed_plaintext, rc2_ecb_known_plaintext,
-                       FIPS_RC2_DECRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-}
-
-
-static CK_RV
-sftk_fips_RC4_PowerUpSelfTest( void )
-{
-    /* RC4 Known Key (40-bits). */
-    static const PRUint8 rc4_known_key[] = { "RSARC" };
-
-    /* RC4 Known Plaintext (64-bits). */
-    static const PRUint8 rc4_known_plaintext[] = { "Netscape" };
-
-    /* RC4 Known Ciphertext (64-bits). */
-    static const PRUint8 rc4_known_ciphertext[] = {
-				0x29,0x33,0xc7,0x9a,0x9d,0x6c,0x09,0xdd};
-
-    /* RC4 variables. */
-    PRUint8        rc4_computed_ciphertext[FIPS_RC4_ENCRYPT_LENGTH];
-    PRUint8        rc4_computed_plaintext[FIPS_RC4_DECRYPT_LENGTH];
-    RC4Context *   rc4_context;
-    unsigned int   rc4_bytes_encrypted;
-    unsigned int   rc4_bytes_decrypted;
-    SECStatus      rc4_status;
-
-
-    /**************************************************/
-    /* RC4 Single-Round Known Answer Encryption Test: */
-    /**************************************************/
-
-    rc4_context = RC4_CreateContext( rc4_known_key, FIPS_RC4_KEY_LENGTH );
-
-    if( rc4_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    rc4_status = RC4_Encrypt( rc4_context, rc4_computed_ciphertext,
-                              &rc4_bytes_encrypted, FIPS_RC4_ENCRYPT_LENGTH,
-                              rc4_known_plaintext, FIPS_RC4_DECRYPT_LENGTH );
-
-    RC4_DestroyContext( rc4_context, PR_TRUE );
-
-    if( ( rc4_status != SECSuccess ) ||
-        ( rc4_bytes_encrypted != FIPS_RC4_ENCRYPT_LENGTH ) ||
-        ( PORT_Memcmp( rc4_computed_ciphertext, rc4_known_ciphertext,
-                       FIPS_RC4_ENCRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /**************************************************/
-    /* RC4 Single-Round Known Answer Decryption Test: */
-    /**************************************************/
-
-    rc4_context = RC4_CreateContext( rc4_known_key, FIPS_RC4_KEY_LENGTH );
-
-    if( rc4_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    rc4_status = RC4_Decrypt( rc4_context, rc4_computed_plaintext,
-                              &rc4_bytes_decrypted, FIPS_RC4_DECRYPT_LENGTH,
-                              rc4_known_ciphertext, FIPS_RC4_ENCRYPT_LENGTH );
-
-    RC4_DestroyContext( rc4_context, PR_TRUE );
-
-    if( ( rc4_status != SECSuccess ) ||
-        ( rc4_bytes_decrypted != FIPS_RC4_DECRYPT_LENGTH ) ||
-        ( PORT_Memcmp( rc4_computed_plaintext, rc4_known_plaintext,
-                       FIPS_RC4_DECRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-}
-
-
-static CK_RV
-sftk_fips_DES_PowerUpSelfTest( void )
-{
-    /* DES Known Key (56-bits). */
-    static const PRUint8 des_known_key[] = { "ANSI DES" };
-
-    /* DES-CBC Known Initialization Vector (64-bits). */
-    static const PRUint8 des_cbc_known_initialization_vector[] = { "Security" };
-
-    /* DES Known Plaintext (64-bits). */
-    static const PRUint8 des_ecb_known_plaintext[] = { "Netscape" };
-    static const PRUint8 des_cbc_known_plaintext[] = { "Netscape" };
-
-    /* DES Known Ciphertext (64-bits). */
-    static const PRUint8 des_ecb_known_ciphertext[] = {
-			       0x26,0x14,0xe9,0xc3,0x28,0x80,0x50,0xb0};
-    static const PRUint8 des_cbc_known_ciphertext[]  = {
-			       0x5e,0x95,0x94,0x5d,0x76,0xa2,0xd3,0x7d};
-
-    /* DES variables. */
-    PRUint8        des_computed_ciphertext[FIPS_DES_ENCRYPT_LENGTH];
-    PRUint8        des_computed_plaintext[FIPS_DES_DECRYPT_LENGTH];
-    DESContext *   des_context;
-    unsigned int   des_bytes_encrypted;
-    unsigned int   des_bytes_decrypted;
-    SECStatus      des_status;
-
-
-    /******************************************************/
-    /* DES-ECB Single-Round Known Answer Encryption Test: */
-    /******************************************************/
-
-    des_context = DES_CreateContext( des_known_key, NULL, NSS_DES, PR_TRUE );
-
-    if( des_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    des_status = DES_Encrypt( des_context, des_computed_ciphertext,
-                              &des_bytes_encrypted, FIPS_DES_ENCRYPT_LENGTH,
-                              des_ecb_known_plaintext,
-                              FIPS_DES_DECRYPT_LENGTH );
-
-    DES_DestroyContext( des_context, PR_TRUE );
-
-    if( ( des_status != SECSuccess ) ||
-        ( des_bytes_encrypted != FIPS_DES_ENCRYPT_LENGTH ) ||
-        ( PORT_Memcmp( des_computed_ciphertext, des_ecb_known_ciphertext,
-                       FIPS_DES_ENCRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /******************************************************/
-    /* DES-ECB Single-Round Known Answer Decryption Test: */
-    /******************************************************/
-
-    des_context = DES_CreateContext( des_known_key, NULL, NSS_DES, PR_FALSE );
-
-    if( des_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    des_status = DES_Decrypt( des_context, des_computed_plaintext,
-                              &des_bytes_decrypted, FIPS_DES_DECRYPT_LENGTH,
-                              des_ecb_known_ciphertext,
-                              FIPS_DES_ENCRYPT_LENGTH );
-
-    DES_DestroyContext( des_context, PR_TRUE );
-
-    if( ( des_status != SECSuccess ) ||
-        ( des_bytes_decrypted != FIPS_DES_DECRYPT_LENGTH ) ||
-        ( PORT_Memcmp( des_computed_plaintext, des_ecb_known_plaintext,
-                       FIPS_DES_DECRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /******************************************************/
-    /* DES-CBC Single-Round Known Answer Encryption Test. */
-    /******************************************************/
-
-    des_context = DES_CreateContext( des_known_key,
-                                     des_cbc_known_initialization_vector,
-                                     NSS_DES_CBC, PR_TRUE );
-
-    if( des_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    des_status = DES_Encrypt( des_context, des_computed_ciphertext,
-                              &des_bytes_encrypted, FIPS_DES_ENCRYPT_LENGTH,
-                              des_cbc_known_plaintext,
-                              FIPS_DES_DECRYPT_LENGTH );
-
-    DES_DestroyContext( des_context, PR_TRUE );
-
-    if( ( des_status != SECSuccess ) ||
-        ( des_bytes_encrypted != FIPS_DES_ENCRYPT_LENGTH ) ||
-        ( PORT_Memcmp( des_computed_ciphertext, des_cbc_known_ciphertext,
-                       FIPS_DES_ENCRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /******************************************************/
-    /* DES-CBC Single-Round Known Answer Decryption Test. */
-    /******************************************************/
-
-    des_context = DES_CreateContext( des_known_key,
-                                     des_cbc_known_initialization_vector,
-                                     NSS_DES_CBC, PR_FALSE );
-
-    if( des_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    des_status = DES_Decrypt( des_context, des_computed_plaintext,
-                              &des_bytes_decrypted, FIPS_DES_DECRYPT_LENGTH,
-                              des_cbc_known_ciphertext,
-                              FIPS_DES_ENCRYPT_LENGTH );
-
-    DES_DestroyContext( des_context, PR_TRUE );
-
-    if( ( des_status != SECSuccess ) ||
-        ( des_bytes_decrypted != FIPS_DES_DECRYPT_LENGTH ) ||
-        ( PORT_Memcmp( des_computed_plaintext, des_cbc_known_plaintext,
-                       FIPS_DES_DECRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-}
-
-
-static CK_RV
-sftk_fips_DES3_PowerUpSelfTest( void )
-{
-    /* DES3 Known Key (56-bits). */
-    static const PRUint8 des3_known_key[] = { "ANSI Triple-DES Key Data" };
-
-    /* DES3-CBC Known Initialization Vector (64-bits). */
-    static const PRUint8 des3_cbc_known_initialization_vector[] = { "Security" };
-
-    /* DES3 Known Plaintext (64-bits). */
-    static const PRUint8 des3_ecb_known_plaintext[] = { "Netscape" };
-    static const PRUint8 des3_cbc_known_plaintext[] = { "Netscape" };
-
-    /* DES3 Known Ciphertext (64-bits). */
-    static const PRUint8 des3_ecb_known_ciphertext[] = {
-			   0x55,0x8e,0xad,0x3c,0xee,0x49,0x69,0xbe};
-    static const PRUint8 des3_cbc_known_ciphertext[] = {
-			   0x43,0xdc,0x6a,0xc1,0xaf,0xa6,0x32,0xf5};
-
-    /* DES3 variables. */
-    PRUint8        des3_computed_ciphertext[FIPS_DES3_ENCRYPT_LENGTH];
-    PRUint8        des3_computed_plaintext[FIPS_DES3_DECRYPT_LENGTH];
-    DESContext *   des3_context;
-    unsigned int   des3_bytes_encrypted;
-    unsigned int   des3_bytes_decrypted;
-    SECStatus      des3_status;
-
-
-    /*******************************************************/
-    /* DES3-ECB Single-Round Known Answer Encryption Test. */
-    /*******************************************************/
-
-    des3_context = DES_CreateContext( des3_known_key, NULL,
-                                     NSS_DES_EDE3, PR_TRUE );
-
-    if( des3_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    des3_status = DES_Encrypt( des3_context, des3_computed_ciphertext,
-                               &des3_bytes_encrypted, FIPS_DES3_ENCRYPT_LENGTH,
-                               des3_ecb_known_plaintext,
-                               FIPS_DES3_DECRYPT_LENGTH );
-
-    DES_DestroyContext( des3_context, PR_TRUE );
-
-    if( ( des3_status != SECSuccess ) ||
-        ( des3_bytes_encrypted != FIPS_DES3_ENCRYPT_LENGTH ) ||
-        ( PORT_Memcmp( des3_computed_ciphertext, des3_ecb_known_ciphertext,
-                       FIPS_DES3_ENCRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /*******************************************************/
-    /* DES3-ECB Single-Round Known Answer Decryption Test. */
-    /*******************************************************/
-
-    des3_context = DES_CreateContext( des3_known_key, NULL,
-                                     NSS_DES_EDE3, PR_FALSE );
-
-    if( des3_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    des3_status = DES_Decrypt( des3_context, des3_computed_plaintext,
-                               &des3_bytes_decrypted, FIPS_DES3_DECRYPT_LENGTH,
-                               des3_ecb_known_ciphertext,
-                               FIPS_DES3_ENCRYPT_LENGTH );
-
-    DES_DestroyContext( des3_context, PR_TRUE );
-
-    if( ( des3_status != SECSuccess ) ||
-        ( des3_bytes_decrypted != FIPS_DES3_DECRYPT_LENGTH ) ||
-        ( PORT_Memcmp( des3_computed_plaintext, des3_ecb_known_plaintext,
-                       FIPS_DES3_DECRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /*******************************************************/
-    /* DES3-CBC Single-Round Known Answer Encryption Test. */
-    /*******************************************************/
-
-    des3_context = DES_CreateContext( des3_known_key,
-                                      des3_cbc_known_initialization_vector,
-                                      NSS_DES_EDE3_CBC, PR_TRUE );
-
-    if( des3_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    des3_status = DES_Encrypt( des3_context, des3_computed_ciphertext,
-                               &des3_bytes_encrypted, FIPS_DES3_ENCRYPT_LENGTH,
-                               des3_cbc_known_plaintext,
-                               FIPS_DES3_DECRYPT_LENGTH );
-
-    DES_DestroyContext( des3_context, PR_TRUE );
-
-    if( ( des3_status != SECSuccess ) ||
-        ( des3_bytes_encrypted != FIPS_DES3_ENCRYPT_LENGTH ) ||
-        ( PORT_Memcmp( des3_computed_ciphertext, des3_cbc_known_ciphertext,
-                       FIPS_DES3_ENCRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /*******************************************************/
-    /* DES3-CBC Single-Round Known Answer Decryption Test. */
-    /*******************************************************/
-
-    des3_context = DES_CreateContext( des3_known_key,
-                                      des3_cbc_known_initialization_vector,
-                                      NSS_DES_EDE3_CBC, PR_FALSE );
-
-    if( des3_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    des3_status = DES_Decrypt( des3_context, des3_computed_plaintext,
-                               &des3_bytes_decrypted, FIPS_DES3_DECRYPT_LENGTH,
-                               des3_cbc_known_ciphertext,
-                               FIPS_DES3_ENCRYPT_LENGTH );
-
-    DES_DestroyContext( des3_context, PR_TRUE );
-
-    if( ( des3_status != SECSuccess ) ||
-        ( des3_bytes_decrypted != FIPS_DES3_DECRYPT_LENGTH ) ||
-        ( PORT_Memcmp( des3_computed_plaintext, des3_cbc_known_plaintext,
-                       FIPS_DES3_DECRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-}
-
-
-/* AES self-test for 128-bit, 192-bit, or 256-bit key sizes*/
-static CK_RV
-sftk_fips_AES_PowerUpSelfTest( int aes_key_size )
-{
-    /* AES Known Key (up to 256-bits). */
-    static const PRUint8 aes_known_key[] = 
-        { "AES-128 RIJNDAELLEADNJIR 821-SEA" };
-
-    /* AES-CBC Known Initialization Vector (128-bits). */
-    static const PRUint8 aes_cbc_known_initialization_vector[] = 
-        { "SecurityytiruceS" };
-
-    /* AES Known Plaintext (128-bits). (blocksize is 128-bits) */
-    static const PRUint8 aes_known_plaintext[] = { "NetscapeepacsteN" };
-
-    /* AES Known Ciphertext (128-bit key). */
-    static const PRUint8 aes_ecb128_known_ciphertext[] = {
-        0x3c,0xa5,0x96,0xf3,0x34,0x6a,0x96,0xc1,
-        0x03,0x88,0x16,0x7b,0x20,0xbf,0x35,0x47 };
-
-    static const PRUint8 aes_cbc128_known_ciphertext[]  = {
-        0xcf,0x15,0x1d,0x4f,0x96,0xe4,0x4f,0x63,
-        0x15,0x54,0x14,0x1d,0x4e,0xd8,0xd5,0xea };
-
-    /* AES Known Ciphertext (192-bit key). */
-    static const PRUint8 aes_ecb192_known_ciphertext[] = { 
-        0xa0,0x18,0x62,0xed,0x88,0x19,0xcb,0x62,
-        0x88,0x1d,0x4d,0xfe,0x84,0x02,0x89,0x0e };
-
-    static const PRUint8 aes_cbc192_known_ciphertext[]  = { 
-        0x83,0xf7,0xa4,0x76,0xd1,0x6f,0x07,0xbe,
-        0x07,0xbc,0x43,0x2f,0x6d,0xad,0x29,0xe1 };
-
-    /* AES Known Ciphertext (256-bit key). */
-    static const PRUint8 aes_ecb256_known_ciphertext[] = { 
-        0xdb,0xa6,0x52,0x01,0x8a,0x70,0xae,0x66,
-        0x3a,0x99,0xd8,0x95,0x7f,0xfb,0x01,0x67 };
-    
-    static const PRUint8 aes_cbc256_known_ciphertext[]  = { 
-        0x37,0xea,0x07,0x06,0x31,0x1c,0x59,0x27,
-        0xc5,0xc5,0x68,0x71,0x6e,0x34,0x40,0x16 };
-
-    const PRUint8 *aes_ecb_known_ciphertext =
-        ( aes_key_size == FIPS_AES_128_KEY_SIZE) ? aes_ecb128_known_ciphertext :
-        ( aes_key_size == FIPS_AES_192_KEY_SIZE) ? aes_ecb192_known_ciphertext :
-                                aes_ecb256_known_ciphertext;
-
-    const PRUint8 *aes_cbc_known_ciphertext =
-        ( aes_key_size == FIPS_AES_128_KEY_SIZE) ? aes_cbc128_known_ciphertext :
-        ( aes_key_size == FIPS_AES_192_KEY_SIZE) ? aes_cbc192_known_ciphertext :
-                                aes_cbc256_known_ciphertext;
-
-    /* AES variables. */
-    PRUint8        aes_computed_ciphertext[FIPS_AES_ENCRYPT_LENGTH];
-    PRUint8        aes_computed_plaintext[FIPS_AES_DECRYPT_LENGTH];
-    AESContext *   aes_context;
-    unsigned int   aes_bytes_encrypted;
-    unsigned int   aes_bytes_decrypted;
-    SECStatus      aes_status;
-
-    /*check if aes_key_size is 128, 192, or 256 bits */
-    if ((aes_key_size != FIPS_AES_128_KEY_SIZE) && 
-        (aes_key_size != FIPS_AES_192_KEY_SIZE) && 
-        (aes_key_size != FIPS_AES_256_KEY_SIZE)) 
-            return( CKR_DEVICE_ERROR );
-
-    /******************************************************/
-    /* AES-ECB Single-Round Known Answer Encryption Test: */
-    /******************************************************/
-
-    aes_context = AES_CreateContext( aes_known_key, NULL, NSS_AES, PR_TRUE,
-                                     aes_key_size, FIPS_AES_BLOCK_SIZE );
-
-    if( aes_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    aes_status = AES_Encrypt( aes_context, aes_computed_ciphertext,
-                              &aes_bytes_encrypted, FIPS_AES_ENCRYPT_LENGTH,
-                              aes_known_plaintext,
-                              FIPS_AES_DECRYPT_LENGTH );
-    
-    AES_DestroyContext( aes_context, PR_TRUE );
-
-    if( ( aes_status != SECSuccess ) ||
-        ( aes_bytes_encrypted != FIPS_AES_ENCRYPT_LENGTH ) ||
-        ( PORT_Memcmp( aes_computed_ciphertext, aes_ecb_known_ciphertext,
-                       FIPS_AES_ENCRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /******************************************************/
-    /* AES-ECB Single-Round Known Answer Decryption Test: */
-    /******************************************************/
-
-    aes_context = AES_CreateContext( aes_known_key, NULL, NSS_AES, PR_FALSE,
-                                     aes_key_size, FIPS_AES_BLOCK_SIZE );
-
-    if( aes_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    aes_status = AES_Decrypt( aes_context, aes_computed_plaintext,
-                              &aes_bytes_decrypted, FIPS_AES_DECRYPT_LENGTH,
-                              aes_ecb_known_ciphertext,
-                              FIPS_AES_ENCRYPT_LENGTH );
-
-    AES_DestroyContext( aes_context, PR_TRUE );
-
-    if( ( aes_status != SECSuccess ) ||         
-        ( aes_bytes_decrypted != FIPS_AES_DECRYPT_LENGTH ) ||
-        ( PORT_Memcmp( aes_computed_plaintext, aes_known_plaintext,
-                       FIPS_AES_DECRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /******************************************************/
-    /* AES-CBC Single-Round Known Answer Encryption Test. */
-    /******************************************************/
-
-    aes_context = AES_CreateContext( aes_known_key,
-                                     aes_cbc_known_initialization_vector,
-                                     NSS_AES_CBC, PR_TRUE, aes_key_size, 
-                                     FIPS_AES_BLOCK_SIZE );
-
-    if( aes_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    aes_status = AES_Encrypt( aes_context, aes_computed_ciphertext,
-                              &aes_bytes_encrypted, FIPS_AES_ENCRYPT_LENGTH,
-                              aes_known_plaintext,
-                              FIPS_AES_DECRYPT_LENGTH );
-
-    AES_DestroyContext( aes_context, PR_TRUE );
-
-    if( ( aes_status != SECSuccess ) ||
-        ( aes_bytes_encrypted != FIPS_AES_ENCRYPT_LENGTH ) ||
-        ( PORT_Memcmp( aes_computed_ciphertext, aes_cbc_known_ciphertext,
-                       FIPS_AES_ENCRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-
-    /******************************************************/
-    /* AES-CBC Single-Round Known Answer Decryption Test. */
-    /******************************************************/
-
-    aes_context = AES_CreateContext( aes_known_key,
-                                     aes_cbc_known_initialization_vector,
-                                     NSS_AES_CBC, PR_FALSE, aes_key_size, 
-                                     FIPS_AES_BLOCK_SIZE );
-
-    if( aes_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    aes_status = AES_Decrypt( aes_context, aes_computed_plaintext,
-                              &aes_bytes_decrypted, FIPS_AES_DECRYPT_LENGTH,
-                              aes_cbc_known_ciphertext,
-                              FIPS_AES_ENCRYPT_LENGTH );
-
-    AES_DestroyContext( aes_context, PR_TRUE );
-
-    if( ( aes_status != SECSuccess ) ||
-        ( aes_bytes_decrypted != FIPS_AES_DECRYPT_LENGTH ) ||
-        ( PORT_Memcmp( aes_computed_plaintext, aes_known_plaintext,
-                       FIPS_AES_DECRYPT_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-}
-
-/* Known Hash Message (512-bits).  Used for all hashes (incl. SHA-N [N>1]). */
-static const PRUint8 known_hash_message[] = {
-  "The test message for the MD2, MD5, and SHA-1 hashing algorithms." };
-
-
-static CK_RV
-sftk_fips_MD2_PowerUpSelfTest( void )
-{
-    /* MD2 Known Digest Message (128-bits). */
-    static const PRUint8 md2_known_digest[]  = {
-                                   0x41,0x5a,0x12,0xb2,0x3f,0x28,0x97,0x17,
-                                   0x0c,0x71,0x4e,0xcc,0x40,0xc8,0x1d,0x1b};
-
-    /* MD2 variables. */
-    MD2Context * md2_context;
-    unsigned int md2_bytes_hashed;
-    PRUint8      md2_computed_digest[MD2_LENGTH];
-
-
-    /***********************************************/
-    /* MD2 Single-Round Known Answer Hashing Test. */
-    /***********************************************/
-
-    md2_context = MD2_NewContext();
-
-    if( md2_context == NULL )
-        return( CKR_HOST_MEMORY );
-
-    MD2_Begin( md2_context );
-
-    MD2_Update( md2_context, known_hash_message,
-                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
-
-    MD2_End( md2_context, md2_computed_digest, &md2_bytes_hashed, MD2_LENGTH );
-
-    MD2_DestroyContext( md2_context , PR_TRUE );
-    
-    if( ( md2_bytes_hashed != MD2_LENGTH ) ||
-        ( PORT_Memcmp( md2_computed_digest, md2_known_digest,
-                       MD2_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-}
-
-
-static CK_RV
-sftk_fips_MD5_PowerUpSelfTest( void )
-{
-    /* MD5 Known Digest Message (128-bits). */
-    static const PRUint8 md5_known_digest[]  = {
-				   0x25,0xc8,0xc0,0x10,0xc5,0x6e,0x68,0x28,
-				   0x28,0xa4,0xa5,0xd2,0x98,0x9a,0xea,0x2d};
-
-    /* MD5 variables. */
-    PRUint8        md5_computed_digest[MD5_LENGTH];
-    SECStatus      md5_status;
-
-
-    /***********************************************/
-    /* MD5 Single-Round Known Answer Hashing Test. */
-    /***********************************************/
-
-    md5_status = MD5_HashBuf( md5_computed_digest, known_hash_message,
-                              FIPS_KNOWN_HASH_MESSAGE_LENGTH );
-
-    if( ( md5_status != SECSuccess ) ||
-        ( PORT_Memcmp( md5_computed_digest, md5_known_digest,
-                       MD5_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-}
-
-/****************************************************/
-/* Single Round HMAC SHA-X test                     */
-/****************************************************/
-static SECStatus
-sftk_fips_HMAC(unsigned char *hmac_computed,
-               const PRUint8 *secret_key,
-               unsigned int secret_key_length,
-               const PRUint8 *message,
-               unsigned int message_length,
-               HASH_HashType hashAlg )
-{
-    SECStatus hmac_status = SECFailure;
-    HMACContext *cx = NULL;
-    SECHashObject *hashObj = NULL;
-    unsigned int bytes_hashed = 0;
-
-    hashObj = (SECHashObject *) HASH_GetRawHashObject(hashAlg);
- 
-    if (!hashObj) 
-        return( SECFailure );
-
-    cx = HMAC_Create(hashObj, secret_key, 
-                     secret_key_length, 
-                     PR_TRUE);  /* PR_TRUE for in FIPS mode */
-
-    if (cx == NULL) 
-        return( SECFailure );
-
-    HMAC_Begin(cx);
-    HMAC_Update(cx, message, message_length);
-    hmac_status = HMAC_Finish(cx, hmac_computed, &bytes_hashed, 
-                              hashObj->length);
-
-    HMAC_Destroy(cx, PR_TRUE);
-
-    return( hmac_status );
-}
-
-static CK_RV
-sftk_fips_HMAC_PowerUpSelfTest( void )
-{
-    static const PRUint8 HMAC_known_secret_key[] = {
-                         "Firefox and ThunderBird are awesome!"};
-
-    static const PRUint8 HMAC_known_secret_key_length 
-                         = sizeof HMAC_known_secret_key;
-
-    /* known SHA1 hmac (20 bytes) */
-    static const PRUint8 known_SHA1_hmac[] = {
-        0xd5, 0x85, 0xf6, 0x5b, 0x39, 0xfa, 0xb9, 0x05, 
-        0x3b, 0x57, 0x1d, 0x61, 0xe7, 0xb8, 0x84, 0x1e, 
-        0x5d, 0x0e, 0x1e, 0x11};
-
-    /* known SHA224 hmac (28 bytes) */
-    static const PRUint8 known_SHA224_hmac[] = {
-        0x1c, 0xc3, 0x06, 0x8e, 0xce, 0x37, 0x68, 0xfb, 
-        0x1a, 0x82, 0x4a, 0xbe, 0x2b, 0x00, 0x51, 0xf8,
-        0x9d, 0xb6, 0xe0, 0x90, 0x0d, 0x00, 0xc9, 0x64,
-        0x9a, 0xb8, 0x98, 0x4e};
-
-    /* known SHA256 hmac (32 bytes) */
-    static const PRUint8 known_SHA256_hmac[] = {
-        0x05, 0x75, 0x9a, 0x9e, 0x70, 0x5e, 0xe7, 0x44, 
-        0xe2, 0x46, 0x4b, 0x92, 0x22, 0x14, 0x22, 0xe0, 
-        0x1b, 0x92, 0x8a, 0x0c, 0xfe, 0xf5, 0x49, 0xe9, 
-        0xa7, 0x1b, 0x56, 0x7d, 0x1d, 0x29, 0x40, 0x48};        
-
-    /* known SHA384 hmac (48 bytes) */
-    static const PRUint8 known_SHA384_hmac[] = {
-        0xcd, 0x56, 0x14, 0xec, 0x05, 0x53, 0x06, 0x2b,
-        0x7e, 0x9c, 0x8a, 0x18, 0x5e, 0xea, 0xf3, 0x91,
-        0x33, 0xfb, 0x64, 0xf6, 0xe3, 0x9f, 0x89, 0x0b,
-        0xaf, 0xbe, 0x83, 0x4d, 0x3f, 0x3c, 0x43, 0x4d,
-        0x4a, 0x0c, 0x56, 0x98, 0xf8, 0xca, 0xb4, 0xaa,
-        0x9a, 0xf4, 0x0a, 0xaf, 0x4f, 0x69, 0xca, 0x87};
-
-    /* known SHA512 hmac (64 bytes) */
-    static const PRUint8 known_SHA512_hmac[] = {
-        0xf6, 0x0e, 0x97, 0x12, 0x00, 0x67, 0x6e, 0xb9,
-        0x0c, 0xb2, 0x63, 0xf0, 0x60, 0xac, 0x75, 0x62,
-        0x70, 0x95, 0x2a, 0x52, 0x22, 0xee, 0xdd, 0xd2,
-        0x71, 0xb1, 0xe8, 0x26, 0x33, 0xd3, 0x13, 0x27,
-        0xcb, 0xff, 0x44, 0xef, 0x87, 0x97, 0x16, 0xfb,
-        0xd3, 0x0b, 0x48, 0xbe, 0x12, 0x4e, 0xda, 0xb1,
-        0x89, 0x90, 0xfb, 0x06, 0x0c, 0xbe, 0xe5, 0xc4,
-        0xff, 0x24, 0x37, 0x3d, 0xc7, 0xe4, 0xe4, 0x37};
-
-    SECStatus    hmac_status;
-    PRUint8      hmac_computed[HASH_LENGTH_MAX]; 
-
-    /***************************************************/
-    /* HMAC SHA-1 Single-Round Known Answer HMAC Test. */
-    /***************************************************/
-
-    hmac_status = sftk_fips_HMAC(hmac_computed, 
-                                 HMAC_known_secret_key,
-                                 HMAC_known_secret_key_length,
-                                 known_hash_message,
-                                 FIPS_KNOWN_HASH_MESSAGE_LENGTH,
-                                 HASH_AlgSHA1); 
-
-    if( ( hmac_status != SECSuccess ) || 
-        ( PORT_Memcmp( hmac_computed, known_SHA1_hmac,
-                       SHA1_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    /***************************************************/
-    /* HMAC SHA-224 Single-Round Known Answer Test.    */
-    /***************************************************/
-
-    hmac_status = sftk_fips_HMAC(hmac_computed, 
-                                 HMAC_known_secret_key,
-                                 HMAC_known_secret_key_length,
-                                 known_hash_message,
-                                 FIPS_KNOWN_HASH_MESSAGE_LENGTH,
-                                 HASH_AlgSHA224);
-
-    if( ( hmac_status != SECSuccess ) || 
-        ( PORT_Memcmp( hmac_computed, known_SHA224_hmac,
-                       SHA224_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    /***************************************************/
-    /* HMAC SHA-256 Single-Round Known Answer Test.    */
-    /***************************************************/
-
-    hmac_status = sftk_fips_HMAC(hmac_computed, 
-                                 HMAC_known_secret_key,
-                                 HMAC_known_secret_key_length,
-                                 known_hash_message,
-                                 FIPS_KNOWN_HASH_MESSAGE_LENGTH,
-                                 HASH_AlgSHA256); 
-
-    if( ( hmac_status != SECSuccess ) || 
-        ( PORT_Memcmp( hmac_computed, known_SHA256_hmac,
-                       SHA256_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    /***************************************************/
-    /* HMAC SHA-384 Single-Round Known Answer Test.    */
-    /***************************************************/
-
-    hmac_status = sftk_fips_HMAC(hmac_computed,
-                                 HMAC_known_secret_key,
-                                 HMAC_known_secret_key_length,
-                                 known_hash_message,
-                                 FIPS_KNOWN_HASH_MESSAGE_LENGTH,
-                                 HASH_AlgSHA384);
-
-    if( ( hmac_status != SECSuccess ) ||
-        ( PORT_Memcmp( hmac_computed, known_SHA384_hmac,
-                       SHA384_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    /***************************************************/
-    /* HMAC SHA-512 Single-Round Known Answer Test.    */
-    /***************************************************/
-
-    hmac_status = sftk_fips_HMAC(hmac_computed,
-                                 HMAC_known_secret_key,
-                                 HMAC_known_secret_key_length,
-                                 known_hash_message,
-                                 FIPS_KNOWN_HASH_MESSAGE_LENGTH,
-                                 HASH_AlgSHA512);
-
-    if( ( hmac_status != SECSuccess ) ||
-        ( PORT_Memcmp( hmac_computed, known_SHA512_hmac,
-                       SHA512_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-}
-
-static CK_RV
-sftk_fips_SHA_PowerUpSelfTest( void )
-{
-    /* SHA-1 Known Digest Message (160-bits). */
-    static const PRUint8 sha1_known_digest[] = {
-			       0x0a,0x6d,0x07,0xba,0x1e,0xbd,0x8a,0x1b,
-			       0x72,0xf6,0xc7,0x22,0xf1,0x27,0x9f,0xf0,
-			       0xe0,0x68,0x47,0x7a};
-
-    /* SHA-224 Known Digest Message (224-bits). */
-    static const PRUint8 sha224_known_digest[] = {
-        0x89,0x5e,0x7f,0xfd,0x0e,0xd8,0x35,0x6f,
-        0x64,0x6d,0xf2,0xde,0x5e,0xed,0xa6,0x7f, 
-        0x29,0xd1,0x12,0x73,0x42,0x84,0x95,0x4f, 
-        0x8e,0x08,0xe5,0xcb};
-
-    /* SHA-256 Known Digest Message (256-bits). */
-    static const PRUint8 sha256_known_digest[] = {
-        0x38,0xa9,0xc1,0xf0,0x35,0xf6,0x5d,0x61,
-        0x11,0xd4,0x0b,0xdc,0xce,0x35,0x14,0x8d,
-        0xf2,0xdd,0xaf,0xaf,0xcf,0xb7,0x87,0xe9,
-        0x96,0xa5,0xd2,0x83,0x62,0x46,0x56,0x79};
- 
-    /* SHA-384 Known Digest Message (384-bits). */
-    static const PRUint8 sha384_known_digest[] = {
-        0x11,0xfe,0x1c,0x00,0x89,0x48,0xde,0xb3,
-        0x99,0xee,0x1c,0x18,0xb4,0x10,0xfb,0xfe,
-        0xe3,0xa8,0x2c,0xf3,0x04,0xb0,0x2f,0xc8,
-        0xa3,0xc4,0x5e,0xea,0x7e,0x60,0x48,0x7b,
-        0xce,0x2c,0x62,0xf7,0xbc,0xa7,0xe8,0xa3,
-        0xcf,0x24,0xce,0x9c,0xe2,0x8b,0x09,0x72};
-
-    /* SHA-512 Known Digest Message (512-bits). */
-    static const PRUint8 sha512_known_digest[] = {
-        0xc8,0xb3,0x27,0xf9,0x0b,0x24,0xc8,0xbf,
-        0x4c,0xba,0x33,0x54,0xf2,0x31,0xbf,0xdb,
-        0xab,0xfd,0xb3,0x15,0xd7,0xfa,0x48,0x99,
-        0x07,0x60,0x0f,0x57,0x41,0x1a,0xdd,0x28,
-        0x12,0x55,0x25,0xac,0xba,0x3a,0x99,0x12,
-        0x2c,0x7a,0x8f,0x75,0x3a,0xe1,0x06,0x6f,
-        0x30,0x31,0xc9,0x33,0xc6,0x1b,0x90,0x1a,
-        0x6c,0x98,0x9a,0x87,0xd0,0xb2,0xf8,0x07};
-
-    /* SHA-X variables. */
-    PRUint8        sha_computed_digest[HASH_LENGTH_MAX];
-    SECStatus      sha_status;
-
-    /*************************************************/
-    /* SHA-1 Single-Round Known Answer Hashing Test. */
-    /*************************************************/
-
-    sha_status = SHA1_HashBuf( sha_computed_digest, known_hash_message,
-                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
- 
-    if( ( sha_status != SECSuccess ) ||
-        ( PORT_Memcmp( sha_computed_digest, sha1_known_digest,
-                       SHA1_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    /***************************************************/
-    /* SHA-224 Single-Round Known Answer Hashing Test. */
-    /***************************************************/
-
-    sha_status = SHA224_HashBuf( sha_computed_digest, known_hash_message,
-                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
-
-    if( ( sha_status != SECSuccess ) ||
-        ( PORT_Memcmp( sha_computed_digest, sha224_known_digest,
-                       SHA224_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    /***************************************************/
-    /* SHA-256 Single-Round Known Answer Hashing Test. */
-    /***************************************************/
-
-    sha_status = SHA256_HashBuf( sha_computed_digest, known_hash_message,
-                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
-
-    if( ( sha_status != SECSuccess ) ||
-        ( PORT_Memcmp( sha_computed_digest, sha256_known_digest,
-                       SHA256_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    /***************************************************/
-    /* SHA-384 Single-Round Known Answer Hashing Test. */
-    /***************************************************/
-
-    sha_status = SHA384_HashBuf( sha_computed_digest, known_hash_message,
-                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
-
-    if( ( sha_status != SECSuccess ) ||
-        ( PORT_Memcmp( sha_computed_digest, sha384_known_digest,
-                       SHA384_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    /***************************************************/
-    /* SHA-512 Single-Round Known Answer Hashing Test. */
-    /***************************************************/
-
-    sha_status = SHA512_HashBuf( sha_computed_digest, known_hash_message,
-                                FIPS_KNOWN_HASH_MESSAGE_LENGTH );
-
-    if( ( sha_status != SECSuccess ) ||
-        ( PORT_Memcmp( sha_computed_digest, sha512_known_digest,
-                       SHA512_LENGTH ) != 0 ) )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-}
-
 /*
-* Single round RSA Signature Known Answer Test
+* Test the softoken RSA_HashSign and RSH_HashCheckSign.
 */
 static SECStatus
 sftk_fips_RSA_PowerUpSigSelfTest (HASH_HashType  shaAlg,
                                   NSSLOWKEYPublicKey *rsa_public_key,
                                   NSSLOWKEYPrivateKey *rsa_private_key,
                                   const unsigned char *rsa_known_msg,
                                   const unsigned int rsa_kmsg_length,
                                   const unsigned char *rsa_known_signature)
@@ -1150,17 +173,17 @@ sftk_fips_RSA_PowerUpSigSelfTest (HASH_H
     return( SECSuccess );
 
 loser:
 
     return( SECFailure );
 
 }
 
-static CK_RV
+static SECStatus
 sftk_fips_RSA_PowerUpSelfTest( void )
 {
     /* RSA Known Modulus used in both Public/Private Key Values (2048-bits). */
     static const PRUint8 rsa_modulus[FIPS_RSA_MODULUS_LENGTH] = {
                             0xb8, 0x15, 0x00, 0x33, 0xda, 0x0c, 0x9d, 0xa5,
                             0x14, 0x8c, 0xde, 0x1f, 0x23, 0x07, 0x54, 0xe2,
                             0xc6, 0xb9, 0x51, 0x04, 0xc9, 0x65, 0x24, 0x6e,
                             0x0a, 0x46, 0x34, 0x5c, 0x37, 0x86, 0x6b, 0x88,
@@ -1331,51 +354,16 @@ sftk_fips_RSA_PowerUpSelfTest( void )
                                          "for RSA Encryption &  Decryption"
                                          "blocks SHA256, SHA384  and      "
                                          "SHA512 RSA Signature KAT tests. "
                                          "Known plaintext message utilized"
                                          "for RSA Encryption &  Decryption"
                                          "blocks SHA256, SHA384  and      "
                                          "SHA512 RSA Signature KAT  tests."};
 
-    /* RSA Known Ciphertext (2048-bits). */
-    static const PRUint8 rsa_known_ciphertext[] = {
-                            0x04, 0x12, 0x46, 0xe3, 0x6a, 0xee, 0xde, 0xdd,
-                            0x49, 0xa1, 0xd9, 0x83, 0xf7, 0x35, 0xf9, 0x70,
-                            0x88, 0x03, 0x2d, 0x01, 0x8b, 0xd1, 0xbf, 0xdb,
-                            0xe5, 0x1c, 0x85, 0xbe, 0xb5, 0x0b, 0x48, 0x45,
-                            0x7a, 0xf0, 0xa0, 0xe3, 0xa2, 0xbb, 0x4b, 0xf6,
-                            0x27, 0xd0, 0x1b, 0x12, 0xe3, 0x77, 0x52, 0x34,
-                            0x9e, 0x8e, 0x03, 0xd2, 0xf8, 0x79, 0x6e, 0x39,
-                            0x79, 0x53, 0x3c, 0x44, 0x14, 0x94, 0xbb, 0x8d,
-                            0xaa, 0x14, 0x44, 0xa0, 0x7b, 0xa5, 0x8c, 0x93,
-                            0x5f, 0x99, 0xa4, 0xa3, 0x6e, 0x7a, 0x38, 0x40,
-                            0x78, 0xfa, 0x36, 0x91, 0x5e, 0x9a, 0x9c, 0xba,
-                            0x1e, 0xd4, 0xf9, 0xda, 0x4b, 0x0f, 0xa8, 0xa3,
-                            0x1c, 0xf3, 0x3a, 0xd1, 0xa5, 0xb4, 0x51, 0x16,
-                            0xed, 0x4b, 0xcf, 0xec, 0x93, 0x7b, 0x90, 0x21,
-                            0xbc, 0x3a, 0xf4, 0x0b, 0xd1, 0x3a, 0x2b, 0xba,
-                            0xa6, 0x7d, 0x5b, 0x53, 0xd8, 0x64, 0xf9, 0x29,
-                            0x7b, 0x7f, 0x77, 0x3e, 0x51, 0x4c, 0x9a, 0x94,
-                            0xd2, 0x4b, 0x4a, 0x8d, 0x61, 0x74, 0x97, 0xae,
-                            0x53, 0x6a, 0xf4, 0x90, 0xc2, 0x2c, 0x49, 0xe2,
-                            0xfa, 0xeb, 0x91, 0xc5, 0xe5, 0x83, 0x13, 0xc9,
-                            0x44, 0x4b, 0x95, 0x2c, 0x57, 0x70, 0x15, 0x5c,
-                            0x64, 0x8d, 0x1a, 0xfd, 0x2a, 0xc7, 0xb2, 0x9c,
-                            0x5c, 0x99, 0xd3, 0x4a, 0xfd, 0xdd, 0xf6, 0x82,
-                            0x87, 0x8c, 0x5a, 0xc4, 0xa8, 0x0d, 0x2a, 0xef,
-                            0xc3, 0xa2, 0x7e, 0x8e, 0x67, 0x9f, 0x6f, 0x63,
-                            0xdb, 0xbb, 0x1d, 0x31, 0xc4, 0xbb, 0xbc, 0x13,
-                            0x3f, 0x54, 0xc6, 0xf6, 0xc5, 0x28, 0x32, 0xab,
-                            0x96, 0x42, 0x10, 0x36, 0x40, 0x92, 0xbb, 0x57,
-                            0x55, 0x38, 0xf5, 0x43, 0x7e, 0x43, 0xc4, 0x65,
-                            0x47, 0x64, 0xaa, 0x0f, 0x4c, 0xe9, 0x49, 0x16,
-                            0xec, 0x6a, 0x50, 0xfd, 0x14, 0x49, 0xca, 0xdb,
-                            0x44, 0x54, 0xca, 0xbe, 0xa3, 0x0e, 0x5f, 0xef};
-
     /* RSA Known Signed Hash (2048-bits). */
     static const PRUint8 rsa_known_sha256_signature[] = {
                             0x8c, 0x2d, 0x2e, 0xfb, 0x37, 0xb5, 0x6f, 0x38,
                             0x9f, 0x06, 0x5a, 0xf3, 0x8c, 0xa0, 0xd0, 0x7a,
                             0xde, 0xcf, 0xf9, 0x14, 0x95, 0x59, 0xd3, 0x5f,
                             0x51, 0x5d, 0x5d, 0xad, 0xd8, 0x71, 0x33, 0x50,
                             0x1d, 0x03, 0x3b, 0x3a, 0x32, 0x00, 0xb4, 0xde,
                             0x7f, 0xe4, 0xb1, 0xe5, 0x6b, 0x83, 0xf4, 0x80,
@@ -1509,18 +497,16 @@ sftk_fips_RSA_PowerUpSelfTest( void )
     PLArenaPool *         rsa_private_arena;
 #endif
     NSSLOWKEYPublicKey *  rsa_public_key;
     NSSLOWKEYPrivateKey * rsa_private_key;
     SECStatus             rsa_status;
 
     NSSLOWKEYPublicKey    low_public_key   = { NULL, NSSLOWKEYRSAKey };
     NSSLOWKEYPrivateKey   low_private_key  = { NULL, NSSLOWKEYRSAKey };
-    PRUint8               rsa_computed_ciphertext[FIPS_RSA_ENCRYPT_LENGTH];
-    PRUint8               rsa_computed_plaintext[FIPS_RSA_DECRYPT_LENGTH];
 
     /****************************************/
     /* Compose RSA Public/Private Key Pair. */
     /****************************************/
 
     low_public_key.u.rsa  = bl_public_key;
     low_private_key.u.rsa = bl_private_key;
 
@@ -1528,60 +514,36 @@ sftk_fips_RSA_PowerUpSelfTest( void )
     rsa_private_key = &low_private_key;
 
 #ifdef CREATE_TEMP_ARENAS
     /* Create some space for the RSA public key. */
     rsa_public_arena = PORT_NewArena( NSS_SOFTOKEN_DEFAULT_CHUNKSIZE );
 
     if( rsa_public_arena == NULL ) {
         PORT_SetError( SEC_ERROR_NO_MEMORY );
-        return( CKR_HOST_MEMORY );
+        return( SECFailure );
     }
 
     /* Create some space for the RSA private key. */
     rsa_private_arena = PORT_NewArena( NSS_SOFTOKEN_DEFAULT_CHUNKSIZE );
 
     if( rsa_private_arena == NULL ) {
         PORT_FreeArena( rsa_public_arena, PR_TRUE );
         PORT_SetError( SEC_ERROR_NO_MEMORY );
-        return( CKR_HOST_MEMORY );
+        return( SECFailure );
     }
 
     rsa_public_key->arena = rsa_public_arena;
     rsa_private_key->arena = rsa_private_arena;
 #endif
 
     /**************************************************/
-    /* RSA Single-Round Known Answer Encryption Test. */
+    /* RSA Hash tests                                 */
     /**************************************************/
 
-    /* Perform RSA Public Key Encryption. */
-    rsa_status = RSA_PublicKeyOp(&rsa_public_key->u.rsa,
-                                 rsa_computed_ciphertext,
-                                 rsa_known_plaintext_msg);
-
-    if( ( rsa_status != SECSuccess ) ||
-        ( PORT_Memcmp( rsa_computed_ciphertext, rsa_known_ciphertext,
-                       FIPS_RSA_ENCRYPT_LENGTH ) != 0 ) )
-        goto rsa_loser;
-
-    /**************************************************/
-    /* RSA Single-Round Known Answer Decryption Test. */
-    /**************************************************/
-
-    /* Perform RSA Private Key Decryption. */
-    rsa_status = RSA_PrivateKeyOp(&rsa_private_key->u.rsa,
-                                  rsa_computed_plaintext,
-                                  rsa_known_ciphertext);
-
-    if( ( rsa_status != SECSuccess ) ||
-        ( PORT_Memcmp( rsa_computed_plaintext, rsa_known_plaintext_msg,
-                       FIPS_RSA_DECRYPT_LENGTH ) != 0 ) )
-        goto rsa_loser;
-
     rsa_status = sftk_fips_RSA_PowerUpSigSelfTest (HASH_AlgSHA256,
                            rsa_public_key, rsa_private_key,
                            rsa_known_plaintext_msg, FIPS_RSA_MESSAGE_LENGTH,
                            rsa_known_sha256_signature);
     if( rsa_status != SECSuccess )
         goto rsa_loser;
 
     rsa_status = sftk_fips_RSA_PowerUpSigSelfTest (HASH_AlgSHA384,
@@ -1597,504 +559,93 @@ sftk_fips_RSA_PowerUpSelfTest( void )
                            rsa_known_sha512_signature);
     if( rsa_status != SECSuccess )
         goto rsa_loser;
 
     /* Dispose of all RSA key material. */
     nsslowkey_DestroyPublicKey( rsa_public_key );
     nsslowkey_DestroyPrivateKey( rsa_private_key );
 
-    return( CKR_OK );
+    return( SECSuccess );
 
 rsa_loser:
 
     nsslowkey_DestroyPublicKey( rsa_public_key );
     nsslowkey_DestroyPrivateKey( rsa_private_key );
 
-    return( CKR_DEVICE_ERROR );
-}
-
-#ifndef NSS_DISABLE_ECC
-
-static CK_RV
-sftk_fips_ECDSA_Test(const PRUint8 *encodedParams, 
-                     unsigned int encodedParamsLen,
-                     const PRUint8 *knownSignature, 
-                     unsigned int knownSignatureLen) {
-
-    /* ECDSA Known Seed info for curves nistp256 and nistk283  */
-    static const PRUint8 ecdsa_Known_Seed[] = {
-                            0x6a, 0x9b, 0xf6, 0xf7, 0xce, 0xed, 0x79, 0x11,
-                            0xf0, 0xc7, 0xc8, 0x9a, 0xa5, 0xd1, 0x57, 0xb1,
-                            0x7b, 0x5a, 0x3b, 0x76, 0x4e, 0x7b, 0x7c, 0xbc,
-                            0xf2, 0x76, 0x1c, 0x1c, 0x7f, 0xc5, 0x53, 0x2f};
-
-    static const PRUint8 msg[] = {
-                            "Firefox and ThunderBird are awesome!"};
-
-    unsigned char sha1[SHA1_LENGTH];  /* SHA-1 hash (160 bits) */
-    unsigned char sig[2*MAX_ECKEY_LEN];
-    SECItem signature, digest;
-    SECItem encodedparams;
-    ECParams *ecparams = NULL;
-    ECPrivateKey *ecdsa_private_key = NULL;
-    ECPublicKey ecdsa_public_key;
-    SECStatus ecdsaStatus = SECSuccess;
-
-    /* construct the ECDSA private/public key pair */
-    encodedparams.type = siBuffer;
-    encodedparams.data = (unsigned char *) encodedParams;
-    encodedparams.len = encodedParamsLen;
-    
-    if (EC_DecodeParams(&encodedparams, &ecparams) != SECSuccess) {
-        return( CKR_DEVICE_ERROR );
-    }
-
-    /* Generates a new EC key pair. The private key is a supplied
-     * random value (in seed) and the public key is the result of 
-     * performing a scalar point multiplication of that value with 
-     * the curve's base point.
-     */
-    ecdsaStatus = EC_NewKeyFromSeed(ecparams, &ecdsa_private_key, 
-                                   ecdsa_Known_Seed, 
-                                   sizeof(ecdsa_Known_Seed));
-    /* free the ecparams they are no longer needed */
-    PORT_FreeArena(ecparams->arena, PR_FALSE);
-    ecparams = NULL;
-    if (ecdsaStatus != SECSuccess) {
-        return ( CKR_DEVICE_ERROR );    
-    }
-
-    /* construct public key from private key. */
-    ecdsaStatus = EC_CopyParams(ecdsa_private_key->ecParams.arena, 
-                                &ecdsa_public_key.ecParams,
-                                &ecdsa_private_key->ecParams);
-    if (ecdsaStatus != SECSuccess) {
-        goto loser;
-    }
-    ecdsa_public_key.publicValue = ecdsa_private_key->publicValue;
-
-    /* validate public key value */
-    ecdsaStatus = EC_ValidatePublicKey(&ecdsa_public_key.ecParams, 
-                                       &ecdsa_public_key.publicValue);
-    if (ecdsaStatus != SECSuccess) {
-        goto loser;
-    }
-
-    /* validate public key value */
-    ecdsaStatus = EC_ValidatePublicKey(&ecdsa_private_key->ecParams, 
-                                       &ecdsa_private_key->publicValue);
-    if (ecdsaStatus != SECSuccess) {
-        goto loser;
-    }
-
-    /***************************************************/
-    /* ECDSA Single-Round Known Answer Signature Test. */
-    /***************************************************/
-    
-    ecdsaStatus = SHA1_HashBuf(sha1, msg, sizeof msg);
-    if (ecdsaStatus != SECSuccess) {
-        goto loser;
-    }
-    digest.type = siBuffer;
-    digest.data = sha1;
-    digest.len = SHA1_LENGTH;
-    
-    memset(sig, 0, sizeof sig);
-    signature.type = siBuffer;
-    signature.data = sig;
-    signature.len = sizeof sig;
-    
-    ecdsaStatus = ECDSA_SignDigestWithSeed(ecdsa_private_key, &signature, 
-                         &digest, ecdsa_Known_Seed, sizeof ecdsa_Known_Seed);
-    if (ecdsaStatus != SECSuccess) {
-        goto loser;
-    }
-
-    if( ( signature.len != knownSignatureLen ) ||
-        ( PORT_Memcmp( signature.data, knownSignature,
-                    knownSignatureLen ) != 0 ) ) {
-        ecdsaStatus = SECFailure;
-        goto loser;
-    }
-    
-    /******************************************************/
-    /* ECDSA Single-Round Known Answer Verification Test. */
-    /******************************************************/
-
-    /* Perform ECDSA verification process. */
-    ecdsaStatus = ECDSA_VerifyDigest(&ecdsa_public_key, &signature, &digest);
-
-loser:
-    /* free the memory for the private key arena*/
-    if (ecdsa_private_key != NULL) {
-        PORT_FreeArena(ecdsa_private_key->ecParams.arena, PR_FALSE);
-    }
-
-    if (ecdsaStatus != SECSuccess) {
-        return CKR_DEVICE_ERROR ;
-    }
-    return( CKR_OK );
-}
-
-static CK_RV
-sftk_fips_ECDSA_PowerUpSelfTest() {
-
-   /* ECDSA Known curve nistp256 == SEC_OID_SECG_EC_SECP256R1 params */
-    static const PRUint8 ecdsa_known_P256_EncodedParams[] = {
-                            0x06,0x08,0x2a,0x86,0x48,0xce,0x3d,0x03,
-                            0x01,0x07};
-
-    static const PRUint8 ecdsa_known_P256_signature[] = {
-                            0x07,0xb1,0xcb,0x57,0x20,0xa7,0x10,0xd6, 
-                            0x9d,0x37,0x4b,0x1c,0xdc,0x35,0x90,0xff, 
-                            0x1a,0x2d,0x98,0x95,0x1b,0x2f,0xeb,0x7f, 
-                            0xbb,0x81,0xca,0xc0,0x69,0x75,0xea,0xc5,
-                            0x59,0x6a,0x62,0x49,0x3d,0x50,0xc9,0xe1, 
-                            0x27,0x3b,0xff,0x9b,0x13,0x66,0x67,0xdd, 
-                            0x7d,0xd1,0x0d,0x2d,0x7c,0x44,0x04,0x1b, 
-                            0x16,0x21,0x12,0xc5,0xcb,0xbd,0x9e,0x75};
-
-#ifdef NSS_ECC_MORE_THAN_SUITE_B
-    /* ECDSA Known curve nistk283 == SEC_OID_SECG_EC_SECT283K1 params */
-    static const PRUint8 ecdsa_known_K283_EncodedParams[] = {
-                            0x06,0x05,0x2b,0x81,0x04,0x00,0x10};
-                         
-    static const PRUint8 ecdsa_known_K283_signature[] = {
-                            0x00,0x45,0x88,0xc0,0x79,0x09,0x07,0xd1, 
-                            0x4e,0x88,0xe6,0xd5,0x2f,0x22,0x04,0x74, 
-                            0x35,0x24,0x65,0xe8,0x15,0xde,0x90,0x66, 
-                            0x94,0x70,0xdd,0x3a,0x14,0x70,0x02,0xd1,
-                            0xef,0x86,0xbd,0x15,0x00,0xd9,0xdc,0xfc, 
-                            0x87,0x2e,0x7c,0x99,0xe2,0xe3,0x79,0xb8, 
-                            0xd9,0x10,0x49,0x78,0x4b,0x59,0x8b,0x05, 
-                            0x77,0xec,0x6c,0xe8,0x35,0xe6,0x2e,0xa9,
-                            0xf9,0x77,0x1f,0x71,0x86,0xa5,0x4a,0xd0};
-#endif
-
-    CK_RV crv;
-
-    /* ECDSA GF(p) prime field curve test */
-    crv = sftk_fips_ECDSA_Test(ecdsa_known_P256_EncodedParams,
-                               sizeof ecdsa_known_P256_EncodedParams,
-                               ecdsa_known_P256_signature,
-                               sizeof ecdsa_known_P256_signature );
-    if (crv != CKR_OK) {
-        return( CKR_DEVICE_ERROR );
-    }
-
-#ifdef NSS_ECC_MORE_THAN_SUITE_B
-    /* ECDSA GF(2m) binary field curve test */
-    crv = sftk_fips_ECDSA_Test(ecdsa_known_K283_EncodedParams,
-                               sizeof ecdsa_known_K283_EncodedParams,
-                               ecdsa_known_K283_signature,
-                               sizeof ecdsa_known_K283_signature );
-    if (crv != CKR_OK) {
-        return( CKR_DEVICE_ERROR );
-    }
-#endif
-
-    return( CKR_OK );
+    PORT_SetError( SEC_ERROR_LIBRARY_FAILURE );
+    return( SECFailure );
 }
 
-#endif /* NSS_DISABLE_ECC */
+
+static PRBool sftk_self_tests_ran = PR_FALSE;
+static PRBool sftk_self_tests_success = PR_FALSE;
 
-static CK_RV
-sftk_fips_DSA_PowerUpSelfTest( void )
+/*
+ * This function is called at dll load time, the code tha makes this 
+ * happen is platform specific on defined above.
+ */ 
+static void
+sftk_startup_tests(void)
 {
-    /* DSA Known P (1024-bits), Q (160-bits), and G (1024-bits) Values. */
-    static const PRUint8 dsa_P[] = {
-         0x80,0xb0,0xd1,0x9d,0x6e,0xa4,0xf3,0x28, 
-         0x9f,0x24,0xa9,0x8a,0x49,0xd0,0x0c,0x63, 
-         0xe8,0x59,0x04,0xf9,0x89,0x4a,0x5e,0xc0, 
-         0x6d,0xd2,0x67,0x6b,0x37,0x81,0x83,0x0c,
-         0xfe,0x3a,0x8a,0xfd,0xa0,0x3b,0x08,0x91, 
-         0x1c,0xcb,0xb5,0x63,0xb0,0x1c,0x70,0xd0, 
-         0xae,0xe1,0x60,0x2e,0x12,0xeb,0x54,0xc7, 
-         0xcf,0xc6,0xcc,0xae,0x97,0x52,0x32,0x63,
-         0xd3,0xeb,0x55,0xea,0x2f,0x4c,0xd5,0xd7, 
-         0x3f,0xda,0xec,0x49,0x27,0x0b,0x14,0x56, 
-         0xc5,0x09,0xbe,0x4d,0x09,0x15,0x75,0x2b, 
-         0xa3,0x42,0x0d,0x03,0x71,0xdf,0x0f,0xf4,
-         0x0e,0xe9,0x0c,0x46,0x93,0x3d,0x3f,0xa6, 
-         0x6c,0xdb,0xca,0xe5,0xac,0x96,0xc8,0x64, 
-         0x5c,0xec,0x4b,0x35,0x65,0xfc,0xfb,0x5a, 
-         0x1b,0x04,0x1b,0xa1,0x0e,0xfd,0x88,0x15};
-        
-    static const PRUint8 dsa_Q[] = {
-         0xad,0x22,0x59,0xdf,0xe5,0xec,0x4c,0x6e, 
-         0xf9,0x43,0xf0,0x4b,0x2d,0x50,0x51,0xc6, 
-         0x91,0x99,0x8b,0xcf};
-        
-    static const PRUint8 dsa_G[] = {
-         0x78,0x6e,0xa9,0xd8,0xcd,0x4a,0x85,0xa4, 
-         0x45,0xb6,0x6e,0x5d,0x21,0x50,0x61,0xf6, 
-         0x5f,0xdf,0x5c,0x7a,0xde,0x0d,0x19,0xd3, 
-         0xc1,0x3b,0x14,0xcc,0x8e,0xed,0xdb,0x17,
-         0xb6,0xca,0xba,0x86,0xa9,0xea,0x51,0x2d, 
-         0xc1,0xa9,0x16,0xda,0xf8,0x7b,0x59,0x8a, 
-         0xdf,0xcb,0xa4,0x67,0x00,0x44,0xea,0x24, 
-         0x73,0xe5,0xcb,0x4b,0xaf,0x2a,0x31,0x25,
-         0x22,0x28,0x3f,0x16,0x10,0x82,0xf7,0xeb, 
-         0x94,0x0d,0xdd,0x09,0x22,0x14,0x08,0x79, 
-         0xba,0x11,0x0b,0xf1,0xff,0x2d,0x67,0xac, 
-         0xeb,0xb6,0x55,0x51,0x69,0x97,0xa7,0x25,
-         0x6b,0x9c,0xa0,0x9b,0xd5,0x08,0x9b,0x27, 
-         0x42,0x1c,0x7a,0x69,0x57,0xe6,0x2e,0xed, 
-         0xa9,0x5b,0x25,0xe8,0x1f,0xd2,0xed,0x1f, 
-         0xdf,0xe7,0x80,0x17,0xba,0x0d,0x4d,0x38};
-
-    /* DSA Known Random Values (known random key block       is 160-bits)  */
-    /*                     and (known random signature block is 160-bits). */
-    static const PRUint8 dsa_known_random_key_block[] = {
-                                                      "Mozilla Rules World!"};
-    static const PRUint8 dsa_known_random_signature_block[] = {
-                                                      "Random DSA Signature"};
-
-    /* DSA Known Digest (160-bits) */
-    static const PRUint8 dsa_known_digest[] = { "DSA Signature Digest" };
+    SECStatus rv;
+    const char *libraryName = SOFTOKEN_LIB_NAME;
 
-    /* DSA Known Signature (320-bits). */
-    static const PRUint8 dsa_known_signature[] = {
-        0x25,0x7c,0x3a,0x79,0x32,0x45,0xb7,0x32, 
-        0x70,0xca,0x62,0x63,0x2b,0xf6,0x29,0x2c, 
-        0x22,0x2a,0x03,0xce,0x48,0x15,0x11,0x72, 
-        0x7b,0x7e,0xf5,0x7a,0xf3,0x10,0x3b,0xde,
-        0x34,0xc1,0x9e,0xd7,0x27,0x9e,0x77,0x38};
-
-    /* DSA variables. */
-    DSAPrivateKey *        dsa_private_key;
-    SECStatus              dsa_status;
-    SECItem                dsa_signature_item;
-    SECItem                dsa_digest_item;
-    DSAPublicKey           dsa_public_key;
-    PRUint8                dsa_computed_signature[FIPS_DSA_SIGNATURE_LENGTH];
-    static const PQGParams dsa_pqg = { NULL,
-			    { FIPS_DSA_TYPE, (unsigned char *)dsa_P, FIPS_DSA_PRIME_LENGTH },
-			    { FIPS_DSA_TYPE, (unsigned char *)dsa_Q, FIPS_DSA_SUBPRIME_LENGTH },
-			    { FIPS_DSA_TYPE, (unsigned char *)dsa_G, FIPS_DSA_BASE_LENGTH }};
-
-    /*******************************************/
-    /* Generate a DSA public/private key pair. */
-    /*******************************************/
-
-    /* Generate a DSA public/private key pair. */
-    dsa_status = DSA_NewKeyFromSeed(&dsa_pqg, dsa_known_random_key_block,
-                                    &dsa_private_key);
-
-    if( dsa_status != SECSuccess )
-        return( CKR_HOST_MEMORY );
+    PORT_Assert(!sftk_self_tests_ran);
+    PORT_Assert(!sftk_self_tests_success);
+    sftk_self_tests_ran = PR_TRUE;
+    sftk_self_tests_success = PR_FALSE; /* just in case */
 
-    /* construct public key from private key. */
-    dsa_public_key.params      = dsa_private_key->params;
-    dsa_public_key.publicValue = dsa_private_key->publicValue;
-
-    /*************************************************/
-    /* DSA Single-Round Known Answer Signature Test. */
-    /*************************************************/
-
-    dsa_signature_item.data = dsa_computed_signature;
-    dsa_signature_item.len  = sizeof dsa_computed_signature;
-
-    dsa_digest_item.data    = (unsigned char *)dsa_known_digest;
-    dsa_digest_item.len     = SHA1_LENGTH;
-
-    /* Perform DSA signature process. */
-    dsa_status = DSA_SignDigestWithSeed( dsa_private_key, 
-                                         &dsa_signature_item,
-                                         &dsa_digest_item,
-                                         dsa_known_random_signature_block );
-
-    if( ( dsa_status != SECSuccess ) ||
-        ( dsa_signature_item.len != FIPS_DSA_SIGNATURE_LENGTH ) ||
-        ( PORT_Memcmp( dsa_computed_signature, dsa_known_signature,
-                       FIPS_DSA_SIGNATURE_LENGTH ) != 0 ) ) {
-        dsa_status = SECFailure;
-    } else {
-
-    /****************************************************/
-    /* DSA Single-Round Known Answer Verification Test. */
-    /****************************************************/
-
-    /* Perform DSA verification process. */
-    dsa_status = DSA_VerifyDigest( &dsa_public_key, 
-                                   &dsa_signature_item,
-                                   &dsa_digest_item);
+    /* need to initiallize the oid library before the RSA tests */
+    rv = SECOID_Init(); 
+    if (rv != SECSuccess) {
+       return;
+    }
+    /* make sure freebl is initialized, or our RSA check 
+     * may fail. This is normally done at freebl load time, but it's 
+     * possible we may have shut freebl down without unloading it. */
+    rv = BL_Init(); 
+    if (rv != SECSuccess) {
+       return;
     }
 
-    PORT_FreeArena(dsa_private_key->params.arena, PR_TRUE);
-    /* Don't free public key, it uses same arena as private key */
-
-    /* Verify DSA signature. */
-    if( dsa_status != SECSuccess )
-        return( CKR_DEVICE_ERROR );
-
-    return( CKR_OK );
-
-
+    rv = RNG_RNGInit(); 
+    if (rv != SECSuccess) {
+       return;
+    }
+    /* check the RSA combined functions in softoken */
+    rv = sftk_fips_RSA_PowerUpSelfTest();
+    if (rv !=SECSuccess) {
+       return;
+    }
+    if (!BLAPI_SHVerify(libraryName, 
+                               (PRFuncPtr) &sftk_fips_RSA_PowerUpSelfTest)) {
+           /* something is wrong with the library, fail without enabling
+            * the token */
+           return;
+    }
+    sftk_self_tests_success = PR_TRUE;
 }
 
-static CK_RV
-sftk_fips_RNG_PowerUpSelfTest( void )
-{
-   static const PRUint8 Q[] = {
-			0x85,0x89,0x9c,0x77,0xa3,0x79,0xff,0x1a,
-			0x86,0x6f,0x2f,0x3e,0x2e,0xf9,0x8c,0x9c,
-			0x9d,0xef,0xeb,0xed};
-   static const PRUint8 GENX[] = {
-			0x65,0x48,0xe3,0xca,0xac,0x64,0x2d,0xf7,
-			0x7b,0xd3,0x4e,0x79,0xc9,0x7d,0xa6,0xa8,
-			0xa2,0xc2,0x1f,0x8f,0xe9,0xb9,0xd3,0xa1,
-			0x3f,0xf7,0x0c,0xcd,0xa6,0xca,0xbf,0xce,
-			0x84,0x0e,0xb6,0xf1,0x0d,0xbe,0xa9,0xa3};
-   static const PRUint8 rng_known_DSAX[] = {
-			0x7a,0x86,0xf1,0x7f,0xbd,0x4e,0x6e,0xd9,
-			0x0a,0x26,0x21,0xd0,0x19,0xcb,0x86,0x73,
-			0x10,0x1f,0x60,0xd7};
 
-
-
-   SECStatus rng_status = SECSuccess;
-   PRUint8 DSAX[FIPS_DSA_SUBPRIME_LENGTH];
-
-   /*******************************************/
-   /*   Run the SP 800-90 Health tests        */
-   /*******************************************/
-   rng_status = PRNGTEST_RunHealthTests();
-   if (rng_status != SECSuccess) {
-	return (CKR_DEVICE_ERROR);
-   }
-  
-   /*******************************************/
-   /* Generate DSAX fow given Q.              */
-   /*******************************************/
-
-   rng_status = FIPS186Change_ReduceModQForDSA(GENX, Q, DSAX);
-
-   /* Verify DSAX to perform the RNG integrity check */
-   if( ( rng_status != SECSuccess ) ||
-       ( PORT_Memcmp( DSAX, rng_known_DSAX,
-                      (FIPS_DSA_SUBPRIME_LENGTH) ) != 0 ) )
-       return( CKR_DEVICE_ERROR );
-       
-   return( CKR_OK ); 
-}
-
-static CK_RV
-sftk_fipsSoftwareIntegrityTest(void)
-{
-    CK_RV crv = CKR_OK;
-
-    /* make sure that our check file signatures are OK */
-    if( !BLAPI_VerifySelf( NULL ) || 
-	!BLAPI_SHVerify( SOFTOKEN_LIB_NAME, (PRFuncPtr) sftk_fips_HMAC ) ) {
-	crv = CKR_DEVICE_ERROR; /* better error code? checksum error? */
-    }
-    return crv;
-}
-
+/*
+ * this is called from nsc_Common_Initizialize entry points that gates access 
+ * to * all other pkcs11 functions. This prevents softoken operation if our
+ * power on selftest failed.
+ */
 CK_RV
-sftk_fipsPowerUpSelfTest( void )
-{
-    CK_RV rv;
-
-    /* RC2 Power-Up SelfTest(s). */
-    rv = sftk_fips_RC2_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* RC4 Power-Up SelfTest(s). */
-    rv = sftk_fips_RC4_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* DES Power-Up SelfTest(s). */
-    rv = sftk_fips_DES_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* DES3 Power-Up SelfTest(s). */
-    rv = sftk_fips_DES3_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
- 
-    /* AES Power-Up SelfTest(s) for 128-bit key. */
-    rv = sftk_fips_AES_PowerUpSelfTest(FIPS_AES_128_KEY_SIZE);
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* AES Power-Up SelfTest(s) for 192-bit key. */
-    rv = sftk_fips_AES_PowerUpSelfTest(FIPS_AES_192_KEY_SIZE);
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* AES Power-Up SelfTest(s) for 256-bit key. */
-    rv = sftk_fips_AES_PowerUpSelfTest(FIPS_AES_256_KEY_SIZE);
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* MD2 Power-Up SelfTest(s). */
-    rv = sftk_fips_MD2_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* MD5 Power-Up SelfTest(s). */
-    rv = sftk_fips_MD5_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* SHA-X Power-Up SelfTest(s). */
-    rv = sftk_fips_SHA_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* HMAC SHA-X Power-Up SelfTest(s). */
-    rv = sftk_fips_HMAC_PowerUpSelfTest();
- 
-    if( rv != CKR_OK )
-        return rv;
-
-    /* RSA Power-Up SelfTest(s). */
-    rv = sftk_fips_RSA_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* DSA Power-Up SelfTest(s). */
-    rv = sftk_fips_DSA_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* RNG Power-Up SelfTest(s). */
-    rv = sftk_fips_RNG_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
-    
-#ifndef NSS_DISABLE_ECC
-    /* ECDSA Power-Up SelfTest(s). */
-    rv = sftk_fips_ECDSA_PowerUpSelfTest();
-
-    if( rv != CKR_OK )
-        return rv;
+sftk_FIPSEntryOK() {
+#ifdef NSS_NO_INIT_SUPPORT
+   /* this should only be set on platforms that can't handle one of the INIT
+    * schemes.  This code allows those platforms to continue to function, 
+    * though they don't meet the strict NIST requirements. If NSS_NO_INIT_SUPPORT
+    * is not set, and init support has not been properly enabled, softken
+    * will always fail because of the test below 
+    */
+    if (!sftk_self_tests_ran) {
+       sftk_startup_tests();
+    }
 #endif
-
-    /* Software/Firmware Integrity Test. */
-    rv = sftk_fipsSoftwareIntegrityTest();
-
-    if( rv != CKR_OK )
-        return rv;
-
-    /* Passed Power-Up SelfTest(s). */
-    return( CKR_OK );
-}
-
+    if (!sftk_self_tests_success) {
+       return CKR_DEVICE_ERROR;
+    }
+    return CKR_OK;
+ }
--- a/lib/softoken/fipstokn.c
+++ b/lib/softoken/fipstokn.c
@@ -87,16 +87,17 @@ libaudit_init(void)
 }
 #endif /* LINUX */
 
 
 /*
  * ******************** Password Utilities *******************************
  */
 static PRBool isLoggedIn = PR_FALSE;
+static PRBool isLevel2 = PR_TRUE;
 PRBool sftk_fatalError = PR_FALSE;
 
 /*
  * This function returns
  *   - CKR_PIN_INVALID if the password/PIN is not a legal UTF8 string
  *   - CKR_PIN_LEN_RANGE if the password/PIN is too short or does not
  *     consist of characters from three or more character classes.
  *   - CKR_OK otherwise
@@ -187,17 +188,17 @@ static CK_RV sftk_newPinCheck(CK_CHAR_PT
     return CKR_OK;
 }
 
 
 /* FIPS required checks before any useful cryptographic services */
 static CK_RV sftk_fipsCheck(void) {
     if (sftk_fatalError) 
 	return CKR_DEVICE_ERROR;
-    if (!isLoggedIn) 
+    if (isLevel2 && !isLoggedIn) 
 	return CKR_USER_NOT_LOGGED_IN;
     return CKR_OK;
 }
 
 
 #define SFTK_FIPSCHECK() \
     CK_RV rv; \
     if ((rv = sftk_fipsCheck()) != CKR_OK) return rv;
@@ -420,56 +421,65 @@ CK_RV FC_GetFunctionList(CK_FUNCTION_LIS
 
     *pFunctionList = &sftk_fipsTable;
     return CKR_OK;
 }
 
 /* sigh global so pkcs11 can read it */
 PRBool nsf_init = PR_FALSE;
 
+void fc_log_init_error(CK_RV crv) {
+    if (sftk_audit_enabled) {
+       char msg[128];
+       PR_snprintf(msg,sizeof msg,
+                       "C_Initialize()=0x%08lX "
+                       "power-up self-tests failed",
+                       (PRUint32)crv);
+       sftk_LogAuditMessage(NSS_AUDIT_ERROR, NSS_AUDIT_SELF_TEST, msg);
+    }
+}
+
+
 /* FC_Initialize initializes the PKCS #11 library. */
 CK_RV FC_Initialize(CK_VOID_PTR pReserved) {
     const char *envp;
     CK_RV crv;
 
+    if ((envp = PR_GetEnv("NSS_ENABLE_AUDIT")) != NULL) {
+	sftk_audit_enabled = (atoi(envp) == 1);
+    }
+
+    /* At this point we should have already done post and integrity checks.
+     * if we haven't, it probably means the FIPS product has not been installed
+     * or the tests failed. Don't let an application try to enter FIPS mode */
+    crv = sftk_FIPSEntryOK();
+    if (crv != CKR_OK) {
+       sftk_fatalError = PR_TRUE;
+       fc_log_init_error(crv);
+       return crv;
+    }
+
+
     sftk_ForkReset(pReserved, &crv);
 
     if (nsf_init) {
 	return CKR_CRYPTOKI_ALREADY_INITIALIZED;
     }
 
-    if ((envp = PR_GetEnvSecure("NSS_ENABLE_AUDIT")) != NULL) {
-	sftk_audit_enabled = (atoi(envp) == 1);
-    }
-
     crv = nsc_CommonInitialize(pReserved, PR_TRUE);
 
     /* not an 'else' rv can be set by either SFTK_LowInit or SFTK_SlotInit*/
     if (crv != CKR_OK) {
 	sftk_fatalError = PR_TRUE;
 	return crv;
     }
 
     sftk_fatalError = PR_FALSE; /* any error has been reset */
-
-    crv = sftk_fipsPowerUpSelfTest();
-    if (crv != CKR_OK) {
-        nsc_CommonFinalize(NULL, PR_TRUE);
-	sftk_fatalError = PR_TRUE;
-	if (sftk_audit_enabled) {
-	    char msg[128];
-	    PR_snprintf(msg,sizeof msg,
-			"C_Initialize()=0x%08lX "
-			"power-up self-tests failed",
-			(PRUint32)crv);
-	    sftk_LogAuditMessage(NSS_AUDIT_ERROR, NSS_AUDIT_SELF_TEST, msg);
-	}
-	return crv;
-    }
     nsf_init = PR_TRUE;
+    isLevel2 = PR_TRUE; /* assume level 2 unless we learn otherwise */
 
     return CKR_OK;
 }
 
 /*FC_Finalize indicates that an application is done with the PKCS #11 library.*/
 CK_RV FC_Finalize (CK_VOID_PTR pReserved) {
    CK_RV crv;
 
@@ -514,45 +524,52 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, 
 
 /*FC_GetTokenInfo obtains information about a particular token in the system.*/
  CK_RV FC_GetTokenInfo(CK_SLOT_ID slotID,CK_TOKEN_INFO_PTR pInfo) {
     CK_RV crv;
 
     CHECK_FORK();
 
     crv = NSC_GetTokenInfo(slotID,pInfo);
-    if (crv == CKR_OK) 
-       pInfo->flags |= CKF_LOGIN_REQUIRED;
+    if (crv == CKR_OK) {
+	if ((pInfo->flags & CKF_LOGIN_REQUIRED) == 0) {
+	    isLevel2 = PR_FALSE;
+ 	}
+    }
     return crv;
 
 }
 
 
 
 /*FC_GetMechanismList obtains a list of mechanism types supported by a token.*/
  CK_RV FC_GetMechanismList(CK_SLOT_ID slotID,
 	CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pusCount) {
      CHECK_FORK();
 
     SFTK_FIPSFATALCHECK();
-    if (slotID == FIPS_SLOT_ID) slotID = NETSCAPE_SLOT_ID;
-    /* FIPS Slot supports all functions */
+    if ((slotID == FIPS_SLOT_ID) || (slotID >=SFTK_MIN_FIPS_USER_SLOT_ID)) {
+	slotID = NETSCAPE_SLOT_ID;
+    }
+    /* FIPS Slots support all functions */
     return NSC_GetMechanismList(slotID,pMechanismList,pusCount);
 }
 
 
 /* FC_GetMechanismInfo obtains information about a particular mechanism 
  * possibly supported by a token. */
  CK_RV FC_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type,
     					CK_MECHANISM_INFO_PTR pInfo) {
     CHECK_FORK();
 
     SFTK_FIPSFATALCHECK();
-    if (slotID == FIPS_SLOT_ID) slotID = NETSCAPE_SLOT_ID;
-    /* FIPS Slot supports all functions */
+    if ((slotID == FIPS_SLOT_ID) || (slotID >=SFTK_MIN_FIPS_USER_SLOT_ID)) {
+	slotID = NETSCAPE_SLOT_ID;
+    }
+    /* FIPS Slots support all functions */
     return NSC_GetMechanismInfo(slotID,type,pInfo);
 }
 
 
 /* FC_InitToken initializes a token. */
  CK_RV FC_InitToken(CK_SLOT_ID slotID,CK_CHAR_PTR pPin,
  				CK_ULONG usPinLen,CK_CHAR_PTR pLabel) {
     CK_RV crv;
@@ -577,18 +594,24 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, 
 /* FC_InitPIN initializes the normal user's PIN. */
  CK_RV FC_InitPIN(CK_SESSION_HANDLE hSession,
     					CK_CHAR_PTR pPin, CK_ULONG ulPinLen) {
     CK_RV rv;
 
     CHECK_FORK();
 
     if (sftk_fatalError) return CKR_DEVICE_ERROR;
-    if ((rv = sftk_newPinCheck(pPin,ulPinLen)) == CKR_OK) {
+    /* NSC_InitPIN will only work once per database. We can either initialize
+     * it to level1 (pin len == 0) or level2. If we initialize to level 2, then
+     * we need to make sure the pin meets FIPS requirements */
+    if ((ulPinLen== 0) || ((rv = sftk_newPinCheck(pPin,ulPinLen)) == CKR_OK)) {
 	rv = NSC_InitPIN(hSession,pPin,ulPinLen);
+	if (rv == CKR_OK) {
+	    isLevel2 = (ulPinLen > 0) ? PR_TRUE : PR_FALSE;
+	}
     }
     if (sftk_audit_enabled) {
 	char msg[128];
 	NSSAuditSeverity severity = (rv == CKR_OK) ?
 		NSS_AUDIT_INFO : NSS_AUDIT_ERROR;
 	PR_snprintf(msg,sizeof msg,
 		"C_InitPIN(hSession=0x%08lX)=0x%08lX",
 		(PRUint32)hSession,(PRUint32)rv);
@@ -604,16 +627,22 @@ CK_RV FC_GetSlotInfo(CK_SLOT_ID slotID, 
     CK_ULONG usOldLen, CK_CHAR_PTR pNewPin, CK_ULONG usNewLen) {
     CK_RV rv;
 
     CHECK_FORK();
 
     if ((rv = sftk_fipsCheck()) == CKR_OK &&
 	(rv = sftk_newPinCheck(pNewPin,usNewLen)) == CKR_OK) {
 	rv = NSC_SetPIN(hSession,pOldPin,usOldLen,pNewPin,usNewLen);
+	if (rv == CKR_OK) {
+	    /* if we set the password in level1 we now go
+	     * to level2. NOTE: we don't allow the user to
+	     * go from level2 to level1 */
+	    isLevel2 = PR_TRUE; 
+	}
     }
     if (sftk_audit_enabled) {
 	char msg[128];
 	NSSAuditSeverity severity = (rv == CKR_OK) ?
 		NSS_AUDIT_INFO : NSS_AUDIT_ERROR;
 	PR_snprintf(msg,sizeof msg,
 		"C_SetPIN(hSession=0x%08lX)=0x%08lX",
 		(PRUint32)hSession,(PRUint32)rv);
--- a/lib/softoken/legacydb/lgdb.h
+++ b/lib/softoken/legacydb/lgdb.h
@@ -62,16 +62,19 @@ extern CK_RV lg_ClearTokenKeyHashTable(S
 
 extern void lg_FreeSearch(SDBFind *search);
 
 NSSLOWCERTCertDBHandle *lg_getCertDB(SDB *sdb);
 NSSLOWKEYDBHandle *lg_getKeyDB(SDB *sdb);
 
 const char *lg_EvaluateConfigDir(const char *configdir, char **domain);
 
+/* verify the FIPS selftests ran and were successful */
+PRBool lg_FIPSEntryOK(void);
+
 
 /*
  * object handle modifiers
  */
 #define LG_TOKEN_MASK		0xc0000000L
 #define LG_TOKEN_TYPE_MASK	0x38000000L
 #define LG_TOKEN_TYPE_SHIFT	27
 /* keydb (high bit == 0) */
new file mode 100644
--- /dev/null
+++ b/lib/softoken/legacydb/lgfips.c
@@ -0,0 +1,116 @@
+/*
+ * PKCS #11 FIPS Power-Up Self Test.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+/* $Id: fipstest.c,v 1.31 2012/06/28 17:55:06 rrelyea%redhat.com Exp $ */
+
+#include "seccomon.h"
+#include "lgdb.h"
+#include "blapi.h"
+
+/*
+ * different platforms have different ways of calling and initial entry point
+ * when the dll/.so is loaded. Most platforms support either a posix pragma
+ * or the GCC attribute. Some platforms suppor a pre-defined name, and some
+ * platforms have a link line way of invoking this function.
+ */
+
+/* The pragma */
+#if defined(USE_INIT_PRAGMA)
+#pragma init(lg_startup_tests)
+#endif
+
+
+/* GCC Attribute */
+#ifdef __GNUC__
+#define INIT_FUNCTION __attribute__((constructor))
+#else
+#define INIT_FUNCTION
+#endif
+
+static void INIT_FUNCTION lg_startup_tests(void);
+
+/* Windows pre-defined entry */
+#ifdef XP_WIN
+#include <windows.h>
+
+BOOL WINAPI DllMain(
+    HINSTANCE hinstDLL,  // handle to DLL module
+    DWORD fdwReason,     // reason for calling function
+    LPVOID lpReserved )  // reserved
+{
+    // Perform actions based on the reason for calling.
+    switch( fdwReason ) 
+    { 
+        case DLL_PROCESS_ATTACH:
+         // Initialize once for each new process.
+         // Return FALSE to fail DLL load.
+	lg_startup_tests();
+            break;
+
+        case DLL_THREAD_ATTACH:
+         // Do thread-specific initialization.
+            break;
+
+        case DLL_THREAD_DETACH:
+         // Do thread-specific cleanup.
+            break;
+
+        case DLL_PROCESS_DETACH:
+         // Perform any necessary cleanup.
+            break;
+    }
+    return TRUE;  // Successful DLL_PROCESS_ATTACH.
+}
+#endif
+
+static PRBool lg_self_tests_ran = PR_FALSE;
+static PRBool lg_self_tests_success = PR_FALSE;
+
+static void
+lg_local_function(void) {}
+
+/*
+ * This function is called at dll load time, the code tha makes this 
+ * happen is platform specific on defined above.
+ */ 
+static void
+lg_startup_tests(void)
+{
+    const char *libraryName = LG_LIB_NAME;
+
+    PORT_Assert(!lg_self_tests_ran);
+    PORT_Assert(!lg_self_tests_success);
+    lg_self_tests_ran = PR_TRUE;
+    lg_self_tests_success = PR_FALSE; /* just in case */
+
+    /* no self tests required for the legacy db, only the integrity check */
+    /* check the integrity of our shared library */
+    if (!BLAPI_SHVerify(libraryName, (PRFuncPtr) &lg_local_function)) {
+	/* something is wrong with the library, fail without enabling
+	 * the fips token */
+	return;
+    }
+    /* FIPS product has been installed and is functioning, allow 
+     * the module to operate in fips mode */
+    lg_self_tests_success = PR_TRUE;
+}
+
+PRBool
+lg_FIPSEntryOK() {
+#ifdef NO_INIT_SUPPORT
+   /* this should only be set on platforms that can't handle one of the INIT
+    * schemes.  This code allows those platforms to continue to function, 
+    * though they don't meet the strict NIST requirements. If NO_INIT_SUPPORT
+    * is not set, and init support has not been properly enabled, softken
+    * will always fail because of the test below */
+    */
+    if (!lg_self_tests_ran) {
+	lg_startup_tests();
+    }
+#endif
+    return lg_self_tests_success;
+}
+
--- a/lib/softoken/legacydb/lginit.c
+++ b/lib/softoken/legacydb/lginit.c
@@ -486,16 +486,17 @@ lg_HashNumber(const void *key)
 CK_RV 
 lg_init(SDB **pSdb, int flags, NSSLOWCERTCertDBHandle *certdbPtr,
 	 NSSLOWKEYDBHandle *keydbPtr)
 {
     SDB *sdb = NULL;
     LGPrivate *lgdb_p = NULL;
     CK_RV error = CKR_HOST_MEMORY;
 
+
     *pSdb = NULL;
     sdb = (SDB *) PORT_Alloc(sizeof(SDB));
     if (sdb == NULL) {
 	goto loser;
     }
     lgdb_p = (LGPrivate *) PORT_Alloc(sizeof(LGPrivate));
     if (lgdb_p == NULL) {
 	goto loser;
@@ -510,17 +511,16 @@ lg_init(SDB **pSdb, int flags, NSSLOWCER
     lgdb_p->hashTable = PL_NewHashTable(64, lg_HashNumber, PL_CompareValues,
 			SECITEM_HashCompare, NULL, 0);
     if (lgdb_p->hashTable == NULL) {
 	goto loser;
     }
 
     sdb->private = lgdb_p;
     sdb->version = 0;
-    /*sdb->sdb_type = SDB_LEGACY; */
     sdb->sdb_flags = flags;
     sdb->app_private = NULL;
     sdb->sdb_FindObjectsInit = lg_FindObjectsInit;
     sdb->sdb_FindObjects = lg_FindObjects;
     sdb->sdb_FindObjectsFinal = lg_FindObjectsFinal;
     sdb->sdb_GetAttributeValue = lg_GetAttributeValue;
     sdb->sdb_SetAttributeValue = lg_SetAttributeValue;
     sdb->sdb_CreateObject = lg_CreateObject;
@@ -573,21 +573,27 @@ loser:
  */
 CK_RV
 legacy_Open(const char *configdir, const char *certPrefix, 
 	    const char *keyPrefix, int certVersion, int keyVersion,
 	    int flags, SDB **certDB, SDB **keyDB)
 {
     CK_RV crv = CKR_OK;
     SECStatus rv;
-    PRBool readOnly = (flags == SDB_RDONLY)? PR_TRUE: PR_FALSE;
+    PRBool readOnly = ((flags & 0x7) == SDB_RDONLY)? PR_TRUE: PR_FALSE;
 
 #define NSS_VERSION_VARIABLE __nss_dbm_version
 #include "verref.h"
 
+    if (flags & SDB_FIPS) {
+	if (!lg_FIPSEntryOK()) {
+	    return CKR_DEVICE_ERROR;
+	}
+    }
+
     rv = SECOID_Init();
     if (SECSuccess != rv) {
         return CKR_DEVICE_ERROR;
     }
     nsslowcert_InitLocks();
 
     if (keyDB) *keyDB = NULL;
     if (certDB) *certDB = NULL;
--- a/lib/softoken/legacydb/manifest.mn
+++ b/lib/softoken/legacydb/manifest.mn
@@ -7,25 +7,26 @@ CORE_DEPTH = ../../..
 MODULE = nss
 
 REQUIRES = dbm 
 
 LIBRARY_NAME = nssdbm
 LIBRARY_VERSION = 3
 MAPFILE = $(OBJDIR)/nssdbm.def
 
-DEFINES += -DSHLIB_SUFFIX=\"$(DLL_SUFFIX)\" -DSHLIB_PREFIX=\"$(DLL_PREFIX)\"
+DEFINES += -DSHLIB_SUFFIX=\"$(DLL_SUFFIX)\" -DSHLIB_PREFIX=\"$(DLL_PREFIX)\" -DLG_LIB_NAME=\"$(notdir $(SHARED_LIBRARY))\"
 
 CSRCS = \
 	dbmshim.c \
 	keydb.c \
 	lgattr.c \
 	lgcreate.c \
 	lgdestroy.c \
 	lgfind.c \
+	lgfips.c \
 	lginit.c \
 	lgutil.c \
 	lowcert.c \
 	lowkey.c \
 	pcertdb.c \
 	pk11db.c \
 	$(NULL)
 
--- a/lib/softoken/lgglue.c
+++ b/lib/softoken/lgglue.c
@@ -241,39 +241,24 @@ sftkdb_decrypt_stub(SDB *sdb, SECItem *c
 }
 
 static const char *LEGACY_LIB_NAME = 
 	SHLIB_PREFIX"nssdbm"SHLIB_VERSION"."SHLIB_SUFFIX;
 /*
  * 2 bools to tell us if we've check the legacy library successfully or
  * not. Initialize on startup to false by the C BSS segment;
  */
-static PRBool legacy_glue_libCheckFailed;    /* set if we failed the check */
-static PRBool legacy_glue_libCheckSucceeded; /* set if we passed the check */
 static PRLibrary *legacy_glue_lib = NULL;
 static SECStatus 
-sftkdbLoad_Legacy(PRBool isFIPS)
+sftkdbLoad_Legacy()
 {
     PRLibrary *lib = NULL;
     LGSetCryptFunc setCryptFunction = NULL;
 
     if (legacy_glue_lib) {
-	/* this check is necessary because it's possible we loaded the
-	 * legacydb to read secmod.db, which told us whether we were in
-	 * FIPS mode or not. */
-	if (isFIPS && !legacy_glue_libCheckSucceeded) {
-	    if (legacy_glue_libCheckFailed || 
-		!BLAPI_SHVerify(LEGACY_LIB_NAME,(PRFuncPtr)legacy_glue_open)) {
-    	    	legacy_glue_libCheckFailed = PR_TRUE;
-		/* don't clobber legacy glue to avoid race. just let it
-		 * get cleared in shutdown */
-		return SECFailure;
-	    }
-    	    legacy_glue_libCheckSucceeded = PR_TRUE;
-	} 
 	return SECSuccess;
     }
 
     lib = sftkdb_LoadLibrary(LEGACY_LIB_NAME);
     if (lib == NULL) {
 	return SECFailure;
     }
     
@@ -293,38 +278,29 @@ sftkdbLoad_Legacy(PRBool isFIPS)
 
     if (!legacy_glue_open || !legacy_glue_readSecmod || 
 	    !legacy_glue_releaseSecmod || !legacy_glue_deleteSecmod || 
 	    !legacy_glue_addSecmod || !setCryptFunction) {
 	PR_UnloadLibrary(lib);
 	return SECFailure;
     }
 
-    /* verify the loaded library if we are in FIPS mode */
-    if (isFIPS) {
-	if (!BLAPI_SHVerify(LEGACY_LIB_NAME,(PRFuncPtr)legacy_glue_open)) {
-	    PR_UnloadLibrary(lib);
-	    return SECFailure;
-	}
-    	legacy_glue_libCheckSucceeded = PR_TRUE;
-    } 
-
     setCryptFunction(sftkdb_encrypt_stub,sftkdb_decrypt_stub);
     legacy_glue_lib = lib;
     return SECSuccess;
 }
 
 CK_RV
 sftkdbCall_open(const char *dir, const char *certPrefix, const char *keyPrefix, 
-		int certVersion, int keyVersion, int flags, PRBool isFIPS,
+		int certVersion, int keyVersion, int flags,
 		SDB **certDB, SDB **keyDB)
 {
     SECStatus rv;
 
-    rv = sftkdbLoad_Legacy(isFIPS);
+    rv = sftkdbLoad_Legacy();
     if (rv != SECSuccess) {
 	return CKR_GENERAL_ERROR;
     }
     if (!legacy_glue_open) {
 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
 	return SECFailure;
     }
     return (*legacy_glue_open)(dir, certPrefix, keyPrefix, 
@@ -333,17 +309,17 @@ sftkdbCall_open(const char *dir, const c
 }
 
 char **
 sftkdbCall_ReadSecmodDB(const char *appName, const char *filename, 
 			const char *dbname, char *params, PRBool rw)
 {
     SECStatus rv;
 
-    rv = sftkdbLoad_Legacy(PR_FALSE);
+    rv = sftkdbLoad_Legacy();
     if (rv != SECSuccess) {
 	return NULL;
     }
     if (!legacy_glue_readSecmod) {
 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
 	return NULL;
     }
     return (*legacy_glue_readSecmod)(appName, filename, dbname, params, rw);
@@ -351,17 +327,17 @@ sftkdbCall_ReadSecmodDB(const char *appN
 
 SECStatus
 sftkdbCall_ReleaseSecmodDBData(const char *appName, 
 			const char *filename, const char *dbname, 
 			char **moduleSpecList, PRBool rw)
 {
     SECStatus rv;
 
-    rv = sftkdbLoad_Legacy(PR_FALSE);
+    rv = sftkdbLoad_Legacy();
     if (rv != SECSuccess) {
 	return rv;
     }
     if (!legacy_glue_releaseSecmod) {
 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
 	return SECFailure;
     }
     return (*legacy_glue_releaseSecmod)(appName, filename, dbname, 
@@ -370,17 +346,17 @@ sftkdbCall_ReleaseSecmodDBData(const cha
 
 SECStatus
 sftkdbCall_DeleteSecmodDB(const char *appName, 
 		      const char *filename, const char *dbname, 
 		      char *args, PRBool rw)
 {
     SECStatus rv;
 
-    rv = sftkdbLoad_Legacy(PR_FALSE);
+    rv = sftkdbLoad_Legacy();
     if (rv != SECSuccess) {
 	return rv;
     }
     if (!legacy_glue_deleteSecmod) {
 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
 	return SECFailure;
     }
     return (*legacy_glue_deleteSecmod)(appName, filename, dbname, args, rw);
@@ -388,17 +364,17 @@ sftkdbCall_DeleteSecmodDB(const char *ap
 
 SECStatus
 sftkdbCall_AddSecmodDB(const char *appName, 
 		   const char *filename, const char *dbname, 
 		   char *module, PRBool rw)
 {
     SECStatus rv;
 
-    rv = sftkdbLoad_Legacy(PR_FALSE);
+    rv = sftkdbLoad_Legacy();
     if (rv != SECSuccess) {
 	return rv;
     }
     if (!legacy_glue_addSecmod) {
 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
 	return SECFailure;
     }
     return (*legacy_glue_addSecmod)(appName, filename, dbname, module, rw);
@@ -423,14 +399,12 @@ sftkdbCall_Shutdown(void)
         PR_UnloadLibrary(legacy_glue_lib);
     }
     legacy_glue_lib = NULL;
     legacy_glue_open = NULL;
     legacy_glue_readSecmod = NULL;
     legacy_glue_releaseSecmod = NULL;
     legacy_glue_deleteSecmod = NULL;
     legacy_glue_addSecmod = NULL;
-    legacy_glue_libCheckFailed    = PR_FALSE;
-    legacy_glue_libCheckSucceeded = PR_FALSE;
     return crv;
 }
     
 
--- a/lib/softoken/lgglue.h
+++ b/lib/softoken/lgglue.h
@@ -38,17 +38,17 @@ typedef SECStatus (*LGShutdownFunc)(PRBo
 typedef void (*LGSetForkStateFunc)(PRBool);
 typedef void (*LGSetCryptFunc)(LGEncryptFunc, LGDecryptFunc);
 
 /*
  * Softoken Glue Functions
  */
 CK_RV sftkdbCall_open(const char *dir, const char *certPrefix, 
 		const char *keyPrefix, 
-		int certVersion, int keyVersion, int flags, PRBool isFIPS,
+		int certVersion, int keyVersion, int flags,
 		SDB **certDB, SDB **keyDB);
 char ** sftkdbCall_ReadSecmodDB(const char *appName, const char *filename, 
 			const char *dbname, char *params, PRBool rw);
 SECStatus sftkdbCall_ReleaseSecmodDBData(const char *appName, 
 			const char *filename, const char *dbname, 
 			char **moduleSpecList, PRBool rw);
 SECStatus sftkdbCall_DeleteSecmodDB(const char *appName, 
 		      const char *filename, const char *dbname, 
--- a/lib/softoken/pkcs11.c
+++ b/lib/softoken/pkcs11.c
@@ -2452,17 +2452,22 @@ SFTK_SlotReInit(SFTKSlot *slot, char *co
 	slot->needLogin = 
 		(PRBool)!sftk_hasNullPassword(slot, slot->keyDB);
 	if ((params->minPW >= 0) && (params->minPW <= SFTK_MAX_PIN)) {
 	    slot->minimumPinLen = params->minPW;
 	}
 	if ((slot->minimumPinLen == 0) && (params->pwRequired)) {
 	    slot->minimumPinLen = 1;
 	}
-	if ((moduleIndex == NSC_FIPS_MODULE) &&
+	/* Make sure the pin len is set to the Minimum allowed value for fips
+  	 * when in FIPS mode. NOTE: we don't set it if the database has not
+  	 * been initialized yet so that we can init into level1 mode if needed
+  	 */
+	if ((sftkdb_HasPasswordSet(slot->keyDB) == SECSuccess) && 
+		(moduleIndex == NSC_FIPS_MODULE) &&
 		(slot->minimumPinLen < FIPS_MIN_PIN)) {
 	    slot->minimumPinLen = FIPS_MIN_PIN;
 	}
     }
 
     slot->present = PR_TRUE;
     return CKR_OK;
 
@@ -3585,16 +3590,24 @@ CK_RV NSC_InitPIN(CK_SESSION_HANDLE hSes
 	sftk_CloseAllSessions(slot, PR_FALSE);
     }
     sftk_freeDB(handle);
     handle = NULL;
 
     /* Now update our local copy of the pin */
     if (rv == SECSuccess) {
 	if (ulPinLen == 0) slot->needLogin = PR_FALSE;
+	/* database has been initialized, now force min password in FIPS
+  	 * mode. NOTE: if we are in level1, we may not have a password, but
+  	 * forcing it now will prevent an insufficient password from being set.
+  	 */
+	if ((sftk_GetModuleIndex(slot->slotID) == NSC_FIPS_MODULE) &&
+		(slot->minimumPinLen < FIPS_MIN_PIN)) {
+	    slot->minimumPinLen = FIPS_MIN_PIN;
+	}
 	return CKR_OK;
     }
     crv = CKR_PIN_INCORRECT;
 
 loser:
     if (sp) {
 	sftk_FreeSession(sp);
     }
--- a/lib/softoken/pkcs11c.c
+++ b/lib/softoken/pkcs11c.c
@@ -1171,20 +1171,20 @@ finish_des:
 	    crv = sftk_MapCryptError(PORT_GetError());
 	    break;
 	}
 	context->update = (SFTKCipher) (isEncrypt ? sftk_ChaCha20Poly1305_Encrypt :
 					sftk_ChaCha20Poly1305_Decrypt);
 	context->destroy = (SFTKDestroy) sftk_ChaCha20Poly1305_DestroyContext;
 	break;
 
-    case CKM_NETSCAPE_AES_KEY_WRAP_PAD:
+    case CKM_NSS_AES_KEY_WRAP_PAD:
     	context->doPad = PR_TRUE;
 	/* fall thru */
-    case CKM_NETSCAPE_AES_KEY_WRAP:
+    case CKM_NSS_AES_KEY_WRAP:
 	context->multi = PR_FALSE;
 	context->blockSize = 8;
 	if (key_type != CKK_AES) {
 	    crv = CKR_KEY_TYPE_INCONSISTENT;
 	    break;
 	}
 	att = sftk_FindAttribute(key,CKA_VALUE);
 	if (att == NULL) {
@@ -3634,42 +3634,101 @@ nsc_parameter_gen(CK_KEY_TYPE key_type, 
     unsigned int j = 8; /* default to 1024 bits */
     CK_RV crv = CKR_OK;
     PQGParams *params = NULL;
     PQGVerify *vfy = NULL;
     SECStatus rv;
 
     attribute = sftk_FindAttribute(key, CKA_PRIME_BITS);
     if (attribute == NULL) {
-	return CKR_TEMPLATE_INCOMPLETE;
-    }
-    primeBits = (unsigned int) *(CK_ULONG *)attribute->attrib.pValue;
-    sftk_FreeAttribute(attribute);
+	attribute =sftk_FindAttribute(key, CKA_PRIME);
+	if (attribute == NULL) {
+	    return CKR_TEMPLATE_INCOMPLETE;
+	} else {
+	    primeBits = attribute->attrib.ulValueLen;
+	    sftk_FreeAttribute(attribute);
+	}
+    } else {
+	primeBits = (unsigned int) *(CK_ULONG *)attribute->attrib.pValue;
+	sftk_FreeAttribute(attribute);
+    }
     if (primeBits < 1024) {
 	j = PQG_PBITS_TO_INDEX(primeBits);
 	if (j == (unsigned int)-1) {
 	    return CKR_ATTRIBUTE_VALUE_INVALID;
 	}
     }
 
-    attribute = sftk_FindAttribute(key, CKA_NETSCAPE_PQG_SEED_BITS);
+    attribute = sftk_FindAttribute(key, CKA_NSS_PQG_SEED_BITS);
     if (attribute != NULL) {
 	seedBits = (unsigned int) *(CK_ULONG *)attribute->attrib.pValue;
 	sftk_FreeAttribute(attribute);
     }
 
     attribute = sftk_FindAttribute(key, CKA_SUBPRIME_BITS);
     if (attribute != NULL) {
 	subprimeBits = (unsigned int) *(CK_ULONG *)attribute->attrib.pValue;
 	sftk_FreeAttribute(attribute);
     }
 
+    /* if P and Q are supplied, we want to generate a new G */
+    attribute = sftk_FindAttribute(key, CKA_PRIME);
+    if (attribute != NULL) {
+	PLArenaPool *arena;
+
+	sftk_FreeAttribute(attribute);
+	arena = PORT_NewArena(1024);
+	if (arena == NULL) {
+	    crv = CKR_HOST_MEMORY;
+	    goto loser;
+	}
+	params = PORT_ArenaAlloc(arena, sizeof(*params));
+	if (params == NULL) {
+	    crv = CKR_HOST_MEMORY;
+	    goto loser;
+	}
+	params->arena = arena;
+	crv = sftk_Attribute2SSecItem(arena, &params->prime, key, CKA_PRIME);
+	if (crv != CKR_OK) {
+	    goto loser;
+	}
+	crv = sftk_Attribute2SSecItem(arena, &params->subPrime, 
+							key, CKA_SUBPRIME);
+	if (crv != CKR_OK) {
+	    goto loser;
+	}
+
+	arena = PORT_NewArena(1024);
+	if (arena == NULL) {
+	    crv = CKR_HOST_MEMORY;
+	    goto loser;
+	}
+	vfy = PORT_ArenaAlloc(arena, sizeof(*vfy));
+	if (vfy == NULL) {
+	    crv = CKR_HOST_MEMORY;
+	    goto loser;
+	}
+	vfy->arena = arena;
+	crv = sftk_Attribute2SSecItem(arena, &vfy->seed, key, CKA_NSS_PQG_SEED);
+	if (crv != CKR_OK) {
+	    goto loser;
+	}
+	crv = sftk_Attribute2SSecItem(arena, &vfy->h, key, CKA_NSS_PQG_H);
+	if (crv != CKR_OK) {
+	    goto loser;
+	}
+    	sftk_DeleteAttributeType(key,CKA_PRIME);
+    	sftk_DeleteAttributeType(key,CKA_SUBPRIME);
+    	sftk_DeleteAttributeType(key,CKA_NSS_PQG_SEED);
+    	sftk_DeleteAttributeType(key,CKA_NSS_PQG_H);
+    }
+
     sftk_DeleteAttributeType(key,CKA_PRIME_BITS);
     sftk_DeleteAttributeType(key,CKA_SUBPRIME_BITS);
-    sftk_DeleteAttributeType(key,CKA_NETSCAPE_PQG_SEED_BITS);
+    sftk_DeleteAttributeType(key,CKA_NSS_PQG_SEED_BITS);
 
     /* use the old PQG interface if we have old input data */
     if ((primeBits < 1024) || ((primeBits == 1024) && (subprimeBits == 0))) {
 	if (seedBits == 0) {
 	    rv = PQG_ParamGen(j, &params, &vfy);
 	} else {
 	    rv = PQG_ParamGenSeedLen(j,seedBits/8, &params, &vfy);
 	}
@@ -3696,27 +3755,29 @@ nsc_parameter_gen(CK_KEY_TYPE key_type, 
     if (crv != CKR_OK) goto loser;
     crv = sftk_AddAttributeType(key,CKA_SUBPRIME,
 				 params->subPrime.data, params->subPrime.len);
     if (crv != CKR_OK) goto loser;
     crv = sftk_AddAttributeType(key,CKA_BASE,
 				 params->base.data, params->base.len);
     if (crv != CKR_OK) goto loser;
     counter = vfy->counter;
-    crv = sftk_AddAttributeType(key,CKA_NETSCAPE_PQG_COUNTER,
+    crv = sftk_AddAttributeType(key,CKA_NSS_PQG_COUNTER,
 				 &counter, sizeof(counter));
-    crv = sftk_AddAttributeType(key,CKA_NETSCAPE_PQG_SEED,
+    crv = sftk_AddAttributeType(key,CKA_NSS_PQG_SEED,
 				 vfy->seed.data, vfy->seed.len);
     if (crv != CKR_OK) goto loser;
-    crv = sftk_AddAttributeType(key,CKA_NETSCAPE_PQG_H,
+    crv = sftk_AddAttributeType(key,CKA_NSS_PQG_H,
 				 vfy->h.data, vfy->h.len);
     if (crv != CKR_OK) goto loser;
 
 loser:
-    PQG_DestroyParams(params);
+    if (params) {
+         PQG_DestroyParams(params);
+    }
 
     if (vfy) {
 	PQG_DestroyVerify(vfy);
     }
     return crv;
 }
 
 
--- a/lib/softoken/sdb.c
+++ b/lib/softoken/sdb.c
@@ -1689,32 +1689,33 @@ void sdb_SetForkState(PRBool forked)
 /*
  * initialize a single database
  */
 static const char INIT_CMD[] =
  "CREATE TABLE %s (id PRIMARY KEY UNIQUE ON CONFLICT ABORT%s)";
 
 CK_RV 
 sdb_init(char *dbname, char *table, sdbDataType type, int *inUpdate,
-	 int *newInit, int flags, PRUint32 accessOps, SDB **pSdb)
+	 int *newInit, int inFlags, PRUint32 accessOps, SDB **pSdb)
 {
     int i;
     char *initStr = NULL;
     char *newStr;
     int inTransaction = 0;
     SDB *sdb = NULL;
     SDBPrivate *sdb_p = NULL;
     sqlite3 *sqlDB = NULL;
     int sqlerr = SQLITE_OK;
     CK_RV error = CKR_OK;
     char *cacheTable = NULL;
     PRIntervalTime now = 0;
     char *env;
     PRBool enableCache = PR_FALSE;
     PRBool create;
+    int flags = inFlags & 0x7;
 
     *pSdb = NULL;
     *inUpdate = 0;
 
     /* sqlite3 doesn't have a flag to specify that we want to 
      * open the database read only. If the db doesn't exist,
      * sqlite3 will always create it.
      */
@@ -1920,17 +1921,17 @@ sdb_init(char *dbname, char *table, sdbD
      * decide the existing cache is stale. Currently set to 10 sec */
     sdb_p->updateInterval = PR_SecondsToInterval(10); 
     sdb_p->dbMon = PR_NewMonitor();
     /* these fields are protected by the lock */
     sdb_p->sqlXactDB = NULL;
     sdb_p->sqlXactThread = NULL;
     sdb->private = sdb_p;
     sdb->version = 0;
-    sdb->sdb_flags = flags | SDB_HAS_META;
+    sdb->sdb_flags = inFlags | SDB_HAS_META;
     sdb->app_private = NULL;
     sdb->sdb_FindObjectsInit = sdb_FindObjectsInit;
     sdb->sdb_FindObjects = sdb_FindObjects;
     sdb->sdb_FindObjectsFinal = sdb_FindObjectsFinal;
     sdb->sdb_GetAttributeValue = sdb_GetAttributeValue;
     sdb->sdb_SetAttributeValue = sdb_SetAttributeValue;
     sdb->sdb_CreateObject = sdb_CreateObject;
     sdb->sdb_DestroyObject = sdb_DestroyObject;
--- a/lib/softoken/sdb.h
+++ b/lib/softoken/sdb.h
@@ -69,10 +69,11 @@ CK_RV s_open(const char *directory, cons
 	     int flags, SDB **certdb, SDB **keydb, int *newInit);
 CK_RV s_shutdown();
 
 /* flags */
 #define SDB_RDONLY      1
 #define SDB_RDWR        2
 #define SDB_CREATE      4
 #define SDB_HAS_META    8
+#define SDB_FIPS        0x10
 
 #endif
--- a/lib/softoken/sftkdb.c
+++ b/lib/softoken/sftkdb.c
@@ -2576,53 +2576,56 @@ sftk_DBInit(const char *configdir, const
     CK_RV crv = CKR_OK;
     int flags = SDB_RDONLY;
     PRBool newInit = PR_FALSE;
     PRBool needUpdate = PR_FALSE;
 
     if (!readOnly) {
 	flags = SDB_CREATE;
     }
+    if (isFIPS) {
+	flags |= SDB_FIPS;
+    }
 
     *certDB = NULL;
     *keyDB = NULL;
 
     if (noKeyDB && noCertDB) {
 	return CKR_OK;
     }
     confdir = _NSSUTIL_EvaluateConfigDir(configdir, &dbType, &appName);
 
     /*
      * now initialize the appropriate database
      */
     switch (dbType) {
     case NSS_DB_TYPE_LEGACY:
 	crv = sftkdbCall_open(confdir, certPrefix, keyPrefix, 8, 3, flags,
-		 isFIPS, noCertDB? NULL : &certSDB, noKeyDB ? NULL: &keySDB);
+		 noCertDB? NULL : &certSDB, noKeyDB ? NULL: &keySDB);
 	break;
     case NSS_DB_TYPE_MULTIACCESS:
 	crv = sftkdbCall_open(configdir, certPrefix, keyPrefix, 8, 3, flags,
-		isFIPS, noCertDB? NULL : &certSDB, noKeyDB ? NULL: &keySDB);
+		noCertDB? NULL : &certSDB, noKeyDB ? NULL: &keySDB);
 	break;
     case NSS_DB_TYPE_SQL:
     case NSS_DB_TYPE_EXTERN: /* SHOULD open a loadable db */
 	crv = s_open(confdir, certPrefix, keyPrefix, 9, 4, flags, 
 		noCertDB? NULL : &certSDB, noKeyDB ? NULL : &keySDB, &newInit);
 
         /*
 	 * if we failed to open the DB's read only, use the old ones if
 	 * the exists.
 	 */
 	if (crv != CKR_OK) {
-	    if ((flags == SDB_RDONLY)  &&
+	    if (((flags & SDB_RDONLY) == SDB_RDONLY)  &&
 	         sftk_hasLegacyDB(confdir, certPrefix, keyPrefix, 8, 3)) {
 	    /* we have legacy databases, if we failed to open the new format 
 	     * DB's read only, just use the legacy ones */
 		crv = sftkdbCall_open(confdir, certPrefix, 
-			keyPrefix, 8, 3, flags, isFIPS, 
+			keyPrefix, 8, 3, flags, 
 			noCertDB? NULL : &certSDB, noKeyDB ? NULL : &keySDB);
 	    }
 	/* Handle the database merge case.
          *
          * For the merge case, we need help from the application. Only
          * the application knows where the old database is, and what unique
          * identifier it has associated with it.
          *
@@ -2683,17 +2686,17 @@ sftk_DBInit(const char *configdir, const
      * mark the handle as needing update.
      */
     if (needUpdate) {
 	SDB *updateCert = NULL;
 	SDB *updateKey = NULL;
 	CK_RV crv2;
 
 	crv2 = sftkdbCall_open(confdir, certPrefix, keyPrefix, 8, 3, flags,
-		isFIPS, noCertDB ? NULL : &updateCert, 
+		noCertDB ? NULL : &updateCert, 
 		noKeyDB ? NULL : &updateKey);
 	if (crv2 == CKR_OK) {
 	    if (*certDB) {
 		(*certDB)->update = updateCert;
 		(*certDB)->updateID = updateID && *updateID 
 				? PORT_Strdup(updateID) : NULL;
 		updateCert->app_private = (*certDB);
 	    }
--- a/lib/softoken/softoken.h
+++ b/lib/softoken/softoken.h
@@ -50,20 +50,20 @@ RSA_HashCheckSign(SECOidTag hashOid, NSS
 */
 extern unsigned char * CBC_PadBuffer(PLArenaPool *arena, unsigned char *inbuf,
                                      unsigned int inlen, unsigned int *outlen,
 				     int blockSize);
 
 
 /****************************************/
 /*
-** Power-Up selftests required for FIPS and invoked only
-** under PKCS #11 FIPS mode.
+** Power-Up selftests are required for FIPS.
 */
-extern CK_RV sftk_fipsPowerUpSelfTest( void ); 
+/* make sure Power-up selftests have been run. */
+extern CK_RV sftk_FIPSEntryOK( void ); 
 
 /*
 ** make known fixed PKCS #11 key types to their sizes in bytes
 */	
 unsigned long sftk_MapKeySize(CK_KEY_TYPE keyType);
 
 /*
 ** FIPS 140-2 auditing
--- a/lib/util/pkcs11t.h
+++ b/lib/util/pkcs11t.h
@@ -824,16 +824,17 @@ typedef CK_ULONG          CK_MECHANISM_T
 #define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE  0x000003D4
 #define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE  0x000003D5
 
 /* TLS 1.2 mechanisms are new for v2.40 */
 #define CKM_TLS12_MASTER_KEY_DERIVE         0x000003E0
 #define CKM_TLS12_KEY_AND_MAC_DERIVE        0x000003E1
 #define CKM_TLS12_MASTER_KEY_DERIVE_DH      0x000003E2
 #define CKM_TLS12_KEY_SAFE_DERIVE           0x000003E3
+#define CKM_TLS12_MAC                       0x000003E4
 #define CKM_TLS_MAC                         0x000003E4
 #define CKM_TLS_KDF                         0x000003E5
 
 #define CKM_KEY_WRAP_LYNKS             0x00000400
 #define CKM_KEY_WRAP_SET_OAEP          0x00000401
 
 /* CKM_CMS_SIG is new for v2.20 */
 #define CKM_CMS_SIG                    0x00000500
--- a/tests/common/Makefile
+++ b/tests/common/Makefile
@@ -14,8 +14,11 @@ objdir_name:
 os_arch:
 	@echo $(OS_ARCH)
 
 dll_prefix:
 	@echo $(DLL_PREFIX)
 
 dll_suffix:
 	@echo $(DLL_SUFFIX)
+
+freebl_lowhash:
+	@echo $(FREEBL_LOWHASH)