Bug 1211568 - Upgrade Firefox 44 to NSS 3.21, landing NSS_3_21_Beta2, r=mt
☠☠ backed out by aaf908d9dcb6 ☠ ☠
authorKai Engert <kaie@kuix.de>
Mon, 05 Oct 2015 22:42:28 +0200
changeset 299572 c288fb0952fb4d3fce858255d1667dc8a88f1b20
parent 299571 f679b59a7b53af15da45f36dbdc309b9a9b461d3
child 299573 be709ac91a4fa322015a6d589d24f713620b2e36
push id5392
push userraliiev@mozilla.com
push dateMon, 14 Dec 2015 20:08:23 +0000
treeherdermozilla-beta@16ce8562a975 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmt
bugs1211568
milestone44.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1211568 - Upgrade Firefox 44 to NSS 3.21, landing NSS_3_21_Beta2, r=mt
security/nss/.gitignore
security/nss/TAG-INFO
security/nss/circle.yml
security/nss/cmd/bltest/blapitest.c
security/nss/cmd/certcgi/certcgi.c
security/nss/cmd/certutil/certutil.c
security/nss/cmd/checkcert/checkcert.c
security/nss/cmd/crlutil/crlgen.c
security/nss/cmd/crlutil/crlutil.c
security/nss/cmd/crmftest/testcrmf.c
security/nss/cmd/fipstest/fipstest.c
security/nss/cmd/httpserv/httpserv.c
security/nss/cmd/lib/basicutil.c
security/nss/cmd/lib/derprint.c
security/nss/cmd/lib/pk11table.c
security/nss/cmd/lib/pk11table.h
security/nss/cmd/lib/secpwd.c
security/nss/cmd/lib/secutil.c
security/nss/cmd/modutil/error.h
security/nss/cmd/modutil/installparse.c
security/nss/cmd/modutil/lex.Pk11Install_yy.c
security/nss/cmd/modutil/manifest.mn
security/nss/cmd/modutil/modutil.c
security/nss/cmd/multinit/multinit.c
security/nss/cmd/ocspclnt/ocspclnt.c
security/nss/cmd/ocspresp/ocspresp.c
security/nss/cmd/oidcalc/oidcalc.c
security/nss/cmd/p7env/p7env.c
security/nss/cmd/pk11gcmtest/pk11gcmtest.c
security/nss/cmd/pk11mode/pk11mode.c
security/nss/cmd/pk12util/pk12util.c
security/nss/cmd/pk1sign/pk1sign.c
security/nss/cmd/pp/pp.c
security/nss/cmd/sdrtest/sdrtest.c
security/nss/cmd/selfserv/selfserv.c
security/nss/cmd/shlibsign/shlibsign.c
security/nss/cmd/signtool/certgen.c
security/nss/cmd/signtool/util.c
security/nss/cmd/ssltap/ssltap.c
security/nss/cmd/strsclnt/strsclnt.c
security/nss/cmd/symkeyutil/symkeyutil.c
security/nss/cmd/tstclnt/tstclnt.c
security/nss/cmd/vfychain/vfychain.c
security/nss/cmd/vfyserv/vfyserv.c
security/nss/cmd/vfyserv/vfyutil.c
security/nss/coreconf/Darwin.mk
security/nss/coreconf/Linux.mk
security/nss/coreconf/WIN32.mk
security/nss/coreconf/coreconf.dep
security/nss/coreconf/mkdepend/parse.c
security/nss/coreconf/rules.mk
security/nss/doc/certutil.xml
security/nss/doc/html/certutil.html
security/nss/doc/nroff/certutil.1
security/nss/external_tests/README
security/nss/external_tests/google_test/Makefile
security/nss/external_tests/ssl_gtest/Makefile
security/nss/external_tests/ssl_gtest/databuffer.h
security/nss/external_tests/ssl_gtest/libssl_internals.c
security/nss/external_tests/ssl_gtest/libssl_internals.h
security/nss/external_tests/ssl_gtest/manifest.mn
security/nss/external_tests/ssl_gtest/ssl_agent_unittest.cc
security/nss/external_tests/ssl_gtest/ssl_extension_unittest.cc
security/nss/external_tests/ssl_gtest/ssl_gtest.cc
security/nss/external_tests/ssl_gtest/ssl_loopback_unittest.cc
security/nss/external_tests/ssl_gtest/ssl_prf_unittest.cc
security/nss/external_tests/ssl_gtest/ssl_skip_unittest.cc
security/nss/external_tests/ssl_gtest/test_io.cc
security/nss/external_tests/ssl_gtest/test_io.h
security/nss/external_tests/ssl_gtest/tls_agent.cc
security/nss/external_tests/ssl_gtest/tls_agent.h
security/nss/external_tests/ssl_gtest/tls_connect.cc
security/nss/external_tests/ssl_gtest/tls_connect.h
security/nss/external_tests/ssl_gtest/tls_filter.cc
security/nss/external_tests/ssl_gtest/tls_filter.h
security/nss/external_tests/ssl_gtest/tls_parser.h
security/nss/lib/base/hash.c
security/nss/lib/base/list.c
security/nss/lib/base/tracker.c
security/nss/lib/certdb/certdb.c
security/nss/lib/certdb/crl.c
security/nss/lib/certdb/genname.c
security/nss/lib/certdb/secname.c
security/nss/lib/certhigh/certhigh.c
security/nss/lib/certhigh/certvfy.c
security/nss/lib/certhigh/certvfypkix.c
security/nss/lib/certhigh/ocsp.c
security/nss/lib/certhigh/xcrldist.c
security/nss/lib/ckfw/builtins/binst.c
security/nss/lib/ckfw/builtins/certdata.perl
security/nss/lib/ckfw/hash.c
security/nss/lib/ckfw/token.c
security/nss/lib/crmf/cmmfchal.c
security/nss/lib/crmf/crmfcont.c
security/nss/lib/crmf/crmfi.h
security/nss/lib/crmf/crmfpop.c
security/nss/lib/crmf/crmftmpl.c
security/nss/lib/cryptohi/keyhi.h
security/nss/lib/cryptohi/seckey.c
security/nss/lib/dbm/src/h_page.c
security/nss/lib/dbm/src/hash.c
security/nss/lib/dev/devslot.c
security/nss/lib/dev/devtoken.c
security/nss/lib/freebl/Makefile
security/nss/lib/freebl/cts.c
security/nss/lib/freebl/dh.c
security/nss/lib/freebl/drbg.c
security/nss/lib/freebl/dsa.c
security/nss/lib/freebl/ec.c
security/nss/lib/freebl/ecl/ecl-priv.h
security/nss/lib/freebl/ecl/ecl_gf.c
security/nss/lib/freebl/ecl/ecl_mult.c
security/nss/lib/freebl/ecl/ecp_192.c
security/nss/lib/freebl/ecl/ecp_224.c
security/nss/lib/freebl/ecl/ecp_256.c
security/nss/lib/freebl/ecl/ecp_256_32.c
security/nss/lib/freebl/ecl/ecp_521.c
security/nss/lib/freebl/ecl/ecp_jac.c
security/nss/lib/freebl/ldvector.c
security/nss/lib/freebl/loader.c
security/nss/lib/freebl/md5.c
security/nss/lib/freebl/mpi/mpcpucache.c
security/nss/lib/freebl/mpi/mpi-priv.h
security/nss/lib/freebl/mpi/mpi.c
security/nss/lib/freebl/mpi/mpi.h
security/nss/lib/freebl/mpi/mplogic.c
security/nss/lib/freebl/mpi/mplogic.h
security/nss/lib/freebl/mpi/mpmontg.c
security/nss/lib/freebl/mpi/mpprime.c
security/nss/lib/freebl/nsslowhash.c
security/nss/lib/freebl/nsslowhash.h
security/nss/lib/freebl/pqg.c
security/nss/lib/freebl/rsa.c
security/nss/lib/freebl/sha512.c
security/nss/lib/freebl/sha_fast.c
security/nss/lib/freebl/sha_fast.h
security/nss/lib/freebl/stubs.c
security/nss/lib/jar/jarfile.c
security/nss/lib/jar/jarsign.c
security/nss/lib/libpkix/include/pkix_certstore.h
security/nss/lib/libpkix/include/pkix_revchecker.h
security/nss/lib/libpkix/pkix/checker/pkix_crlchecker.c
security/nss/lib/libpkix/pkix/checker/pkix_crlchecker.h
security/nss/lib/libpkix/pkix/checker/pkix_ocspchecker.c
security/nss/lib/libpkix/pkix/checker/pkix_ocspchecker.h
security/nss/lib/libpkix/pkix/checker/pkix_revocationchecker.c
security/nss/lib/libpkix/pkix/checker/pkix_revocationchecker.h
security/nss/lib/libpkix/pkix/checker/pkix_revocationmethod.h
security/nss/lib/libpkix/pkix/crlsel/pkix_crlselector.c
security/nss/lib/libpkix/pkix/results/pkix_policynode.c
security/nss/lib/libpkix/pkix/store/pkix_store.c
security/nss/lib/libpkix/pkix/top/pkix_build.c
security/nss/lib/libpkix/pkix/util/pkix_error.c
security/nss/lib/libpkix/pkix/util/pkix_logger.c
security/nss/lib/libpkix/pkix/util/pkix_tools.h
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpdefaultclient.c
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_ldapdefaultclient.c
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_ldaprequest.c
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_ldapresponse.c
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_pk11certstore.c
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_socket.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crl.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_lifecycle.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_object.c
security/nss/lib/nss/manifest.mn
security/nss/lib/nss/nss.def
security/nss/lib/nss/nss.h
security/nss/lib/nss/nssinit.c
security/nss/lib/nss/nssoptions.c
security/nss/lib/nss/nssoptions.h
security/nss/lib/pk11wrap/pk11cert.c
security/nss/lib/pk11wrap/pk11load.c
security/nss/lib/pk11wrap/pk11mech.c
security/nss/lib/pk11wrap/pk11merge.c
security/nss/lib/pk11wrap/pk11obj.c
security/nss/lib/pk11wrap/pk11pars.c
security/nss/lib/pk11wrap/pk11pk12.c
security/nss/lib/pk11wrap/pk11skey.c
security/nss/lib/pk11wrap/pk11slot.c
security/nss/lib/pk11wrap/secmod.h
security/nss/lib/pkcs12/p12d.c
security/nss/lib/pkcs12/p12e.c
security/nss/lib/pkcs7/p7common.c
security/nss/lib/pkcs7/p7decode.c
security/nss/lib/pkcs7/p7encode.c
security/nss/lib/pkcs7/p7local.c
security/nss/lib/pki/certificate.c
security/nss/lib/pki/pki3hack.c
security/nss/lib/pki/pkibase.c
security/nss/lib/pki/tdcache.c
security/nss/lib/pki/trustdomain.c
security/nss/lib/smime/cmsasn1.c
security/nss/lib/smime/cmscinfo.c
security/nss/lib/smime/cmscipher.c
security/nss/lib/smime/cmsencode.c
security/nss/lib/smime/cmsrecinfo.c
security/nss/lib/smime/cmssiginfo.c
security/nss/lib/smime/cmsudf.c
security/nss/lib/smime/smimeutil.c
security/nss/lib/softoken/legacydb/Makefile
security/nss/lib/softoken/legacydb/keydb.c
security/nss/lib/softoken/legacydb/lgattr.c
security/nss/lib/softoken/legacydb/lginit.c
security/nss/lib/softoken/legacydb/lgutil.c
security/nss/lib/softoken/legacydb/pcertdb.c
security/nss/lib/softoken/lowpbe.c
security/nss/lib/softoken/pkcs11.c
security/nss/lib/softoken/pkcs11c.c
security/nss/lib/softoken/pkcs11i.h
security/nss/lib/softoken/pkcs11u.c
security/nss/lib/softoken/sdb.c
security/nss/lib/softoken/sftkdb.c
security/nss/lib/softoken/sftkhmac.c
security/nss/lib/softoken/sftkpwd.c
security/nss/lib/softoken/softkver.h
security/nss/lib/softoken/tlsprf.c
security/nss/lib/sqlite/Makefile
security/nss/lib/sqlite/sqlite3.c
security/nss/lib/ssl/SSLerrs.h
security/nss/lib/ssl/derive.c
security/nss/lib/ssl/dtlscon.c
security/nss/lib/ssl/ssl.def
security/nss/lib/ssl/ssl.h
security/nss/lib/ssl/ssl3con.c
security/nss/lib/ssl/ssl3ecc.c
security/nss/lib/ssl/ssl3ext.c
security/nss/lib/ssl/ssl3gthr.c
security/nss/lib/ssl/ssl3prot.h
security/nss/lib/ssl/sslauth.c
security/nss/lib/ssl/sslcon.c
security/nss/lib/ssl/sslerr.h
security/nss/lib/ssl/sslimpl.h
security/nss/lib/ssl/sslinfo.c
security/nss/lib/ssl/sslmutex.c
security/nss/lib/ssl/sslmutex.h
security/nss/lib/ssl/sslsecur.c
security/nss/lib/ssl/sslsnce.c
security/nss/lib/ssl/sslsock.c
security/nss/lib/ssl/sslt.h
security/nss/lib/util/derdec.c
security/nss/lib/util/derenc.c
security/nss/lib/util/manifest.mn
security/nss/lib/util/nssb64e.c
security/nss/lib/util/nssrwlk.c
security/nss/lib/util/nssutil.def
security/nss/lib/util/nssutil.h
security/nss/lib/util/pkcs11n.h
security/nss/lib/util/pkcs11t.h
security/nss/lib/util/quickder.c
security/nss/lib/util/secoid.c
security/nss/lib/util/secport.c
security/nss/lib/util/secport.h
security/nss/lib/util/utilmod.c
security/nss/lib/util/utilpars.c
security/nss/lib/util/utilpars.h
security/nss/lib/util/verref.h
security/nss/tests/all.sh
security/nss/tests/cert/cert.sh
security/nss/tests/common/cleanup.sh
security/nss/tests/common/init.sh
security/nss/tests/dbupgrade/dbupgrade.sh
security/nss/tests/pkcs11/netscape/suites/security/pkcs11/pk11test.c
security/nss/tests/ssl/ssl.sh
security/nss/tests/ssl/sslauth.txt
security/nss/tests/ssl_gtests/parsereport.sed
security/nss/tests/ssl_gtests/ssl_gtests.sh
new file mode 100644
--- /dev/null
+++ b/security/nss/.gitignore
@@ -0,0 +1,5 @@
+*~
+*.swp
+*OPT.OBJ/
+*DBG.OBJ/
+*DBG.OBJD/
--- a/security/nss/TAG-INFO
+++ b/security/nss/TAG-INFO
@@ -1,1 +1,1 @@
-NSS_3_20_RTM
+NSS_3_21_Beta2
new file mode 100644
--- /dev/null
+++ b/security/nss/circle.yml
@@ -0,0 +1,18 @@
+checkout:
+    post:
+        - cd ..; hg clone https://hg.mozilla.org/projects/nspr
+
+test:
+    override:
+        - make nss_build_all
+        - cd tests; NSS_TESTS=ssl_gtests NSS_CYCLES=standard ./all.sh
+
+machine:
+    environment:
+        { USE_64: 1,
+          NSS_ENABLE_TLS_1_3: 1,
+          NSS_BUILD_GTESTS: 1,
+        }
+    hosts:
+
+
--- a/security/nss/cmd/bltest/blapitest.c
+++ b/security/nss/cmd/bltest/blapitest.c
@@ -51,18 +51,17 @@ char *testdir = NULL;
 #define TIMEFINISH(time, reps) \
     time2 = (PRIntervalTime)(PR_IntervalNow() - time1); \
     time1 = PR_IntervalToMilliseconds(time2); \
     time = ((double)(time1))/reps;
 
 #define TIMEMARK(seconds) \
     time1 = PR_SecondsToInterval(seconds); \
     { \
-        PRInt64 tmp, L100; \
-        LL_I2L(L100, 100); \
+        PRInt64 tmp; \
         if (time2 == 0) { \
             time2 = 1; \
         } \
         LL_DIV(tmp, time1, time2); \
         if (tmp < 10) { \
             if (tmp == 0) { \
                 opsBetweenChecks = 1; \
             } else { \
@@ -308,29 +307,28 @@ char2_from_hex(unsigned char byteval, ch
     return SECSuccess;
 }
 
 void
 serialize_key(SECItem *it, int ni, PRFileDesc *file)
 {
     unsigned char len[4];
     int i;
-    SECStatus status;
     NSSBase64Encoder *cx;
     cx = NSSBase64Encoder_Create(output_ascii, file);
     for (i=0; i<ni; i++, it++) {
 	len[0] = (it->len >> 24) & 0xff;
 	len[1] = (it->len >> 16) & 0xff;
 	len[2] = (it->len >>  8) & 0xff;
 	len[3] = (it->len	 & 0xff);
-	status = NSSBase64Encoder_Update(cx, len, 4);
-	status = NSSBase64Encoder_Update(cx, it->data, it->len);
+	NSSBase64Encoder_Update(cx, len, 4);
+	NSSBase64Encoder_Update(cx, it->data, it->len);
     }
-    status = NSSBase64Encoder_Destroy(cx, PR_FALSE);
-    status = PR_Write(file, "\r\n", 2);
+    NSSBase64Encoder_Destroy(cx, PR_FALSE);
+    PR_Write(file, "\r\n", 2);
 }
 
 void
 key_from_filedata(PLArenaPool *arena, SECItem *it, int ns, int ni, SECItem *filedata)
 {
     int fpos = 0;
     int i, len;
     unsigned char *buf = filedata->data;
@@ -1431,17 +1429,17 @@ bltest_rc5_init(bltestCipherInfo *cipher
 SECStatus
 bltest_aes_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     bltestSymmKeyParams *aesp = &cipherInfo->params.sk;
     bltestAuthSymmKeyParams *gcmp = &cipherInfo->params.ask;
     int minorMode;
     int i;
     int keylen   = aesp->key.buf.len;
-    int blocklen = AES_BLOCK_SIZE; 
+    unsigned int blocklen = AES_BLOCK_SIZE;
     PRIntervalTime time1, time2;
     unsigned char *params;
     int len;
     CK_AES_CTR_PARAMS ctrParams;
     CK_GCM_PARAMS gcmParams;
 
     params = aesp->iv.buf.data;
     switch (cipherInfo->mode) {
@@ -1630,16 +1628,18 @@ bltest_rsa_init(bltestCipherInfo *cipher
         case bltestRSA_PSS:
             cipherInfo->cipher.pubkeyCipher = encrypt ? rsa_signDigestPSS
                                                       : rsa_verifyDigestPSS;
             break;
         case bltestRSA_OAEP:
             cipherInfo->cipher.pubkeyCipher = encrypt ? rsa_encryptOAEP
                                                       : rsa_decryptOAEP;
             break;
+        default:
+            break;
     }
     return SECSuccess;
 }
 
 SECStatus
 blapi_pqg_param_gen(unsigned int keysize, PQGParams **pqg, PQGVerify **vfy)
 {
     if (keysize < 1024) {
@@ -2564,18 +2564,16 @@ getHighUnitBytes(PRInt64 res)
 static void
 printPR_smpString(const char *sformat, char *reportStr,
                   const char *nformat, PRInt64 rNum)
 {
     if (reportStr) {
         fprintf(stdout, sformat, reportStr);
         PR_smprintf_free(reportStr);
     } else {
-        int prnRes;
-        LL_L2I(prnRes, rNum);
         fprintf(stdout, nformat, rNum);
     }
 }
 
 static char*
 getHighUnitOps(PRInt64 res)
 {
     int spl[] = {0, 0, 0, 0};
@@ -2786,18 +2784,18 @@ mode_str_to_hash_alg(const SECItem *mode
     switch (mode) {
         case bltestMD2:    return HASH_AlgMD2;
         case bltestMD5:    return HASH_AlgMD5;
         case bltestSHA1:   return HASH_AlgSHA1;
         case bltestSHA224: return HASH_AlgSHA224;
         case bltestSHA256: return HASH_AlgSHA256;
         case bltestSHA384: return HASH_AlgSHA384;
         case bltestSHA512: return HASH_AlgSHA512;
+        default: return HASH_AlgNULL;
     }
-    return HASH_AlgNULL;
 }
 
 void
 get_params(PLArenaPool *arena, bltestParams *params,
 	   bltestCipherMode mode, int j)
 {
     char filename[256];
     char *modestr = mode_strings[mode];
@@ -2999,17 +2997,17 @@ ReadFileToItem(SECItem *dst, const char 
 static SECStatus
 blapi_selftest(bltestCipherMode *modes, int numModes, int inoff, int outoff,
                PRBool encrypt, PRBool decrypt)
 {
     bltestCipherInfo cipherInfo;
     bltestIO pt, ct;
     bltestCipherMode mode;
     bltestParams *params;
-    int i, j, nummodes, numtests;
+    unsigned int i, j, nummodes, numtests;
     char *modestr;
     char filename[256];
     PLArenaPool *arena;
     SECItem item;
     SECStatus rv = SECSuccess, srv;
 
     PORT_Memset(&cipherInfo, 0, sizeof(cipherInfo));
     arena = PORT_NewArena(BLTEST_DEFAULT_CHUNKSIZE);
@@ -3452,23 +3450,22 @@ static secuCommandFlag bltest_options[] 
     { /* opt_MonteCarlo   */ '3', PR_FALSE, 0, PR_FALSE },
     { /* opt_ThreadNum    */ '4', PR_TRUE,  0, PR_FALSE },
     { /* opt_SecondsToRun */ '5', PR_TRUE,  0, PR_FALSE },
     { /* opt_CmdLine	  */ '-', PR_FALSE, 0, PR_FALSE }
 };
 
 int main(int argc, char **argv)
 {
-    char *infileName, *outfileName, *keyfileName, *ivfileName;
     SECStatus rv = SECFailure;
 
-    double              totalTime;
+    double              totalTime = 0.0;
     PRIntervalTime      time1, time2;
     PRFileDesc          *outfile = NULL;
-    bltestCipherInfo    *cipherInfoListHead, *cipherInfo;
+    bltestCipherInfo    *cipherInfoListHead, *cipherInfo = NULL;
     bltestIOMode        ioMode;
     int                 bufsize, exponent, curThrdNum;
 #ifndef NSS_DISABLE_ECC
     char		*curveName = NULL;
 #endif
     int			 i, commandsEntered;
     int			 inoff, outoff;
     int                  threads = 1;
@@ -3506,18 +3503,16 @@ int main(int argc, char **argv)
     if (rv == SECFailure) {
 	fprintf(stderr, "%s: command line parsing error!\n", progName);
 	goto print_usage;
     }
     rv = SECFailure;
 
     cipherInfo = PORT_ZNew(bltestCipherInfo);
     cipherInfoListHead = cipherInfo;
-    /* set some defaults */
-    infileName = outfileName = keyfileName = ivfileName = NULL;
 
     /* Check the number of commands entered on the command line. */
     commandsEntered = 0;
     for (i=0; i<bltest.numCommands; i++)
 	if (bltest.commands[i].activated)
 	    commandsEntered++;
 
     if (commandsEntered > 1 &&
@@ -3552,17 +3547,17 @@ int main(int argc, char **argv)
      * Handle three simple cases first
      */
 
     /* test the RSA_PopulatePrivateKey function */
     if (bltest.commands[cmd_RSAPopulate].activated) {
 	unsigned int keySize = 1024;
 	unsigned long exponent = 65537;
 	int rounds = 1;
-	int ret;
+	int ret = -1;
 	
 	if (bltest.options[opt_KeySize].activated) {
 	    keySize = PORT_Atoi(bltest.options[opt_KeySize].arg);
 	}
 	if (bltest.options[opt_Rounds].activated) {
 	    rounds = PORT_Atoi(bltest.options[opt_Rounds].arg);
 	}
 	if (bltest.options[opt_Exponent].activated) {
@@ -3707,18 +3702,20 @@ int main(int argc, char **argv)
 	curveName = NULL;
 #endif
 
     if (bltest.commands[cmd_Verify].activated &&
         !bltest.options[opt_SigFile].activated) {
         fprintf(stderr, "%s: You must specify a signature file with -f.\n",
                 progName);
 
-      print_usage:
-        PORT_Free(cipherInfo);
+print_usage:
+        if (cipherInfo) {
+            PORT_Free(cipherInfo);
+        }
         Usage();
     }
 
     if (bltest.options[opt_MonteCarlo].activated) {
         cipherInfo->mCarlo = PR_TRUE;
     } else {
         cipherInfo->mCarlo = PR_FALSE;
     }
--- a/security/nss/cmd/certcgi/certcgi.c
+++ b/security/nss/cmd/certcgi/certcgi.c
@@ -351,91 +351,16 @@ find_field_bool(Pair    *data,
 	
     if  ((rv != NULL) && (PORT_Strcmp(rv, "true")) == 0) {
 	return PR_TRUE;
     } else {
 	return PR_FALSE;
     }
 }
 
-static char *
-update_data_by_name(Pair  *data, 
-		    char  *field_name,
-                    char  *new_data)
-    /* replaces the data in the data structure associated with 
-       a name with new data, returns null if not found */
-{
-    int                   i = 0;
-    int                   found = 0;
-    int                   length = 100;
-    char                  *new;
-
-    while (return_name(data, i) != NULL) {
-	if (PORT_Strcmp(return_name(data, i), field_name) == 0) {
-	    new = make_copy_string( new_data, length, '\0');
-	    PORT_Free(return_data(data, i));
-	    found = 1;
-	    (*(data + i)).data = new;
-	    break;
-	}
-	i++;
-    }
-    if (!found) {
-	new = NULL;
-    }
-    return new;
-}
-
-static char *
-update_data_by_index(Pair  *data, 
-		     int   n, 
-		     char  *new_data)
-    /* replaces the data of a particular index in the data structure */
-{
-    int                    length = 100;
-    char                   *new;
-
-    new = make_copy_string(new_data, length, '\0');
-    PORT_Free(return_data(data, n));
-    (*(data + n)).data = new;
-    return new;
-}
-
-
-static Pair *
-add_field(Pair   *data, 
-	  char*  field_name, 
-	  char*  field_data)
-    /* adds a new name/data pair to the data structure */
-{
-    int          i = 0;
-    int          j;
-    int          name_length = 100;
-    int          data_length = 100;
-
-    while(return_name(data, i) != NULL) {
-	i++;
-    }
-    j = START_FIELDS;
-    while ( j < (i + 1) ) {
-	j = j * 2;
-    }
-    if (j == (i + 1)) {
-	data = (Pair *) PORT_Realloc(data, (j * 2) * sizeof(Pair));
-	if (data == NULL) {
-	    error_allocate();
-	}
-    }
-    (*(data + i)).name = make_copy_string(field_name, name_length, '\0');
-    (*(data + i)).data = make_copy_string(field_data, data_length, '\0');
-    (data + i + 1)->name = NULL;
-    return data;
-}
-
-
 static CERTCertificateRequest *
 makeCertReq(Pair             *form_data,
 	    int              which_priv_key)
     /* makes and encodes a certrequest */
 {
 
     PK11SlotInfo             *slot;
     CERTCertificateRequest   *certReq = NULL;
@@ -522,40 +447,36 @@ MakeV1Cert(CERTCertDBHandle        *hand
 	   Pair                    *data)
 {
     CERTCertificate                 *issuerCert = NULL;
     CERTValidity                    *validity;
     CERTCertificate                 *cert = NULL;
     PRExplodedTime                  printableTime;
     PRTime                          now, 
 	                            after;
-    SECStatus rv;
-   
-    
-
     if ( !selfsign ) {
 	issuerCert = CERT_FindCertByNameString(handle, issuerNameStr);
 	if (!issuerCert) {
 	    error_out("ERROR: Could not find issuer's certificate");
 	    return NULL;
 	}
     }
     if (find_field_bool(data, "manValidity", PR_TRUE)) {
-	rv = DER_AsciiToTime(&now, find_field(data, "notBefore", PR_TRUE));
+	(void)DER_AsciiToTime(&now, find_field(data, "notBefore", PR_TRUE));
     } else {
 	now = PR_Now();
     }
     PR_ExplodeTime (now, PR_GMTParameters, &printableTime);
     if ( warpmonths ) {
 	printableTime.tm_month += warpmonths;
 	now = PR_ImplodeTime (&printableTime);
 	PR_ExplodeTime (now, PR_GMTParameters, &printableTime);
     }
     if (find_field_bool(data, "manValidity", PR_TRUE)) {
-	rv = DER_AsciiToTime(&after, find_field(data, "notAfter", PR_TRUE));
+	(void)DER_AsciiToTime(&after, find_field(data, "notAfter", PR_TRUE));
 	PR_ExplodeTime (after, PR_GMTParameters, &printableTime);
     } else {
 	printableTime.tm_month += 3;
 	after = PR_ImplodeTime (&printableTime);
     }
     /* note that the time is now in micro-second unit */
     validity = CERT_CreateValidity (now, after);
 
@@ -582,21 +503,21 @@ get_serial_number(Pair  *data)
     char                *filename = SERIAL_FILE;
     char                *SN;
     FILE                *serialFile;
 
 
     if (find_field_bool(data, "serial-auto", PR_TRUE)) {
 	serialFile = fopen(filename, "r");
 	if (serialFile != NULL) {
-	    fread(&serial, sizeof(int), 1, serialFile);
-	    if (ferror(serialFile) != 0) {
+	    size_t nread = fread(&serial, sizeof(int), 1, serialFile);
+	    if (ferror(serialFile) != 0 || nread != 1) {
 		error_out("Error: Unable to read serial number file");
 	    }
-	    if (serial == 4294967295) {
+	    if (serial == -1) {
 		serial = 21;
 	    }
 	    fclose(serialFile);
 	    ++serial;
 	    serialFile = fopen(filename,"w");
 	    if (serialFile == NULL) {
 	        error_out("ERROR: Unable to open serial number file for writing");
 	    }
@@ -1412,62 +1333,59 @@ string_to_ipaddress(char *string)
     *(ipaddress->data + j) = '\0';
     if (j != 4 && j != 8) {
 	error_out("ERROR: Improperly formated IP Address");
     }
     ipaddress->len = j;
     return ipaddress;
 }
 
+static int
+chr_to_hex(char c) {
+    if (isdigit(c)) {
+        return c - '0';
+    }
+    if (isxdigit(c)) {
+        return toupper(c) - 'A' + 10;
+    }
+    return -1;
+}
+
 static SECItem *
-string_to_binary(char  *string)
+string_to_binary(char *string)
 {
     SECItem            *rv;
-    int                high_digit;
-    int                low_digit;
 
     rv = (SECItem *) PORT_ZAlloc(sizeof(SECItem));
     if (rv == NULL) {
 	error_allocate();
     }
     rv->data = (unsigned char *) PORT_ZAlloc((PORT_Strlen(string))/3 + 2);
-    while (!isxdigit(*string)) {
+    rv->len = 0;
+    while (*string && !isxdigit(*string)) {
 	string++;
     }
-    rv->len = 0;
-    while (*string != '\0') {
-	if (isxdigit(*string)) {
-	    if (*string >= '0' && *string <= '9') {
-		high_digit = *string - '0';
-	    } else {
-		*string = toupper(*string);
-		high_digit = *string - 'A' + 10;
-	    }
-	    string++;
-	    if (*string >= '0' && *string <= '9') {
-		low_digit = *string - '0';
-	    } else {
-		*string = toupper(*string);
-		low_digit = *string - 'A' + 10;
-	    }
-	    (rv->len)++;
-	} else {
-	    if (*string == ':') {
-		string++;
-	    } else {
-		if (*string == ' ') {
-		    while (*string == ' ') {
-			string++;
-		    }
-		}
-		if (*string != '\0') {
-		    error_out("ERROR: Improperly formated binary encoding");
-		}
-	    }
-	} 
+    while (*string) {
+        int high, low;
+        high = chr_to_hex(*string++);
+        low = chr_to_hex(*string++);
+        if (high < 0 || low < 0) {
+            error_out("ERROR: Improperly formated binary encoding");
+        }
+	rv->data[(rv->len)++] = high << 4 | low;
+        if (*string != ':') {
+            break;
+        }
+        ++string;
+    }
+    while (*string == ' ') {
+       ++string;
+    }
+    if (*string) {
+        error_out("ERROR: Junk after binary encoding");
     }
 
     return rv;
 }
 
 static SECStatus
 MakeGeneralName(char             *name, 
 		CERTGeneralName  *genName,
--- a/security/nss/cmd/certutil/certutil.c
+++ b/security/nss/cmd/certutil/certutil.c
@@ -604,16 +604,37 @@ DeleteCert(CERTCertDBHandle *handle, cha
     rv = SEC_DeletePermCertificate(cert);
     CERT_DestroyCertificate(cert);
     if (rv) {
 	SECU_PrintError(progName, "unable to delete certificate");
     }
     return rv;
 }
 
+static SECStatus 
+RenameCert(CERTCertDBHandle *handle, char *name, char *newName)
+{
+    SECStatus rv;
+    CERTCertificate *cert;
+
+    cert = CERT_FindCertByNicknameOrEmailAddr(handle, name);
+    if (!cert) {
+	SECU_PrintError(progName, "could not find certificate named \"%s\"",
+			name);
+	return SECFailure;
+    }
+
+    rv = __PK11_SetCertificateNickname(cert, newName);
+    CERT_DestroyCertificate(cert);
+    if (rv) {
+	SECU_PrintError(progName, "unable to rename certificate");
+    }
+    return rv;
+}
+
 static SECStatus
 ValidateCert(CERTCertDBHandle *handle, char *name, char *date,
              char *certUsage, PRBool checkSig, PRBool logit,
              PRBool ascii, secuPWData *pwdata)
 {
     SECStatus rv;
     CERTCertificate *cert = NULL;
     PRTime timeBoundary;
@@ -979,16 +1000,18 @@ PrintSyntax(char *progName)
 	"\t\t [-m serial-number] [-w warp-months] [-v months-valid]\n"
         "\t\t [-f pwfile] [-d certdir] [-P dbprefix] [-Z hashAlg]\n"
         "\t\t [-1 | --keyUsage [keyUsageKeyword,..]] [-2] [-3] [-4]\n"
         "\t\t [-5 | --nsCertType [nsCertTypeKeyword,...]]\n"
         "\t\t [-6 | --extKeyUsage [extKeyUsageKeyword,...]] [-7 emailAddrs]\n"
         "\t\t [-8 dns-names] [-a]\n",
 	progName);
     FPS "\t%s -D -n cert-name [-d certdir] [-P dbprefix]\n", progName);
+    FPS "\t%s --rename -n cert-name --new-n new-cert-name\n"
+        "\t\t [-d certdir] [-P dbprefix]\n", progName);
     FPS "\t%s -E -n cert-name -t trustargs [-d certdir] [-P dbprefix] [-a] [-i input]\n",
 	progName);
     FPS "\t%s -F -n nickname [-d certdir] [-P dbprefix]\n", 
 	progName);
     FPS "\t%s -G -n key-name [-h token-name] [-k rsa] [-g key-size] [-y exp]\n" 
 	"\t\t [-f pwfile] [-z noisefile] [-d certdir] [-P dbprefix]\n", progName);
     FPS "\t%s -G [-h token-name] -k dsa [-q pqgfile -g key-size] [-f pwfile]\n"
 	"\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName);
@@ -1545,16 +1568,35 @@ static void luW(enum usage_level ul, con
         "   -d certdir");
     FPS "%-20s Specify a file with the current password\n",
         "   -f pwfile");
     FPS "%-20s Specify a file with the new password in two lines\n",
         "   -@ newpwfile");
     FPS "\n");
 }
 
+static void luRename(enum usage_level ul, const char *command)
+{
+    int is_my_command = (command && 0 == strcmp(command, "rename"));
+    if (ul == usage_all || !command || is_my_command)
+    FPS "%-15s Change the database nickname of a certificate\n",
+        "--rename");
+    if (ul == usage_selected && !is_my_command)
+        return;
+    FPS "%-20s The old nickname of the cert to rename\n",
+        "   -n cert-name");
+    FPS "%-20s The new nickname of the cert to rename\n",
+        "   --new-n new-name");
+    FPS "%-20s Cert database directory (default is ~/.netscape)\n",
+        "   -d certdir");
+    FPS "%-20s Cert & Key database prefix\n",
+        "   -P dbprefix");
+    FPS "\n");
+}
+
 static void luUpgradeMerge(enum usage_level ul, const char *command)
 {
     int is_my_command = (command && 0 == strcmp(command, "upgrade-merge"));
     if (ul == usage_all || !command || is_my_command)
     FPS "%-15s Upgrade an old database and merge it into a new one\n",
         "--upgrade-merge");
     if (ul == usage_selected && !is_my_command)
         return;
@@ -1707,16 +1749,17 @@ static void luS(enum usage_level ul, con
 static void LongUsage(char *progName, enum usage_level ul, const char *command)
 {
     luA(ul, command);
     luB(ul, command);
     luE(ul, command);
     luC(ul, command);
     luG(ul, command);
     luD(ul, command);
+    luRename(ul, command);
     luF(ul, command);
     luU(ul, command);
     luK(ul, command);
     luL(ul, command);
     luM(ul, command);
     luN(ul, command);
     luT(ul, command);
     luO(ul, command);
@@ -2206,16 +2249,17 @@ enum {
     cmd_TokenReset,
     cmd_ListModules,
     cmd_CheckCertValidity,
     cmd_ChangePassword,
     cmd_Version,
     cmd_Batch,
     cmd_Merge,
     cmd_UpgradeMerge, /* test only */
+    cmd_Rename,
     max_cmd
 };
 
 /*  Certutil options */
 enum certutilOpts {
     opt_SSOPass = 0,
     opt_AddKeyUsageExt,
     opt_AddBasicConstraintExt,
@@ -2274,16 +2318,17 @@ enum certutilOpts {
     opt_KeyOpFlagsOn,
     opt_KeyOpFlagsOff,
     opt_KeyAttrFlags,
     opt_EmptyPassword,
     opt_CertVersion,
     opt_AddSubjectAltNameExt,
     opt_DumpExtensionValue,
     opt_GenericExtensions,
+    opt_NewNickname,
     opt_Help
 };
 
 static const
 secuCommandFlag commands_init[] =
 {
 	{ /* cmd_AddCert             */  'A', PR_FALSE, 0, PR_FALSE },
 	{ /* cmd_CreateNewCert       */  'C', PR_FALSE, 0, PR_FALSE },
@@ -2304,17 +2349,19 @@ secuCommandFlag commands_init[] =
 	{ /* cmd_TokenReset          */  'T', PR_FALSE, 0, PR_FALSE },
 	{ /* cmd_ListModules         */  'U', PR_FALSE, 0, PR_FALSE },
 	{ /* cmd_CheckCertValidity   */  'V', PR_FALSE, 0, PR_FALSE },
 	{ /* cmd_ChangePassword      */  'W', PR_FALSE, 0, PR_FALSE },
 	{ /* cmd_Version             */  'Y', PR_FALSE, 0, PR_FALSE },
 	{ /* cmd_Batch               */  'B', PR_FALSE, 0, PR_FALSE },
 	{ /* cmd_Merge               */   0,  PR_FALSE, 0, PR_FALSE, "merge" },
 	{ /* cmd_UpgradeMerge        */   0,  PR_FALSE, 0, PR_FALSE, 
-                                                   "upgrade-merge" }
+                                                   "upgrade-merge" },
+	{ /* cmd_Rename              */   0,  PR_FALSE, 0, PR_FALSE, 
+                                                   "rename" }
 };
 #define NUM_COMMANDS ((sizeof commands_init) / (sizeof commands_init[0]))
  
 static const 
 secuCommandFlag options_init[] =
 {
 	{ /* opt_SSOPass             */  '0', PR_TRUE,  0, PR_FALSE },
 	{ /* opt_AddKeyUsageExt      */  '1', PR_FALSE, 0, PR_FALSE },
@@ -2390,16 +2437,18 @@ secuCommandFlag options_init[] =
                                                    "empty-password"},
         { /* opt_CertVersion         */  0,   PR_TRUE, 0, PR_FALSE,
                                                    "certVersion"},
 	{ /* opt_AddSubjectAltExt    */  0,   PR_TRUE,  0, PR_FALSE, "extSAN"},
 	{ /* opt_DumpExtensionValue  */  0,   PR_TRUE, 0, PR_FALSE, 
                                                    "dump-ext-val"},
 	{ /* opt_GenericExtensions   */  0,   PR_TRUE, 0, PR_FALSE, 
                                                    "extGeneric"},
+	{ /* opt_NewNickname         */  0,   PR_TRUE, 0, PR_FALSE, 
+                                                   "new-n"},
 };
 #define NUM_OPTIONS ((sizeof options_init)  / (sizeof options_init[0]))
 
 static secuCommandFlag certutil_commands[NUM_COMMANDS];
 static secuCommandFlag certutil_options [NUM_OPTIONS ];
 
 static const secuCommand certutil = {
     NUM_COMMANDS, 
@@ -2423,16 +2472,17 @@ certutil_main(int argc, char **argv, PRB
     const char *slotname        = "internal";
     const char *certPrefix      = "";
     char *      sourceDir       = "";
     const char *srcCertPrefix   = "";
     char *      upgradeID        = "";
     char *      upgradeTokenName     = "";
     KeyType     keytype         = rsaKey;
     char *      name            = NULL;
+    char *      newName         = NULL;
     char *      email            = NULL;
     char *      keysource       = NULL;
     SECOidTag   hashAlgTag      = SEC_OID_UNKNOWN;
     int	        keysize	        = DEFAULT_KEY_BITS;
     int         publicExponent  = 0x010001;
     int         certVersion     = SEC_CERTIFICATE_VERSION_3;
     unsigned int serialNumber   = 0;
     int         warpmonths      = 0;
@@ -2781,16 +2831,29 @@ certutil_main(int argc, char **argv, PRB
     if (certutil.commands[cmd_CheckCertValidity].activated &&
         !certutil.options[opt_Usage].activated) {
 	PR_fprintf(PR_STDERR, 
 	           "%s -V: specify a usage to validate the cert for (-u).\n",
 	           progName);
 	return 255;
     }
 
+    /* Rename needs an old and a new nickname */
+    if (certutil.commands[cmd_Rename].activated &&
+        !(certutil.options[opt_Nickname].activated &&
+          certutil.options[opt_NewNickname].activated)) {
+
+	PR_fprintf(PR_STDERR, 
+	           "%s --rename: specify an old nickname (-n) and\n"
+                   "   a new nickname (--new-n).\n",
+	           progName);
+	return 255;
+    }
+
+
     /* Upgrade/Merge needs a source database and a upgrade id. */
     if (certutil.commands[cmd_UpgradeMerge].activated &&
         !(certutil.options[opt_SourceDir].activated &&
           certutil.options[opt_UpgradeID].activated)) {
 
 	PR_fprintf(PR_STDERR, 
 	           "%s --upgrade-merge: specify an upgrade database directory "
 		   "(--source-dir) and\n"
@@ -2862,16 +2925,17 @@ certutil_main(int argc, char **argv, PRB
 	               "%s:  unable to open \"%s\" for writing (%ld, %ld).\n",
 	               progName, certutil.options[opt_OutputFile].arg,
 	               PR_GetError(), PR_GetOSError());
 	    return 255;
 	}
     }
 
     name = SECU_GetOptionArg(&certutil, opt_Nickname);
+    newName = SECU_GetOptionArg(&certutil, opt_NewNickname);
     email = SECU_GetOptionArg(&certutil, opt_Emailaddress);
 
     PK11_SetPasswordFunc(SECU_GetModulePassword);
 
     if (PR_TRUE == initialize) {
         /*  Initialize NSPR and NSS.  */
         PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
 	if (!certutil.commands[cmd_UpgradeMerge].activated) {
@@ -3100,16 +3164,21 @@ merge_fail:
 	rv = ListModules();
 	goto shutdown;
     }
     /*  Delete cert (-D)  */
     if (certutil.commands[cmd_DeleteCert].activated) {
 	rv = DeleteCert(certHandle, name);
 	goto shutdown;
     }
+    /*  Rename cert (--rename)  */
+    if (certutil.commands[cmd_Rename].activated) {
+	rv = RenameCert(certHandle, name, newName);
+	goto shutdown;
+    }
     /*  Delete key (-F)  */
     if (certutil.commands[cmd_DeleteKey].activated) {
 	rv = DeleteKey(name, &pwdata);
 	goto shutdown;
     }
     /*  Modify trust attribute for cert (-M)  */
     if (certutil.commands[cmd_ModifyCertTrust].activated) {
 	rv = ChangeTrustAttributes(certHandle, slot, name, 
--- a/security/nss/cmd/checkcert/checkcert.c
+++ b/security/nss/cmd/checkcert/checkcert.c
@@ -117,30 +117,27 @@ void checkName(CERTName *n, char *fieldN
 static
 SECStatus
 OurVerifyData(unsigned char *buf, int len, SECKEYPublicKey *key,
 	      SECItem *sig, SECAlgorithmID *sigAlgorithm)
 {
     SECStatus rv;
     VFYContext *cx;
     SECOidData *sigAlgOid, *oiddata;
-    SECOidTag sigAlgTag;
     SECOidTag hashAlgTag;
     int showDigestOid=0;
 
     cx = VFY_CreateContextWithAlgorithmID(key, sig, sigAlgorithm, &hashAlgTag, 
                                           NULL);
     if (cx == NULL)
 	return SECFailure;
 
     sigAlgOid = SECOID_FindOID(&sigAlgorithm->algorithm);
     if (sigAlgOid == 0)
 	return SECFailure;
-    sigAlgTag = sigAlgOid->offset;
-
 
     if (showDigestOid) {
 	oiddata = SECOID_FindOIDByTag(hashAlgTag);
 	if ( oiddata ) {
 	    printf("PROBLEM: (cont) Digest OID is %s\n", oiddata->desc);
 	} else {
 	    SECU_PrintAsHex(stdout,
 			    &oiddata->oid, "PROBLEM: UNKNOWN OID", 0);
@@ -383,17 +380,17 @@ int main(int argc, char **argv)
 
 
     if (verbose) {
 	printf("Decoded ok as an X509 certificate.\n");
     }
 
     SECU_RegisterDynamicOids();
     rv = SECU_PrintSignedData(stdout, &derCert, "Certificate", 0,
-			      SECU_PrintCertificate);
+			      (SECU_PPFunc)SECU_PrintCertificate);
 
     if (rv) {
 	fprintf(stderr, "%s: Unable to pretty print cert. Error: %d\n",
 		progName, PORT_GetError());
 	if (!force) {
 	    exit(1);
 	}
     }
--- a/security/nss/cmd/crlutil/crlgen.c
+++ b/security/nss/cmd/crlutil/crlgen.c
@@ -540,17 +540,17 @@ crlgen_AddCrlNumber(CRLGENGeneratorData 
 /* Creates Cert Revocation Reason code extension. Encodes it and
  * returns as SECItem structure */
 static SECItem*
 crlgen_CreateReasonCode(PLArenaPool *arena, const char **dataArr,
                         int *extCode)
 {
     SECItem *encodedItem;
     void *dummy;
-    void *mark;
+    void *mark = NULL;
     int code = 0;
 
     PORT_Assert(arena && dataArr);
     if (!arena || !dataArr) {
         goto loser;
     } 
 
     mark = PORT_ArenaMark(arena);
@@ -578,29 +578,31 @@ crlgen_CreateReasonCode(PLArenaPool *are
     if (!dummy) {
         goto loser;
     }
 
     *extCode = SEC_OID_X509_REASON_CODE;
     return encodedItem;
 
   loser:
-    PORT_ArenaRelease (arena, mark);
+    if (mark) {
+        PORT_ArenaRelease (arena, mark);
+    }
     return NULL;
 }
 
 /* Creates Cert Invalidity Date extension. Encodes it and
  * returns as SECItem structure */
 static SECItem*
 crlgen_CreateInvalidityDate(PLArenaPool *arena, const char **dataArr,
                        int *extCode)
 {
     SECItem *encodedItem;
     int length = 0;
-    void *mark;
+    void *mark = NULL;
 
     PORT_Assert(arena && dataArr);
     if (!arena || !dataArr) {
         goto loser;
     } 
 
     mark = PORT_ArenaMark(arena);
 
@@ -619,17 +621,19 @@ crlgen_CreateInvalidityDate(PLArenaPool 
 
     PORT_Memcpy(encodedItem->data, dataArr[2], (encodedItem->len = length) *
                 sizeof(char));
 
     *extCode = SEC_OID_X509_INVALID_DATE;
     return encodedItem;
     
   loser:
-    PORT_ArenaRelease(arena, mark);
+    if (mark) {
+        PORT_ArenaRelease(arena, mark);
+    }
     return NULL;
 }
 
 /* Creates(by calling extCreator function) and adds extension to a set
  * of already added certs. Uses values of rangeFrom and rangeTo from
  * CRLGENCrlGenCtl structure for identifying the inclusive set of certs */
 static SECStatus
 crlgen_AddEntryExtension(CRLGENGeneratorData *crlGenData,
@@ -1074,26 +1078,23 @@ crlgen_AddCert(CRLGENGeneratorData *crlG
 
 
 /* Removes certs from entryDataHashTable which have certId serial number.
  * certId can have value of a range of certs */
 static SECStatus
 crlgen_RmCert(CRLGENGeneratorData *crlGenData, char *certId)
 {
     PRUint64 i = 0;
-    PLArenaPool *arena;
 
     PORT_Assert(crlGenData && certId);
     if (!crlGenData || !certId) {
         PORT_SetError(SEC_ERROR_INVALID_ARGS);
         return SECFailure;
     }
 
-    arena = crlGenData->signCrl->arena;
-
     if (crlgen_SetNewRangeField(crlGenData, certId) == SECFailure &&
         certId) {
         return SECFailure;
     }
 
     for (i = 0;i < crlGenData->rangeTo - crlGenData->rangeFrom + 1;i++) {
         SECItem* certIdItem = SEC_ASN1EncodeInteger(NULL, NULL,
                                                     crlGenData->rangeFrom + i);
--- a/security/nss/cmd/crlutil/crlutil.c
+++ b/security/nss/cmd/crlutil/crlutil.c
@@ -123,17 +123,17 @@ static void ListCRLNames (CERTCertDBHand
 
 	crlNode  = crlList->first;
 
         fprintf (stdout, "\n");
 	fprintf (stdout, "\n%-40s %-5s\n\n", "CRL names", "CRL Type");
 	while (crlNode) {
 	    char* asciiname = NULL;
 	    CERTCertificate *cert = NULL;
-	    if (crlNode->crl && &crlNode->crl->crl.derName) {
+	    if (crlNode->crl && crlNode->crl->crl.derName.data != NULL) {
 	        cert = CERT_FindCertByName(certHandle,
 	                                   &crlNode->crl->crl.derName);
 	        if (!cert) {
 	            SECU_PrintError(progName, "could not find signing "
 	                         "certificate in database");
 	        }
 	    }
 	    if (cert) {
@@ -693,41 +693,45 @@ GenerateCRL (CERTCertDBHandle *certHandl
         SECU_PrintError(progName, "fail to allocate memory\n");
         return SECFailure;
     }
 
     if (modifyFlag == PR_TRUE) {
         signCrl = CreateModifiedCRLCopy(arena, certHandle, &cert, certNickName,
                                          inFile, decodeOptions, importOptions);
         if (signCrl == NULL) {
+            rv = SECFailure;
             goto loser;
         }
     }
 
     if (!cert) {
         cert = FindSigningCert(certHandle, signCrl, certNickName);
         if (cert == NULL) {
+            rv = SECFailure;
             goto loser;
         }
     }
 
     if (!signCrl) {
         if (modifyFlag == PR_TRUE) {
             if (!outFileName) {
                 int len = strlen(certNickName) + 5;
                 outFileName = PORT_ArenaAlloc(arena, len);
                 PR_snprintf(outFileName, len, "%s.crl", certNickName);
             }
             SECU_PrintError(progName, "Will try to generate crl. "
                             "It will be saved in file: %s",
                             outFileName);
         }
         signCrl = CreateNewCrl(arena, certHandle, cert);
-        if (!signCrl)
+        if (!signCrl) {
+            rv = SECFailure;
             goto loser;
+        }
     }
 
     rv = UpdateCrl(signCrl, inCrlInitFile);
     if (rv != SECSuccess) {
         goto loser;
     }
 
     rv = SignAndStoreCrl(signCrl, cert, outFileName, hashAlgTag, ascii,
--- a/security/nss/cmd/crmftest/testcrmf.c
+++ b/security/nss/cmd/crmftest/testcrmf.c
@@ -122,23 +122,27 @@ debug_test(SECItem *src, char *filePath)
     }
     PR_Write(fileDesc, src->data, src->len);
     
 }
 
 SECStatus
 get_serial_number(long *dest)
 {
-   SECStatus   rv;
+    SECStatus rv;
 
-   if (dest == NULL) {
+    if (dest == NULL) {
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
        return SECFailure;
-   }
+    }
     rv = PK11_GenerateRandom((unsigned char *)dest, sizeof(long));
+    if (rv != SECSuccess) {
+       /* PK11_GenerateRandom calls PORT_SetError */
+       return SECFailure;
+    }
     /* make serial number positive */
     if (*dest < 0L)
     	*dest = - *dest;
     return SECSuccess;
 }
 
 PK11RSAGenParams *
 GetRSAParams(void) 
@@ -932,28 +936,16 @@ DoCMMFStuff(void)
         CERT_DestroyCertificate(cert);
     }
     if (list) {
         CERT_DestroyCertList(list);
     }
     return rv;
 }
 
-static CK_MECHANISM_TYPE
-mapWrapKeyType(KeyType keyType)
-{
-    switch (keyType) {
-    case rsaKey:
-        return CKM_RSA_PKCS;
-    default:
-        break;
-    }
-    return CKM_INVALID_MECHANISM;
-} 
-
 #define KNOWN_MESSAGE_LENGTH 20 /*160 bits*/
 
 int
 DoKeyRecovery( SECKEYPrivateKey *privKey)
 {
 #ifdef DOING_KEY_RECOVERY  /* Doesn't compile yet. */
     SECKEYPublicKey      *pubKey;
     PK11SlotInfo         *slot;
@@ -1528,20 +1520,16 @@ main(int argc, char **argv)
     PLOptState       *optstate;
     PLOptStatus       status;
     char             *password = NULL;
     char             *pwfile = NULL;
     int               irv     = 0;
     PRUint32          flags   = 0;
     SECStatus         rv;
     PRBool            nssInit = PR_FALSE;
-    PRBool            pArg    = PR_FALSE;
-    PRBool            eArg    = PR_FALSE;
-    PRBool            sArg    = PR_FALSE;
-    PRBool            PArg    = PR_FALSE;
 
     memset( &signPair,  0, sizeof signPair);
     memset( &cryptPair, 0, sizeof cryptPair);
     printf ("\ncrmftest v1.0\n");
     optstate = PL_CreateOptState(argc, argv, "d:p:e:s:P:f:");
     while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
 	switch (optstate->option) {
 	case 'd':
@@ -1554,43 +1542,39 @@ main(int argc, char **argv)
 	    nssInit = PR_TRUE;
 	    break;
 	case 'p':
 	    personalCert = PORT_Strdup(optstate->value);
 	    if (personalCert == NULL) {
 	        printf ("-p  failed\n");
 	        return 603;
 	    }
-	    pArg = PR_TRUE;
 	    break;
 	case 'e':
 	    recoveryEncrypter = PORT_Strdup(optstate->value);
 	    if (recoveryEncrypter == NULL) {
 	        printf ("-e  failed\n");
 	        return 602;
 	    }
-	    eArg = PR_TRUE;
 	    break;
 	case 's':
 	    caCertName = PORT_Strdup(optstate->value);
 	    if (caCertName == NULL) {
 	        printf ("-s  failed\n");
 	        return 604;
 	    }
-	    sArg = PR_TRUE;
 	    break;
 	case 'P':
 	    password = PORT_Strdup(optstate->value);
 	    if (password == NULL) {
 	        printf ("-P  failed\n");
 	        return 606;
 	    }
             pwdata.source = PW_PLAINTEXT;
             pwdata.data = password;
-	    PArg = PR_TRUE;
 	    break;
         case 'f':
 	    pwfile = PORT_Strdup(optstate->value);
 	    if (pwfile == NULL) {
 	        printf ("-f  failed\n");
 	        return 607;
 	    }
             pwdata.source = PW_FROMFILE;
--- a/security/nss/cmd/fipstest/fipstest.c
+++ b/security/nss/cmd/fipstest/fipstest.c
@@ -12,16 +12,31 @@
 #include "secerr.h"
 #include "secder.h"
 #include "secdig.h"
 #include "secoid.h"
 #include "ec.h"
 #include "hasht.h"
 #include "lowkeyi.h"
 #include "softoken.h"
+#include "pkcs11t.h"
+#define __PASTE(x,y) x##y
+#undef CK_PKCS11_FUNCTION_INFO
+#undef CK_NEED_ARG_LIST
+#define CK_EXTERN extern
+#define CK_PKCS11_FUNCTION_INFO(func) \
+                CK_RV __PASTE(NS,func)
+#define CK_NEED_ARG_LIST        1
+#include "pkcs11f.h"
+#undef CK_PKCS11_FUNCTION_INFO
+#undef CK_NEED_ARG_LIST
+#undef __PASTE
+#define SSL3_RANDOM_LENGTH              32
+
+
 
 #if 0
 #include "../../lib/freebl/mpi/mpi.h"
 #endif
 
 #ifndef NSS_DISABLE_ECC
 extern SECStatus
 EC_DecodeParams(const SECItem *encodedParams, ECParams **ecparams);
@@ -41,64 +56,64 @@ EC_CopyParams(PLArenaPool *arena, ECPara
 
 SECStatus
 hex_to_byteval(const char *c2, unsigned char *byteval)
 {
     int i;
     unsigned char offset;
     *byteval = 0;
     for (i=0; i<2; i++) {
-	if (c2[i] >= '0' && c2[i] <= '9') {
-	    offset = c2[i] - '0';
-	    *byteval |= offset << 4*(1-i);
-	} else if (c2[i] >= 'a' && c2[i] <= 'f') {
-	    offset = c2[i] - 'a';
-	    *byteval |= (offset + 10) << 4*(1-i);
-	} else if (c2[i] >= 'A' && c2[i] <= 'F') {
-	    offset = c2[i] - 'A';
-	    *byteval |= (offset + 10) << 4*(1-i);
-	} else {
-	    return SECFailure;
-	}
+        if (c2[i] >= '0' && c2[i] <= '9') {
+            offset = c2[i] - '0';
+            *byteval |= offset << 4*(1-i);
+        } else if (c2[i] >= 'a' && c2[i] <= 'f') {
+            offset = c2[i] - 'a';
+            *byteval |= (offset + 10) << 4*(1-i);
+        } else if (c2[i] >= 'A' && c2[i] <= 'F') {
+            offset = c2[i] - 'A';
+            *byteval |= (offset + 10) << 4*(1-i);
+        } else {
+            return SECFailure;
+        }
     }
     return SECSuccess;
 }
 
 SECStatus
 byteval_to_hex(unsigned char byteval, char *c2, char a)
 {
     int i;
     unsigned char offset;
     for (i=0; i<2; i++) {
-	offset = (byteval >> 4*(1-i)) & 0x0f;
-	if (offset < 10) {
-	    c2[i] = '0' + offset;
-	} else {
-	    c2[i] = a + offset - 10;
-	}
+        offset = (byteval >> 4*(1-i)) & 0x0f;
+        if (offset < 10) {
+            c2[i] = '0' + offset;
+        } else {
+            c2[i] = a + offset - 10;
+        }
     }
     return SECSuccess;
 }
 
 void
 to_hex_str(char *str, const unsigned char *buf, unsigned int len)
 {
     unsigned int i;
     for (i=0; i<len; i++) {
-	byteval_to_hex(buf[i], &str[2*i], 'a');
+        byteval_to_hex(buf[i], &str[2*i], 'a');
     }
     str[2*len] = '\0';
 }
 
 void
 to_hex_str_cap(char *str, const unsigned char *buf, unsigned int len)
 {
     unsigned int i;
     for (i=0; i<len; i++) {
-	byteval_to_hex(buf[i], &str[2*i], 'A');
+        byteval_to_hex(buf[i], &str[2*i], 'A');
     }
     str[2*len] = '\0';
 }
 
 /*
  * Convert a string of hex digits (str) to an array (buf) of len bytes.
  * Return PR_TRUE if the hex string can fit in the byte array.  Return
  * PR_FALSE if the hex string is empty or is too long.
@@ -108,51 +123,51 @@ from_hex_str(unsigned char *buf, unsigne
 {
     unsigned int nxdigit;  /* number of hex digits in str */
     unsigned int i;  /* index into buf */
     unsigned int j;  /* index into str */
 
     /* count the hex digits */
     nxdigit = 0;
     for (nxdigit = 0; isxdigit(str[nxdigit]); nxdigit++) {
-	/* empty body */
+        /* empty body */
     }
     if (nxdigit == 0) {
-	return PR_FALSE;
+        return PR_FALSE;
     }
     if (nxdigit > 2*len) {
-	/*
-	 * The input hex string is too long, but we allow it if the
-	 * extra digits are leading 0's.
-	 */
-	for (j = 0; j < nxdigit-2*len; j++) {
-	    if (str[j] != '0') {
-		return PR_FALSE;
-	    }
-	}
-	/* skip leading 0's */
-	str += nxdigit-2*len;
-	nxdigit = 2*len;
+        /*
+         * The input hex string is too long, but we allow it if the
+         * extra digits are leading 0's.
+         */
+        for (j = 0; j < nxdigit-2*len; j++) {
+            if (str[j] != '0') {
+                return PR_FALSE;
+            }
+        }
+        /* skip leading 0's */
+        str += nxdigit-2*len;
+        nxdigit = 2*len;
     }
     for (i=0, j=0; i< len; i++) {
-	if (2*i < 2*len-nxdigit) {
-	    /* Handle a short input as if we padded it with leading 0's. */
-	    if (2*i+1 < 2*len-nxdigit) {
-		buf[i] = 0;
-	    } else {
-		char tmp[2];
-		tmp[0] = '0';
-		tmp[1] = str[j];
-		hex_to_byteval(tmp, &buf[i]);
-		j++;
-	    }
-	} else {
-	    hex_to_byteval(&str[j], &buf[i]);
-	    j += 2;
-	}
+        if (2*i < 2*len-nxdigit) {
+            /* Handle a short input as if we padded it with leading 0's. */
+            if (2*i+1 < 2*len-nxdigit) {
+                buf[i] = 0;
+            } else {
+                char tmp[2];
+                tmp[0] = '0';
+                tmp[1] = str[j];
+                hex_to_byteval(tmp, &buf[i]);
+                j++;
+            }
+        } else {
+            hex_to_byteval(&str[j], &buf[i]);
+            j += 2;
+        }
     }
     return PR_TRUE;
 }
 
 SECStatus
 tdea_encrypt_buf(
     int mode,
     const unsigned char *key, 
@@ -283,21 +298,21 @@ tdea_kat_mmt(char *reqfn)
 {
     char buf[180];      /* holds one line from the input REQUEST file.
                          * needs to be large enough to hold the longest
                          * line "CIPHERTEXT = <180 hex digits>\n".
                          */
     FILE *req;       /* input stream from the REQUEST file */
     FILE *resp;      /* output stream to the RESPONSE file */
     int i, j;
-    int mode;           /* NSS_DES_EDE3 (ECB) or NSS_DES_EDE3_CBC */
+    int mode = NSS_DES_EDE3;           /* NSS_DES_EDE3 (ECB) or NSS_DES_EDE3_CBC */
     int crypt = DECRYPT;    /* 1 means encrypt, 0 means decrypt */
     unsigned char key[24];              /* TDEA 3 key bundle */
     unsigned int numKeys = 0;
-    unsigned char iv[8];		/* for all modes except ECB */
+    unsigned char iv[8];                /* for all modes except ECB */
     unsigned char plaintext[8*20];     /* 1 to 20 blocks */
     unsigned int plaintextlen;
     unsigned char ciphertext[8*20];   /* 1 to 20 blocks */  
     unsigned int ciphertextlen;
     SECStatus rv;
 
     req = fopen(reqfn, "r");
     resp = stdout;
@@ -871,54 +886,54 @@ aes_encrypt_buf(
 {
     SECStatus rv = SECFailure;
     AESContext *cx;
     unsigned char doublecheck[10*16];  /* 1 to 10 blocks */
     unsigned int doublechecklen = 0;
 
     cx = AES_CreateContext(key, iv, mode, PR_TRUE, keysize, 16);
     if (cx == NULL) {
-	goto loser;
+        goto loser;
     }
     rv = AES_Encrypt(cx, output, outputlen, maxoutputlen, input, inputlen);
     if (rv != SECSuccess) {
-	goto loser;
+        goto loser;
     }
     if (*outputlen != inputlen) {
-	goto loser;
+        goto loser;
     }
     AES_DestroyContext(cx, PR_TRUE);
     cx = NULL;
 
     /*
      * Doublecheck our result by decrypting the ciphertext and
      * compare the output with the input plaintext.
      */
     cx = AES_CreateContext(key, iv, mode, PR_FALSE, keysize, 16);
     if (cx == NULL) {
-	goto loser;
+        goto loser;
     }
     rv = AES_Decrypt(cx, doublecheck, &doublechecklen, sizeof doublecheck,
-	output, *outputlen);
+        output, *outputlen);
     if (rv != SECSuccess) {
-	goto loser;
+        goto loser;
     }
     if (doublechecklen != *outputlen) {
-	goto loser;
+        goto loser;
     }
     AES_DestroyContext(cx, PR_TRUE);
     cx = NULL;
     if (memcmp(doublecheck, input, inputlen) != 0) {
-	goto loser;
+        goto loser;
     }
     rv = SECSuccess;
 
 loser:
     if (cx != NULL) {
-	AES_DestroyContext(cx, PR_TRUE);
+        AES_DestroyContext(cx, PR_TRUE);
     }
     return rv;
 }
 
 SECStatus
 aes_decrypt_buf(
     int mode,
     const unsigned char *key, unsigned int keysize,
@@ -928,58 +943,274 @@ aes_decrypt_buf(
 {
     SECStatus rv = SECFailure;
     AESContext *cx;
     unsigned char doublecheck[10*16];  /* 1 to 10 blocks */
     unsigned int doublechecklen = 0;
 
     cx = AES_CreateContext(key, iv, mode, PR_FALSE, keysize, 16);
     if (cx == NULL) {
-	goto loser;
+        goto loser;
     }
     rv = AES_Decrypt(cx, output, outputlen, maxoutputlen,
-	input, inputlen);
+        input, inputlen);
     if (rv != SECSuccess) {
-	goto loser;
+        goto loser;
     }
     if (*outputlen != inputlen) {
-	goto loser;
+        goto loser;
     }
     AES_DestroyContext(cx, PR_TRUE);
     cx = NULL;
 
     /*
      * Doublecheck our result by encrypting the plaintext and
      * compare the output with the input ciphertext.
      */
     cx = AES_CreateContext(key, iv, mode, PR_TRUE, keysize, 16);
     if (cx == NULL) {
-	goto loser;
+        goto loser;
     }
     rv = AES_Encrypt(cx, doublecheck, &doublechecklen, sizeof doublecheck,
-	output, *outputlen);
+        output, *outputlen);
     if (rv != SECSuccess) {
-	goto loser;
+        goto loser;
     }
     if (doublechecklen != *outputlen) {
-	goto loser;
+        goto loser;
     }
     AES_DestroyContext(cx, PR_TRUE);
     cx = NULL;
     if (memcmp(doublecheck, input, inputlen) != 0) {
-	goto loser;
+        goto loser;
     }
     rv = SECSuccess;
 
 loser:
     if (cx != NULL) {
-	AES_DestroyContext(cx, PR_TRUE);
+        AES_DestroyContext(cx, PR_TRUE);
     }
     return rv;
 }
+/*
+ * Perform the AES GCM tests.
+ *
+ * reqfn is the pathname of the REQUEST file.
+ *
+ * The output RESPONSE file is written to stdout.
+ */
+void
+aes_gcm(char *reqfn, int encrypt)
+{
+    char buf[512];      /* holds one line from the input REQUEST file.
+                         * needs to be large enough to hold the longest
+                         * line "CIPHERTEXT = <320 hex digits>\n".
+                         */
+    FILE *aesreq;       /* input stream from the REQUEST file */
+    FILE *aesresp;      /* output stream to the RESPONSE file */
+    int i, j;
+    unsigned char key[32];              /* 128, 192, or 256 bits */
+    unsigned int keysize = 0;
+    unsigned char iv[128];                /* handle large gcm IV's */
+    unsigned char plaintext[10*16];     /* 1 to 10 blocks */
+    unsigned int plaintextlen;
+    unsigned char ciphertext[11*16];    /* 1 to 10 blocks + tag */
+    unsigned int ciphertextlen;
+    unsigned char aad[11*16];            /* 1 to 10 blocks + tag */
+    unsigned int aadlen = 0;
+    unsigned int tagbits;
+    unsigned int taglen = 0;
+    unsigned int ivlen;
+    CK_GCM_PARAMS params;
+    SECStatus rv;
+
+    aesreq = fopen(reqfn, "r");
+    aesresp = stdout;
+    while (fgets(buf, sizeof buf, aesreq) != NULL) {
+        /* a comment or blank line */
+        if (buf[0] == '#' || buf[0] == '\n') {
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* [ENCRYPT] or [DECRYPT] */
+        if (buf[0] == '[') {
+            if (strncmp(buf, "[Taglen", 7)  == 0) {
+                if (sscanf(buf, "[Taglen = %d]", &tagbits) != 1) {
+                    goto loser;
+                }
+                taglen = tagbits/8;
+            } 
+            if (strncmp(buf, "[IVlen", 6)  == 0) {
+                if (sscanf(buf, "[IVlen = %d]", &ivlen) != 1) {
+                    goto loser;
+                }
+                ivlen=ivlen/8;
+            } 
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* "COUNT = x" begins a new data set */
+        if (strncmp(buf, "Count", 5) == 0) {
+            /* zeroize the variables for the test with this data set */
+            memset(key, 0, sizeof key);
+            keysize = 0;
+            memset(iv, 0, sizeof iv);
+            memset(plaintext, 0, sizeof plaintext);
+            plaintextlen = 0;
+            memset(ciphertext, 0, sizeof ciphertext);
+            ciphertextlen = 0;
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* KEY = ... */
+        if (strncmp(buf, "Key", 3) == 0) {
+            i = 3;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &key[j]);
+            }
+            keysize = j;
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* IV = ... */
+        if (strncmp(buf, "IV", 2) == 0) {
+            i = 2;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<sizeof iv; i+=2,j++) {
+                hex_to_byteval(&buf[i], &iv[j]);
+            }
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* PLAINTEXT = ... */
+        if (strncmp(buf, "PT", 2) == 0) {
+            /* sanity check */
+            if (!encrypt) {
+                goto loser;
+            }
+
+            i = 2;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &plaintext[j]);
+            }
+            plaintextlen = j;
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* CIPHERTEXT = ... */
+        if (strncmp(buf, "CT", 2) == 0) {
+            /* sanity check */
+            if (encrypt) {
+                goto loser;
+            }
+
+            i = 2;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &ciphertext[j]);
+            }
+            ciphertextlen = j;
+            fputs(buf, aesresp);
+            continue;
+        }
+        if (strncmp(buf, "AAD", 3) == 0) {
+            i = 3;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &aad[j]);
+            }
+            aadlen = j;
+            fputs(buf, aesresp);
+            if (encrypt) {
+                if (encrypt == 2) {
+                    rv = RNG_GenerateGlobalRandomBytes(iv, ivlen);
+                    if (rv != SECSuccess) {
+                        goto loser;
+                    }
+                }
+                params.pIv = iv;
+                params.ulIvLen = ivlen;
+                params.pAAD = aad;
+                params.ulAADLen = aadlen;
+                params.ulTagBits = tagbits;
+                rv = aes_encrypt_buf(NSS_AES_GCM, key, keysize,
+                (unsigned char *)&params,
+                ciphertext, &ciphertextlen, sizeof ciphertext,
+                plaintext, plaintextlen);
+                if (rv != SECSuccess) {
+                    goto loser;
+                }
+
+		if (encrypt == 2) {
+                    fputs("IV = ", aesresp);
+                    to_hex_str(buf, iv, ivlen);
+                    fputs(buf, aesresp);
+                    fputc('\n', aesresp);
+		}
+                fputs("CT = ", aesresp);
+                j = ciphertextlen-taglen;
+                to_hex_str(buf, ciphertext, j);
+                fputs(buf, aesresp);
+                fputs("\nTag = ", aesresp);
+                to_hex_str(buf, ciphertext+j, taglen);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+            }
+            continue;
+        }
+        if (strncmp(buf, "Tag", 3) == 0) {
+            /* sanity check */
+            if (encrypt) {
+                goto loser;
+            }
+
+            i = 3;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &ciphertext[j+ciphertextlen]);
+            }
+            ciphertextlen += j;
+            params.pIv = iv;
+            params.ulIvLen = ivlen;
+            params.pAAD = aad;
+            params.ulAADLen = aadlen;
+            params.ulTagBits = tagbits;
+            rv = aes_decrypt_buf(NSS_AES_GCM, key, keysize,
+                (unsigned char *)&params,
+                plaintext, &plaintextlen, sizeof plaintext,
+                ciphertext, ciphertextlen);
+            fputs(buf, aesresp);
+            if (rv != SECSuccess) {
+                fprintf(aesresp,"FAIL\n");
+            } else {
+                fputs("PT = ", aesresp);
+                to_hex_str(buf, plaintext, plaintextlen);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+            }
+            continue;
+        }
+    }
+loser:
+    fclose(aesreq);
+}
 
 /*
  * Perform the AES Known Answer Test (KAT) or Multi-block Message
  * Test (MMT) in ECB or CBC mode.  The KAT (there are four types)
  * and MMT have the same structure: given the key and IV (CBC mode
  * only), encrypt the given plaintext or decrypt the given ciphertext.
  * So we can handle them the same way.
  *
@@ -992,147 +1223,147 @@ aes_kat_mmt(char *reqfn)
 {
     char buf[512];      /* holds one line from the input REQUEST file.
                          * needs to be large enough to hold the longest
                          * line "CIPHERTEXT = <320 hex digits>\n".
                          */
     FILE *aesreq;       /* input stream from the REQUEST file */
     FILE *aesresp;      /* output stream to the RESPONSE file */
     int i, j;
-    int mode;           /* NSS_AES (ECB) or NSS_AES_CBC */
+    int mode = NSS_AES;           /* NSS_AES (ECB) or NSS_AES_CBC */
     int encrypt = 0;    /* 1 means encrypt, 0 means decrypt */
     unsigned char key[32];              /* 128, 192, or 256 bits */
-    unsigned int keysize;
-    unsigned char iv[16];		/* for all modes except ECB */
+    unsigned int keysize = 0;
+    unsigned char iv[16];                /* for all modes except ECB */
     unsigned char plaintext[10*16];     /* 1 to 10 blocks */
     unsigned int plaintextlen;
     unsigned char ciphertext[10*16];    /* 1 to 10 blocks */
     unsigned int ciphertextlen;
     SECStatus rv;
 
     aesreq = fopen(reqfn, "r");
     aesresp = stdout;
     while (fgets(buf, sizeof buf, aesreq) != NULL) {
-	/* a comment or blank line */
-	if (buf[0] == '#' || buf[0] == '\n') {
-	    fputs(buf, aesresp);
-	    continue;
-	}
-	/* [ENCRYPT] or [DECRYPT] */
-	if (buf[0] == '[') {
-	    if (strncmp(&buf[1], "ENCRYPT", 7) == 0) {
-		encrypt = 1;
-	    } else {
-		encrypt = 0;
-	    }
-	    fputs(buf, aesresp);
-	    continue;
-	}
-	/* "COUNT = x" begins a new data set */
-	if (strncmp(buf, "COUNT", 5) == 0) {
-	    mode = NSS_AES;
-	    /* zeroize the variables for the test with this data set */
-	    memset(key, 0, sizeof key);
-	    keysize = 0;
-	    memset(iv, 0, sizeof iv);
-	    memset(plaintext, 0, sizeof plaintext);
-	    plaintextlen = 0;
-	    memset(ciphertext, 0, sizeof ciphertext);
-	    ciphertextlen = 0;
-	    fputs(buf, aesresp);
-	    continue;
-	}
-	/* KEY = ... */
-	if (strncmp(buf, "KEY", 3) == 0) {
-	    i = 3;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; isxdigit(buf[i]); i+=2,j++) {
-		hex_to_byteval(&buf[i], &key[j]);
-	    }
-	    keysize = j;
-	    fputs(buf, aesresp);
-	    continue;
-	}
-	/* IV = ... */
-	if (strncmp(buf, "IV", 2) == 0) {
-	    mode = NSS_AES_CBC;
-	    i = 2;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; j<sizeof iv; i+=2,j++) {
-		hex_to_byteval(&buf[i], &iv[j]);
-	    }
-	    fputs(buf, aesresp);
-	    continue;
-	}
-	/* PLAINTEXT = ... */
-	if (strncmp(buf, "PLAINTEXT", 9) == 0) {
-	    /* sanity check */
-	    if (!encrypt) {
-		goto loser;
-	    }
-
-	    i = 9;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; isxdigit(buf[i]); i+=2,j++) {
-		hex_to_byteval(&buf[i], &plaintext[j]);
-	    }
-	    plaintextlen = j;
-
-	    rv = aes_encrypt_buf(mode, key, keysize,
-		(mode == NSS_AES) ? NULL : iv,
-		ciphertext, &ciphertextlen, sizeof ciphertext,
-		plaintext, plaintextlen);
-	    if (rv != SECSuccess) {
-		goto loser;
-	    }
-
-	    fputs(buf, aesresp);
-	    fputs("CIPHERTEXT = ", aesresp);
-	    to_hex_str(buf, ciphertext, ciphertextlen);
-	    fputs(buf, aesresp);
-	    fputc('\n', aesresp);
-	    continue;
-	}
-	/* CIPHERTEXT = ... */
-	if (strncmp(buf, "CIPHERTEXT", 10) == 0) {
-	    /* sanity check */
-	    if (encrypt) {
-		goto loser;
-	    }
-
-	    i = 10;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; isxdigit(buf[i]); i+=2,j++) {
-		hex_to_byteval(&buf[i], &ciphertext[j]);
-	    }
-	    ciphertextlen = j;
-
-	    rv = aes_decrypt_buf(mode, key, keysize,
-		(mode == NSS_AES) ? NULL : iv,
-		plaintext, &plaintextlen, sizeof plaintext,
-		ciphertext, ciphertextlen);
-	    if (rv != SECSuccess) {
-		goto loser;
-	    }
-
-	    fputs(buf, aesresp);
-	    fputs("PLAINTEXT = ", aesresp);
-	    to_hex_str(buf, plaintext, plaintextlen);
-	    fputs(buf, aesresp);
-	    fputc('\n', aesresp);
-	    continue;
-	}
+        /* a comment or blank line */
+        if (buf[0] == '#' || buf[0] == '\n') {
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* [ENCRYPT] or [DECRYPT] */
+        if (buf[0] == '[') {
+            if (strncmp(&buf[1], "ENCRYPT", 7) == 0) {
+                encrypt = 1;
+            } else {
+                encrypt = 0;
+            }
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* "COUNT = x" begins a new data set */
+        if (strncmp(buf, "COUNT", 5) == 0) {
+            mode = NSS_AES;
+            /* zeroize the variables for the test with this data set */
+            memset(key, 0, sizeof key);
+            keysize = 0;
+            memset(iv, 0, sizeof iv);
+            memset(plaintext, 0, sizeof plaintext);
+            plaintextlen = 0;
+            memset(ciphertext, 0, sizeof ciphertext);
+            ciphertextlen = 0;
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* KEY = ... */
+        if (strncmp(buf, "KEY", 3) == 0) {
+            i = 3;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &key[j]);
+            }
+            keysize = j;
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* IV = ... */
+        if (strncmp(buf, "IV", 2) == 0) {
+            mode = NSS_AES_CBC;
+            i = 2;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<sizeof iv; i+=2,j++) {
+                hex_to_byteval(&buf[i], &iv[j]);
+            }
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* PLAINTEXT = ... */
+        if (strncmp(buf, "PLAINTEXT", 9) == 0) {
+            /* sanity check */
+            if (!encrypt) {
+                goto loser;
+            }
+
+            i = 9;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &plaintext[j]);
+            }
+            plaintextlen = j;
+
+            rv = aes_encrypt_buf(mode, key, keysize,
+                (mode == NSS_AES) ? NULL : iv,
+                ciphertext, &ciphertextlen, sizeof ciphertext,
+                plaintext, plaintextlen);
+            if (rv != SECSuccess) {
+                goto loser;
+            }
+
+            fputs(buf, aesresp);
+            fputs("CIPHERTEXT = ", aesresp);
+            to_hex_str(buf, ciphertext, ciphertextlen);
+            fputs(buf, aesresp);
+            fputc('\n', aesresp);
+            continue;
+        }
+        /* CIPHERTEXT = ... */
+        if (strncmp(buf, "CIPHERTEXT", 10) == 0) {
+            /* sanity check */
+            if (encrypt) {
+                goto loser;
+            }
+
+            i = 10;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &ciphertext[j]);
+            }
+            ciphertextlen = j;
+
+            rv = aes_decrypt_buf(mode, key, keysize,
+                (mode == NSS_AES) ? NULL : iv,
+                plaintext, &plaintextlen, sizeof plaintext,
+                ciphertext, ciphertextlen);
+            if (rv != SECSuccess) {
+                goto loser;
+            }
+
+            fputs(buf, aesresp);
+            fputs("PLAINTEXT = ", aesresp);
+            to_hex_str(buf, plaintext, plaintextlen);
+            fputs(buf, aesresp);
+            fputc('\n', aesresp);
+            continue;
+        }
     }
 loser:
     fclose(aesreq);
 }
 
 /*
  * Generate Key[i+1] from Key[i], CT[j-1], and CT[j] for AES Monte Carlo
  * Test (MCT) in ECB and CBC modes.
@@ -1140,42 +1371,42 @@ loser:
 void
 aes_mct_next_key(unsigned char *key, unsigned int keysize,
     const unsigned char *ciphertext_1, const unsigned char *ciphertext)
 {
     int k;
 
     switch (keysize) {
     case 16:  /* 128-bit key */
-	/* Key[i+1] = Key[i] xor CT[j] */
-	for (k=0; k<16; k++) {
-	    key[k] ^= ciphertext[k];
-	}
-	break;
+        /* Key[i+1] = Key[i] xor CT[j] */
+        for (k=0; k<16; k++) {
+            key[k] ^= ciphertext[k];
+        }
+        break;
     case 24:  /* 192-bit key */
-	/*
-	 * Key[i+1] = Key[i] xor (last 64-bits of
-	 *            CT[j-1] || CT[j])
-	 */
-	for (k=0; k<8; k++) {
-	    key[k] ^= ciphertext_1[k+8];
-	}
-	for (k=8; k<24; k++) {
-	    key[k] ^= ciphertext[k-8];
-	}
-	break;
+        /*
+         * Key[i+1] = Key[i] xor (last 64-bits of
+         *            CT[j-1] || CT[j])
+         */
+        for (k=0; k<8; k++) {
+            key[k] ^= ciphertext_1[k+8];
+        }
+        for (k=8; k<24; k++) {
+            key[k] ^= ciphertext[k-8];
+        }
+        break;
     case 32:  /* 256-bit key */
-	/* Key[i+1] = Key[i] xor (CT[j-1] || CT[j]) */
-	for (k=0; k<16; k++) {
-	    key[k] ^= ciphertext_1[k];
-	}
-	for (k=16; k<32; k++) {
-	    key[k] ^= ciphertext[k-16];
-	}
-	break;
+        /* Key[i+1] = Key[i] xor (CT[j-1] || CT[j]) */
+        for (k=0; k<16; k++) {
+            key[k] ^= ciphertext_1[k];
+        }
+        for (k=16; k<32; k++) {
+            key[k] ^= ciphertext[k-16];
+        }
+        break;
     }
 }
 
 /*
  * Perform the AES Monte Carlo Test (MCT) in ECB mode.  MCT exercises
  * our AES code in streaming mode because the plaintext or ciphertext
  * is generated block by block as we go, so we can't collect all the
  * plaintext or ciphertext in one buffer and encrypt or decrypt it in
@@ -1192,272 +1423,272 @@ aes_ecb_mct(char *reqfn)
                          * needs to be large enough to hold the longest
                          * line "KEY = <64 hex digits>\n".
                          */
     FILE *aesreq;       /* input stream from the REQUEST file */
     FILE *aesresp;      /* output stream to the RESPONSE file */
     int i, j;
     int encrypt = 0;    /* 1 means encrypt, 0 means decrypt */
     unsigned char key[32];              /* 128, 192, or 256 bits */
-    unsigned int keysize;
+    unsigned int keysize = 0;
     unsigned char plaintext[16];        /* PT[j] */
     unsigned char plaintext_1[16];      /* PT[j-1] */
     unsigned char ciphertext[16];       /* CT[j] */
     unsigned char ciphertext_1[16];     /* CT[j-1] */
     unsigned char doublecheck[16];
     unsigned int outputlen;
-    AESContext *cx = NULL;	/* the operation being tested */
+    AESContext *cx = NULL;        /* the operation being tested */
     AESContext *cx2 = NULL;     /* the inverse operation done in parallel
                                  * to doublecheck our result.
                                  */
     SECStatus rv;
 
     aesreq = fopen(reqfn, "r");
     aesresp = stdout;
     while (fgets(buf, sizeof buf, aesreq) != NULL) {
-	/* a comment or blank line */
-	if (buf[0] == '#' || buf[0] == '\n') {
-	    fputs(buf, aesresp);
-	    continue;
-	}
-	/* [ENCRYPT] or [DECRYPT] */
-	if (buf[0] == '[') {
-	    if (strncmp(&buf[1], "ENCRYPT", 7) == 0) {
-		encrypt = 1;
-	    } else {
-		encrypt = 0;
-	    }
-	    fputs(buf, aesresp);
-	    continue;
-	}
-	/* "COUNT = x" begins a new data set */
-	if (strncmp(buf, "COUNT", 5) == 0) {
-	    /* zeroize the variables for the test with this data set */
-	    memset(key, 0, sizeof key);
-	    keysize = 0;
-	    memset(plaintext, 0, sizeof plaintext);
-	    memset(ciphertext, 0, sizeof ciphertext);
-	    continue;
-	}
-	/* KEY = ... */
-	if (strncmp(buf, "KEY", 3) == 0) {
-	    /* Key[0] = Key */
-	    i = 3;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; isxdigit(buf[i]); i+=2,j++) {
-		hex_to_byteval(&buf[i], &key[j]);
-	    }
-	    keysize = j;
-	    continue;
-	}
-	/* PLAINTEXT = ... */
-	if (strncmp(buf, "PLAINTEXT", 9) == 0) {
-	    /* sanity check */
-	    if (!encrypt) {
-		goto loser;
-	    }
-	    /* PT[0] = PT */
-	    i = 9;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; j<sizeof plaintext; i+=2,j++) {
-		hex_to_byteval(&buf[i], &plaintext[j]);
-	    }
-
-	    for (i=0; i<100; i++) {
-		sprintf(buf, "COUNT = %d\n", i);
-	        fputs(buf, aesresp);
-		/* Output Key[i] */
-		fputs("KEY = ", aesresp);
-		to_hex_str(buf, key, keysize);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-		/* Output PT[0] */
-		fputs("PLAINTEXT = ", aesresp);
-		to_hex_str(buf, plaintext, sizeof plaintext);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-
-		cx = AES_CreateContext(key, NULL, NSS_AES,
-		    PR_TRUE, keysize, 16);
-		if (cx == NULL) {
-		    goto loser;
-		}
-		/*
-		 * doublecheck our result by decrypting the result
-		 * and comparing the output with the plaintext.
-		 */
-		cx2 = AES_CreateContext(key, NULL, NSS_AES,
-		    PR_FALSE, keysize, 16);
-		if (cx2 == NULL) {
-		    goto loser;
-		}
-		for (j=0; j<1000; j++) {
-		    /* Save CT[j-1] */
-		    memcpy(ciphertext_1, ciphertext, sizeof ciphertext);
-
-		    /* CT[j] = AES(Key[i], PT[j]) */
-		    outputlen = 0;
-		    rv = AES_Encrypt(cx,
-			ciphertext, &outputlen, sizeof ciphertext,
-			plaintext, sizeof plaintext);
-		    if (rv != SECSuccess) {
-			goto loser;
-		    }
-		    if (outputlen != sizeof plaintext) {
-			goto loser;
-		    }
-
-		    /* doublecheck our result */
-		    outputlen = 0;
-		    rv = AES_Decrypt(cx2,
-			doublecheck, &outputlen, sizeof doublecheck,
-			ciphertext, sizeof ciphertext);
-		    if (rv != SECSuccess) {
-			goto loser;
-		    }
-		    if (outputlen != sizeof ciphertext) {
-			goto loser;
-		    }
-		    if (memcmp(doublecheck, plaintext, sizeof plaintext)) {
-			goto loser;
-		    }
-
-		    /* PT[j+1] = CT[j] */
-		    memcpy(plaintext, ciphertext, sizeof plaintext);
-		}
-		AES_DestroyContext(cx, PR_TRUE);
-		cx = NULL;
-		AES_DestroyContext(cx2, PR_TRUE);
-		cx2 = NULL;
-
-		/* Output CT[j] */
-		fputs("CIPHERTEXT = ", aesresp);
-		to_hex_str(buf, ciphertext, sizeof ciphertext);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-
-		/* Key[i+1] = Key[i] xor ... */
-		aes_mct_next_key(key, keysize, ciphertext_1, ciphertext);
-		/* PT[0] = CT[j] */
-		/* done at the end of the for(j) loop */
-
-		fputc('\n', aesresp);
-	    }
-
-	    continue;
-	}
-	/* CIPHERTEXT = ... */
-	if (strncmp(buf, "CIPHERTEXT", 10) == 0) {
-	    /* sanity check */
-	    if (encrypt) {
-		goto loser;
-	    }
-	    /* CT[0] = CT */
-	    i = 10;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; isxdigit(buf[i]); i+=2,j++) {
-		hex_to_byteval(&buf[i], &ciphertext[j]);
-	    }
-
-	    for (i=0; i<100; i++) {
-		sprintf(buf, "COUNT = %d\n", i);
-	        fputs(buf, aesresp);
-		/* Output Key[i] */
-		fputs("KEY = ", aesresp);
-		to_hex_str(buf, key, keysize);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-		/* Output CT[0] */
-		fputs("CIPHERTEXT = ", aesresp);
-		to_hex_str(buf, ciphertext, sizeof ciphertext);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-
-		cx = AES_CreateContext(key, NULL, NSS_AES,
-		    PR_FALSE, keysize, 16);
-		if (cx == NULL) {
-		    goto loser;
-		}
-		/*
-		 * doublecheck our result by encrypting the result
-		 * and comparing the output with the ciphertext.
-		 */
-		cx2 = AES_CreateContext(key, NULL, NSS_AES,
-		    PR_TRUE, keysize, 16);
-		if (cx2 == NULL) {
-		    goto loser;
-		}
-		for (j=0; j<1000; j++) {
-		    /* Save PT[j-1] */
-		    memcpy(plaintext_1, plaintext, sizeof plaintext);
-
-		    /* PT[j] = AES(Key[i], CT[j]) */
-		    outputlen = 0;
-		    rv = AES_Decrypt(cx,
-			plaintext, &outputlen, sizeof plaintext,
-			ciphertext, sizeof ciphertext);
-		    if (rv != SECSuccess) {
-			goto loser;
-		    }
-		    if (outputlen != sizeof ciphertext) {
-			goto loser;
-		    }
-
-		    /* doublecheck our result */
-		    outputlen = 0;
-		    rv = AES_Encrypt(cx2,
-			doublecheck, &outputlen, sizeof doublecheck,
-			plaintext, sizeof plaintext);
-		    if (rv != SECSuccess) {
-			goto loser;
-		    }
-		    if (outputlen != sizeof plaintext) {
-			goto loser;
-		    }
-		    if (memcmp(doublecheck, ciphertext, sizeof ciphertext)) {
-			goto loser;
-		    }
-
-		    /* CT[j+1] = PT[j] */
-		    memcpy(ciphertext, plaintext, sizeof ciphertext);
-		}
-		AES_DestroyContext(cx, PR_TRUE);
-		cx = NULL;
-		AES_DestroyContext(cx2, PR_TRUE);
-		cx2 = NULL;
-
-		/* Output PT[j] */
-		fputs("PLAINTEXT = ", aesresp);
-		to_hex_str(buf, plaintext, sizeof plaintext);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-
-		/* Key[i+1] = Key[i] xor ... */
-		aes_mct_next_key(key, keysize, plaintext_1, plaintext);
-		/* CT[0] = PT[j] */
-		/* done at the end of the for(j) loop */
-
-		fputc('\n', aesresp);
-	    }
-
-	    continue;
-	}
+        /* a comment or blank line */
+        if (buf[0] == '#' || buf[0] == '\n') {
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* [ENCRYPT] or [DECRYPT] */
+        if (buf[0] == '[') {
+            if (strncmp(&buf[1], "ENCRYPT", 7) == 0) {
+                encrypt = 1;
+            } else {
+                encrypt = 0;
+            }
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* "COUNT = x" begins a new data set */
+        if (strncmp(buf, "COUNT", 5) == 0) {
+            /* zeroize the variables for the test with this data set */
+            memset(key, 0, sizeof key);
+            keysize = 0;
+            memset(plaintext, 0, sizeof plaintext);
+            memset(ciphertext, 0, sizeof ciphertext);
+            continue;
+        }
+        /* KEY = ... */
+        if (strncmp(buf, "KEY", 3) == 0) {
+            /* Key[0] = Key */
+            i = 3;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &key[j]);
+            }
+            keysize = j;
+            continue;
+        }
+        /* PLAINTEXT = ... */
+        if (strncmp(buf, "PLAINTEXT", 9) == 0) {
+            /* sanity check */
+            if (!encrypt) {
+                goto loser;
+            }
+            /* PT[0] = PT */
+            i = 9;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<sizeof plaintext; i+=2,j++) {
+                hex_to_byteval(&buf[i], &plaintext[j]);
+            }
+
+            for (i=0; i<100; i++) {
+                sprintf(buf, "COUNT = %d\n", i);
+                fputs(buf, aesresp);
+                /* Output Key[i] */
+                fputs("KEY = ", aesresp);
+                to_hex_str(buf, key, keysize);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+                /* Output PT[0] */
+                fputs("PLAINTEXT = ", aesresp);
+                to_hex_str(buf, plaintext, sizeof plaintext);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+
+                cx = AES_CreateContext(key, NULL, NSS_AES,
+                    PR_TRUE, keysize, 16);
+                if (cx == NULL) {
+                    goto loser;
+                }
+                /*
+                 * doublecheck our result by decrypting the result
+                 * and comparing the output with the plaintext.
+                 */
+                cx2 = AES_CreateContext(key, NULL, NSS_AES,
+                    PR_FALSE, keysize, 16);
+                if (cx2 == NULL) {
+                    goto loser;
+                }
+                for (j=0; j<1000; j++) {
+                    /* Save CT[j-1] */
+                    memcpy(ciphertext_1, ciphertext, sizeof ciphertext);
+
+                    /* CT[j] = AES(Key[i], PT[j]) */
+                    outputlen = 0;
+                    rv = AES_Encrypt(cx,
+                        ciphertext, &outputlen, sizeof ciphertext,
+                        plaintext, sizeof plaintext);
+                    if (rv != SECSuccess) {
+                        goto loser;
+                    }
+                    if (outputlen != sizeof plaintext) {
+                        goto loser;
+                    }
+
+                    /* doublecheck our result */
+                    outputlen = 0;
+                    rv = AES_Decrypt(cx2,
+                        doublecheck, &outputlen, sizeof doublecheck,
+                        ciphertext, sizeof ciphertext);
+                    if (rv != SECSuccess) {
+                        goto loser;
+                    }
+                    if (outputlen != sizeof ciphertext) {
+                        goto loser;
+                    }
+                    if (memcmp(doublecheck, plaintext, sizeof plaintext)) {
+                        goto loser;
+                    }
+
+                    /* PT[j+1] = CT[j] */
+                    memcpy(plaintext, ciphertext, sizeof plaintext);
+                }
+                AES_DestroyContext(cx, PR_TRUE);
+                cx = NULL;
+                AES_DestroyContext(cx2, PR_TRUE);
+                cx2 = NULL;
+
+                /* Output CT[j] */
+                fputs("CIPHERTEXT = ", aesresp);
+                to_hex_str(buf, ciphertext, sizeof ciphertext);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+
+                /* Key[i+1] = Key[i] xor ... */
+                aes_mct_next_key(key, keysize, ciphertext_1, ciphertext);
+                /* PT[0] = CT[j] */
+                /* done at the end of the for(j) loop */
+
+                fputc('\n', aesresp);
+            }
+
+            continue;
+        }
+        /* CIPHERTEXT = ... */
+        if (strncmp(buf, "CIPHERTEXT", 10) == 0) {
+            /* sanity check */
+            if (encrypt) {
+                goto loser;
+            }
+            /* CT[0] = CT */
+            i = 10;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &ciphertext[j]);
+            }
+
+            for (i=0; i<100; i++) {
+                sprintf(buf, "COUNT = %d\n", i);
+                fputs(buf, aesresp);
+                /* Output Key[i] */
+                fputs("KEY = ", aesresp);
+                to_hex_str(buf, key, keysize);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+                /* Output CT[0] */
+                fputs("CIPHERTEXT = ", aesresp);
+                to_hex_str(buf, ciphertext, sizeof ciphertext);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+
+                cx = AES_CreateContext(key, NULL, NSS_AES,
+                    PR_FALSE, keysize, 16);
+                if (cx == NULL) {
+                    goto loser;
+                }
+                /*
+                 * doublecheck our result by encrypting the result
+                 * and comparing the output with the ciphertext.
+                 */
+                cx2 = AES_CreateContext(key, NULL, NSS_AES,
+                    PR_TRUE, keysize, 16);
+                if (cx2 == NULL) {
+                    goto loser;
+                }
+                for (j=0; j<1000; j++) {
+                    /* Save PT[j-1] */
+                    memcpy(plaintext_1, plaintext, sizeof plaintext);
+
+                    /* PT[j] = AES(Key[i], CT[j]) */
+                    outputlen = 0;
+                    rv = AES_Decrypt(cx,
+                        plaintext, &outputlen, sizeof plaintext,
+                        ciphertext, sizeof ciphertext);
+                    if (rv != SECSuccess) {
+                        goto loser;
+                    }
+                    if (outputlen != sizeof ciphertext) {
+                        goto loser;
+                    }
+
+                    /* doublecheck our result */
+                    outputlen = 0;
+                    rv = AES_Encrypt(cx2,
+                        doublecheck, &outputlen, sizeof doublecheck,
+                        plaintext, sizeof plaintext);
+                    if (rv != SECSuccess) {
+                        goto loser;
+                    }
+                    if (outputlen != sizeof plaintext) {
+                        goto loser;
+                    }
+                    if (memcmp(doublecheck, ciphertext, sizeof ciphertext)) {
+                        goto loser;
+                    }
+
+                    /* CT[j+1] = PT[j] */
+                    memcpy(ciphertext, plaintext, sizeof ciphertext);
+                }
+                AES_DestroyContext(cx, PR_TRUE);
+                cx = NULL;
+                AES_DestroyContext(cx2, PR_TRUE);
+                cx2 = NULL;
+
+                /* Output PT[j] */
+                fputs("PLAINTEXT = ", aesresp);
+                to_hex_str(buf, plaintext, sizeof plaintext);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+
+                /* Key[i+1] = Key[i] xor ... */
+                aes_mct_next_key(key, keysize, plaintext_1, plaintext);
+                /* CT[0] = PT[j] */
+                /* done at the end of the for(j) loop */
+
+                fputc('\n', aesresp);
+            }
+
+            continue;
+        }
     }
 loser:
     if (cx != NULL) {
-	AES_DestroyContext(cx, PR_TRUE);
+        AES_DestroyContext(cx, PR_TRUE);
     }
     if (cx2 != NULL) {
-	AES_DestroyContext(cx2, PR_TRUE);
+        AES_DestroyContext(cx2, PR_TRUE);
     }
     fclose(aesreq);
 }
 
 /*
  * Perform the AES Monte Carlo Test (MCT) in CBC mode.  MCT exercises
  * our AES code in streaming mode because the plaintext or ciphertext
  * is generated block by block as we go, so we can't collect all the
@@ -1475,380 +1706,380 @@ aes_cbc_mct(char *reqfn)
                          * needs to be large enough to hold the longest
                          * line "KEY = <64 hex digits>\n".
                          */
     FILE *aesreq;       /* input stream from the REQUEST file */
     FILE *aesresp;      /* output stream to the RESPONSE file */
     int i, j;
     int encrypt = 0;    /* 1 means encrypt, 0 means decrypt */
     unsigned char key[32];              /* 128, 192, or 256 bits */
-    unsigned int keysize;
+    unsigned int keysize = 0;
     unsigned char iv[16];
     unsigned char plaintext[16];        /* PT[j] */
     unsigned char plaintext_1[16];      /* PT[j-1] */
     unsigned char ciphertext[16];       /* CT[j] */
     unsigned char ciphertext_1[16];     /* CT[j-1] */
     unsigned char doublecheck[16];
     unsigned int outputlen;
-    AESContext *cx = NULL;	/* the operation being tested */
+    AESContext *cx = NULL;        /* the operation being tested */
     AESContext *cx2 = NULL;     /* the inverse operation done in parallel
                                  * to doublecheck our result.
                                  */
     SECStatus rv;
 
     aesreq = fopen(reqfn, "r");
     aesresp = stdout;
     while (fgets(buf, sizeof buf, aesreq) != NULL) {
-	/* a comment or blank line */
-	if (buf[0] == '#' || buf[0] == '\n') {
-	    fputs(buf, aesresp);
-	    continue;
-	}
-	/* [ENCRYPT] or [DECRYPT] */
-	if (buf[0] == '[') {
-	    if (strncmp(&buf[1], "ENCRYPT", 7) == 0) {
-		encrypt = 1;
-	    } else {
-		encrypt = 0;
-	    }
-	    fputs(buf, aesresp);
-	    continue;
-	}
-	/* "COUNT = x" begins a new data set */
-	if (strncmp(buf, "COUNT", 5) == 0) {
-	    /* zeroize the variables for the test with this data set */
-	    memset(key, 0, sizeof key);
-	    keysize = 0;
-	    memset(iv, 0, sizeof iv);
-	    memset(plaintext, 0, sizeof plaintext);
-	    memset(ciphertext, 0, sizeof ciphertext);
-	    continue;
-	}
-	/* KEY = ... */
-	if (strncmp(buf, "KEY", 3) == 0) {
-	    /* Key[0] = Key */
-	    i = 3;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; isxdigit(buf[i]); i+=2,j++) {
-		hex_to_byteval(&buf[i], &key[j]);
-	    }
-	    keysize = j;
-	    continue;
-	}
-	/* IV = ... */
-	if (strncmp(buf, "IV", 2) == 0) {
-	    /* IV[0] = IV */
-	    i = 2;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; j<sizeof iv; i+=2,j++) {
-		hex_to_byteval(&buf[i], &iv[j]);
-	    }
-	    continue;
-	}
-	/* PLAINTEXT = ... */
-	if (strncmp(buf, "PLAINTEXT", 9) == 0) {
-	    /* sanity check */
-	    if (!encrypt) {
-		goto loser;
-	    }
-	    /* PT[0] = PT */
-	    i = 9;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; j<sizeof plaintext; i+=2,j++) {
-		hex_to_byteval(&buf[i], &plaintext[j]);
-	    }
-
-	    for (i=0; i<100; i++) {
-		sprintf(buf, "COUNT = %d\n", i);
-	        fputs(buf, aesresp);
-		/* Output Key[i] */
-		fputs("KEY = ", aesresp);
-		to_hex_str(buf, key, keysize);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-		/* Output IV[i] */
-		fputs("IV = ", aesresp);
-		to_hex_str(buf, iv, sizeof iv);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-		/* Output PT[0] */
-		fputs("PLAINTEXT = ", aesresp);
-		to_hex_str(buf, plaintext, sizeof plaintext);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-
-		cx = AES_CreateContext(key, iv, NSS_AES_CBC,
-		    PR_TRUE, keysize, 16);
-		if (cx == NULL) {
-		    goto loser;
-		}
-		/*
-		 * doublecheck our result by decrypting the result
-		 * and comparing the output with the plaintext.
-		 */
-		cx2 = AES_CreateContext(key, iv, NSS_AES_CBC,
-		    PR_FALSE, keysize, 16);
-		if (cx2 == NULL) {
-		    goto loser;
-		}
-		/* CT[-1] = IV[i] */
-		memcpy(ciphertext, iv, sizeof ciphertext);
-		for (j=0; j<1000; j++) {
-		    /* Save CT[j-1] */
-		    memcpy(ciphertext_1, ciphertext, sizeof ciphertext);
-		    /*
-		     * If ( j=0 )
-		     *      CT[j] = AES(Key[i], IV[i], PT[j])
-		     *      PT[j+1] = IV[i] (= CT[j-1])
-		     * Else
-		     *      CT[j] = AES(Key[i], PT[j])
-		     *      PT[j+1] = CT[j-1]
-		     */
-		    outputlen = 0;
-		    rv = AES_Encrypt(cx,
-			ciphertext, &outputlen, sizeof ciphertext,
-			plaintext, sizeof plaintext);
-		    if (rv != SECSuccess) {
-			goto loser;
-		    }
-		    if (outputlen != sizeof plaintext) {
-			goto loser;
-		    }
-
-		    /* doublecheck our result */
-		    outputlen = 0;
-		    rv = AES_Decrypt(cx2,
-			doublecheck, &outputlen, sizeof doublecheck,
-			ciphertext, sizeof ciphertext);
-		    if (rv != SECSuccess) {
-			goto loser;
-		    }
-		    if (outputlen != sizeof ciphertext) {
-			goto loser;
-		    }
-		    if (memcmp(doublecheck, plaintext, sizeof plaintext)) {
-			goto loser;
-		    }
-
-		    memcpy(plaintext, ciphertext_1, sizeof plaintext);
-		}
-		AES_DestroyContext(cx, PR_TRUE);
-		cx = NULL;
-		AES_DestroyContext(cx2, PR_TRUE);
-		cx2 = NULL;
-
-		/* Output CT[j] */
-		fputs("CIPHERTEXT = ", aesresp);
-		to_hex_str(buf, ciphertext, sizeof ciphertext);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-
-		/* Key[i+1] = Key[i] xor ... */
-		aes_mct_next_key(key, keysize, ciphertext_1, ciphertext);
-		/* IV[i+1] = CT[j] */
-		memcpy(iv, ciphertext, sizeof iv);
-		/* PT[0] = CT[j-1] */
-		/* done at the end of the for(j) loop */
-
-		fputc('\n', aesresp);
-	    }
-
-	    continue;
-	}
-	/* CIPHERTEXT = ... */
-	if (strncmp(buf, "CIPHERTEXT", 10) == 0) {
-	    /* sanity check */
-	    if (encrypt) {
-		goto loser;
-	    }
-	    /* CT[0] = CT */
-	    i = 10;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; isxdigit(buf[i]); i+=2,j++) {
-		hex_to_byteval(&buf[i], &ciphertext[j]);
-	    }
-
-	    for (i=0; i<100; i++) {
-		sprintf(buf, "COUNT = %d\n", i);
-	        fputs(buf, aesresp);
-		/* Output Key[i] */
-		fputs("KEY = ", aesresp);
-		to_hex_str(buf, key, keysize);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-		/* Output IV[i] */
-		fputs("IV = ", aesresp);
-		to_hex_str(buf, iv, sizeof iv);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-		/* Output CT[0] */
-		fputs("CIPHERTEXT = ", aesresp);
-		to_hex_str(buf, ciphertext, sizeof ciphertext);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-
-		cx = AES_CreateContext(key, iv, NSS_AES_CBC,
-		    PR_FALSE, keysize, 16);
-		if (cx == NULL) {
-		    goto loser;
-		}
-		/*
-		 * doublecheck our result by encrypting the result
-		 * and comparing the output with the ciphertext.
-		 */
-		cx2 = AES_CreateContext(key, iv, NSS_AES_CBC,
-		    PR_TRUE, keysize, 16);
-		if (cx2 == NULL) {
-		    goto loser;
-		}
-		/* PT[-1] = IV[i] */
-		memcpy(plaintext, iv, sizeof plaintext);
-		for (j=0; j<1000; j++) {
-		    /* Save PT[j-1] */
-		    memcpy(plaintext_1, plaintext, sizeof plaintext);
-		    /*
-		     * If ( j=0 )
-		     *      PT[j] = AES(Key[i], IV[i], CT[j])
-		     *      CT[j+1] = IV[i] (= PT[j-1])
-		     * Else
-		     *      PT[j] = AES(Key[i], CT[j])
-		     *      CT[j+1] = PT[j-1]
-		     */
-		    outputlen = 0;
-		    rv = AES_Decrypt(cx,
-			plaintext, &outputlen, sizeof plaintext,
-			ciphertext, sizeof ciphertext);
-		    if (rv != SECSuccess) {
-			goto loser;
-		    }
-		    if (outputlen != sizeof ciphertext) {
-			goto loser;
-		    }
-
-		    /* doublecheck our result */
-		    outputlen = 0;
-		    rv = AES_Encrypt(cx2,
-			doublecheck, &outputlen, sizeof doublecheck,
-			plaintext, sizeof plaintext);
-		    if (rv != SECSuccess) {
-			goto loser;
-		    }
-		    if (outputlen != sizeof plaintext) {
-			goto loser;
-		    }
-		    if (memcmp(doublecheck, ciphertext, sizeof ciphertext)) {
-			goto loser;
-		    }
-
-		    memcpy(ciphertext, plaintext_1, sizeof ciphertext);
-		}
-		AES_DestroyContext(cx, PR_TRUE);
-		cx = NULL;
-		AES_DestroyContext(cx2, PR_TRUE);
-		cx2 = NULL;
-
-		/* Output PT[j] */
-		fputs("PLAINTEXT = ", aesresp);
-		to_hex_str(buf, plaintext, sizeof plaintext);
-		fputs(buf, aesresp);
-		fputc('\n', aesresp);
-
-		/* Key[i+1] = Key[i] xor ... */
-		aes_mct_next_key(key, keysize, plaintext_1, plaintext);
-		/* IV[i+1] = PT[j] */
-		memcpy(iv, plaintext, sizeof iv);
-		/* CT[0] = PT[j-1] */
-		/* done at the end of the for(j) loop */
-
-		fputc('\n', aesresp);
-	    }
-
-	    continue;
-	}
+        /* a comment or blank line */
+        if (buf[0] == '#' || buf[0] == '\n') {
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* [ENCRYPT] or [DECRYPT] */
+        if (buf[0] == '[') {
+            if (strncmp(&buf[1], "ENCRYPT", 7) == 0) {
+                encrypt = 1;
+            } else {
+                encrypt = 0;
+            }
+            fputs(buf, aesresp);
+            continue;
+        }
+        /* "COUNT = x" begins a new data set */
+        if (strncmp(buf, "COUNT", 5) == 0) {
+            /* zeroize the variables for the test with this data set */
+            memset(key, 0, sizeof key);
+            keysize = 0;
+            memset(iv, 0, sizeof iv);
+            memset(plaintext, 0, sizeof plaintext);
+            memset(ciphertext, 0, sizeof ciphertext);
+            continue;
+        }
+        /* KEY = ... */
+        if (strncmp(buf, "KEY", 3) == 0) {
+            /* Key[0] = Key */
+            i = 3;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &key[j]);
+            }
+            keysize = j;
+            continue;
+        }
+        /* IV = ... */
+        if (strncmp(buf, "IV", 2) == 0) {
+            /* IV[0] = IV */
+            i = 2;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<sizeof iv; i+=2,j++) {
+                hex_to_byteval(&buf[i], &iv[j]);
+            }
+            continue;
+        }
+        /* PLAINTEXT = ... */
+        if (strncmp(buf, "PLAINTEXT", 9) == 0) {
+            /* sanity check */
+            if (!encrypt) {
+                goto loser;
+            }
+            /* PT[0] = PT */
+            i = 9;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<sizeof plaintext; i+=2,j++) {
+                hex_to_byteval(&buf[i], &plaintext[j]);
+            }
+
+            for (i=0; i<100; i++) {
+                sprintf(buf, "COUNT = %d\n", i);
+                fputs(buf, aesresp);
+                /* Output Key[i] */
+                fputs("KEY = ", aesresp);
+                to_hex_str(buf, key, keysize);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+                /* Output IV[i] */
+                fputs("IV = ", aesresp);
+                to_hex_str(buf, iv, sizeof iv);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+                /* Output PT[0] */
+                fputs("PLAINTEXT = ", aesresp);
+                to_hex_str(buf, plaintext, sizeof plaintext);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+
+                cx = AES_CreateContext(key, iv, NSS_AES_CBC,
+                    PR_TRUE, keysize, 16);
+                if (cx == NULL) {
+                    goto loser;
+                }
+                /*
+                 * doublecheck our result by decrypting the result
+                 * and comparing the output with the plaintext.
+                 */
+                cx2 = AES_CreateContext(key, iv, NSS_AES_CBC,
+                    PR_FALSE, keysize, 16);
+                if (cx2 == NULL) {
+                    goto loser;
+                }
+                /* CT[-1] = IV[i] */
+                memcpy(ciphertext, iv, sizeof ciphertext);
+                for (j=0; j<1000; j++) {
+                    /* Save CT[j-1] */
+                    memcpy(ciphertext_1, ciphertext, sizeof ciphertext);
+                    /*
+                     * If ( j=0 )
+                     *      CT[j] = AES(Key[i], IV[i], PT[j])
+                     *      PT[j+1] = IV[i] (= CT[j-1])
+                     * Else
+                     *      CT[j] = AES(Key[i], PT[j])
+                     *      PT[j+1] = CT[j-1]
+                     */
+                    outputlen = 0;
+                    rv = AES_Encrypt(cx,
+                        ciphertext, &outputlen, sizeof ciphertext,
+                        plaintext, sizeof plaintext);
+                    if (rv != SECSuccess) {
+                        goto loser;
+                    }
+                    if (outputlen != sizeof plaintext) {
+                        goto loser;
+                    }
+
+                    /* doublecheck our result */
+                    outputlen = 0;
+                    rv = AES_Decrypt(cx2,
+                        doublecheck, &outputlen, sizeof doublecheck,
+                        ciphertext, sizeof ciphertext);
+                    if (rv != SECSuccess) {
+                        goto loser;
+                    }
+                    if (outputlen != sizeof ciphertext) {
+                        goto loser;
+                    }
+                    if (memcmp(doublecheck, plaintext, sizeof plaintext)) {
+                        goto loser;
+                    }
+
+                    memcpy(plaintext, ciphertext_1, sizeof plaintext);
+                }
+                AES_DestroyContext(cx, PR_TRUE);
+                cx = NULL;
+                AES_DestroyContext(cx2, PR_TRUE);
+                cx2 = NULL;
+
+                /* Output CT[j] */
+                fputs("CIPHERTEXT = ", aesresp);
+                to_hex_str(buf, ciphertext, sizeof ciphertext);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+
+                /* Key[i+1] = Key[i] xor ... */
+                aes_mct_next_key(key, keysize, ciphertext_1, ciphertext);
+                /* IV[i+1] = CT[j] */
+                memcpy(iv, ciphertext, sizeof iv);
+                /* PT[0] = CT[j-1] */
+                /* done at the end of the for(j) loop */
+
+                fputc('\n', aesresp);
+            }
+
+            continue;
+        }
+        /* CIPHERTEXT = ... */
+        if (strncmp(buf, "CIPHERTEXT", 10) == 0) {
+            /* sanity check */
+            if (encrypt) {
+                goto loser;
+            }
+            /* CT[0] = CT */
+            i = 10;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &ciphertext[j]);
+            }
+
+            for (i=0; i<100; i++) {
+                sprintf(buf, "COUNT = %d\n", i);
+                fputs(buf, aesresp);
+                /* Output Key[i] */
+                fputs("KEY = ", aesresp);
+                to_hex_str(buf, key, keysize);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+                /* Output IV[i] */
+                fputs("IV = ", aesresp);
+                to_hex_str(buf, iv, sizeof iv);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+                /* Output CT[0] */
+                fputs("CIPHERTEXT = ", aesresp);
+                to_hex_str(buf, ciphertext, sizeof ciphertext);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+
+                cx = AES_CreateContext(key, iv, NSS_AES_CBC,
+                    PR_FALSE, keysize, 16);
+                if (cx == NULL) {
+                    goto loser;
+                }
+                /*
+                 * doublecheck our result by encrypting the result
+                 * and comparing the output with the ciphertext.
+                 */
+                cx2 = AES_CreateContext(key, iv, NSS_AES_CBC,
+                    PR_TRUE, keysize, 16);
+                if (cx2 == NULL) {
+                    goto loser;
+                }
+                /* PT[-1] = IV[i] */
+                memcpy(plaintext, iv, sizeof plaintext);
+                for (j=0; j<1000; j++) {
+                    /* Save PT[j-1] */
+                    memcpy(plaintext_1, plaintext, sizeof plaintext);
+                    /*
+                     * If ( j=0 )
+                     *      PT[j] = AES(Key[i], IV[i], CT[j])
+                     *      CT[j+1] = IV[i] (= PT[j-1])
+                     * Else
+                     *      PT[j] = AES(Key[i], CT[j])
+                     *      CT[j+1] = PT[j-1]
+                     */
+                    outputlen = 0;
+                    rv = AES_Decrypt(cx,
+                        plaintext, &outputlen, sizeof plaintext,
+                        ciphertext, sizeof ciphertext);
+                    if (rv != SECSuccess) {
+                        goto loser;
+                    }
+                    if (outputlen != sizeof ciphertext) {
+                        goto loser;
+                    }
+
+                    /* doublecheck our result */
+                    outputlen = 0;
+                    rv = AES_Encrypt(cx2,
+                        doublecheck, &outputlen, sizeof doublecheck,
+                        plaintext, sizeof plaintext);
+                    if (rv != SECSuccess) {
+                        goto loser;
+                    }
+                    if (outputlen != sizeof plaintext) {
+                        goto loser;
+                    }
+                    if (memcmp(doublecheck, ciphertext, sizeof ciphertext)) {
+                        goto loser;
+                    }
+
+                    memcpy(ciphertext, plaintext_1, sizeof ciphertext);
+                }
+                AES_DestroyContext(cx, PR_TRUE);
+                cx = NULL;
+                AES_DestroyContext(cx2, PR_TRUE);
+                cx2 = NULL;
+
+                /* Output PT[j] */
+                fputs("PLAINTEXT = ", aesresp);
+                to_hex_str(buf, plaintext, sizeof plaintext);
+                fputs(buf, aesresp);
+                fputc('\n', aesresp);
+
+                /* Key[i+1] = Key[i] xor ... */
+                aes_mct_next_key(key, keysize, plaintext_1, plaintext);
+                /* IV[i+1] = PT[j] */
+                memcpy(iv, plaintext, sizeof iv);
+                /* CT[0] = PT[j-1] */
+                /* done at the end of the for(j) loop */
+
+                fputc('\n', aesresp);
+            }
+
+            continue;
+        }
     }
 loser:
     if (cx != NULL) {
-	AES_DestroyContext(cx, PR_TRUE);
+        AES_DestroyContext(cx, PR_TRUE);
     }
     if (cx2 != NULL) {
-	AES_DestroyContext(cx2, PR_TRUE);
+        AES_DestroyContext(cx2, PR_TRUE);
     }
     fclose(aesreq);
 }
 
 void write_compact_string(FILE *out, unsigned char *hash, unsigned int len)
 {
     unsigned int i;
     int j, count = 0, last = -1, z = 0;
     long start = ftell(out);
     for (i=0; i<len; i++) {
-	for (j=7; j>=0; j--) {
-	    if (last < 0) {
-		last = (hash[i] & (1 << j)) ? 1 : 0;
-		fprintf(out, "%d ", last);
-		count = 1;
-	    } else if (hash[i] & (1 << j)) {
-		if (last) {
-		    count++; 
-		} else { 
-		    last = 0;
-		    fprintf(out, "%d ", count);
-		    count = 1;
-		    z++;
-		}
-	    } else {
-		if (!last) {
-		    count++; 
-		} else { 
-		    last = 1;
-		    fprintf(out, "%d ", count);
-		    count = 1;
-		    z++;
-		}
-	    }
-	}
+        for (j=7; j>=0; j--) {
+            if (last < 0) {
+                last = (hash[i] & (1 << j)) ? 1 : 0;
+                fprintf(out, "%d ", last);
+                count = 1;
+            } else if (hash[i] & (1 << j)) {
+                if (last) {
+                    count++; 
+                } else { 
+                    last = 0;
+                    fprintf(out, "%d ", count);
+                    count = 1;
+                    z++;
+                }
+            } else {
+                if (!last) {
+                    count++; 
+                } else { 
+                    last = 1;
+                    fprintf(out, "%d ", count);
+                    count = 1;
+                    z++;
+                }
+            }
+        }
     }
     fprintf(out, "^\n");
     fseek(out, start, SEEK_SET);
     fprintf(out, "%d ", z);
     fseek(out, 0, SEEK_END);
 }
 
 int get_next_line(FILE *req, char *key, char *val, FILE *rsp)
 {
     int ignore = 0;
     char *writeto = key;
     int w = 0;
     int c;
     while ((c = fgetc(req)) != EOF) {
-	if (ignore) {
-	    fprintf(rsp, "%c", c);
-	    if (c == '\n') return ignore;
-	} else if (c == '\n') {
-	    break;
-	} else if (c == '#') {
-	    ignore = 1;
-	    fprintf(rsp, "%c", c);
-	} else if (c == '=') {
-	    writeto[w] = '\0';
-	    w = 0;
-	    writeto = val;
-	} else if (c == ' ' || c == '[' || c == ']') {
-	    continue;
-	} else {
-	    writeto[w++] = c;
-	}
+        if (ignore) {
+            fprintf(rsp, "%c", c);
+            if (c == '\n') return ignore;
+        } else if (c == '\n') {
+            break;
+        } else if (c == '#') {
+            ignore = 1;
+            fprintf(rsp, "%c", c);
+        } else if (c == '=') {
+            writeto[w] = '\0';
+            w = 0;
+            writeto = val;
+        } else if (c == ' ' || c == '[' || c == ']') {
+            continue;
+        } else {
+            writeto[w++] = c;
+        }
     }
     writeto[w] = '\0';
     return (c == EOF) ? -1 : ignore;
 }
 
 #ifndef NSS_DISABLE_ECC
 typedef struct curveNameTagPairStr {
     char *curveName;
@@ -1945,28 +2176,28 @@ getECParams(const char *curve)
 {
     SECItem *ecparams;
     SECOidData *oidData = NULL;
     SECOidTag curveOidTag = SEC_OID_UNKNOWN; /* default */
     int i, numCurves;
 
     if (curve != NULL) {
         numCurves = sizeof(nameTagPair)/sizeof(CurveNameTagPair);
-	for (i = 0; ((i < numCurves) && (curveOidTag == SEC_OID_UNKNOWN)); 
-	     i++) {
-	    if (PL_strcmp(curve, nameTagPair[i].curveName) == 0)
-	        curveOidTag = nameTagPair[i].curveOidTag;
-	}
+        for (i = 0; ((i < numCurves) && (curveOidTag == SEC_OID_UNKNOWN)); 
+             i++) {
+            if (PL_strcmp(curve, nameTagPair[i].curveName) == 0)
+                curveOidTag = nameTagPair[i].curveOidTag;
+        }
     }
 
     /* Return NULL if curve name is not recognized */
     if ((curveOidTag == SEC_OID_UNKNOWN) || 
-	(oidData = SECOID_FindOIDByTag(curveOidTag)) == NULL) {
+        (oidData = SECOID_FindOIDByTag(curveOidTag)) == NULL) {
         fprintf(stderr, "Unrecognized elliptic curve %s\n", curve);
-	return NULL;
+        return NULL;
     }
 
     ecparams = SECITEM_AllocItem(NULL, NULL, (2 + oidData->oid.len));
 
     /* 
      * ecparams->data needs to contain the ASN encoding of an object ID (OID)
      * representing the named curve. The actual OID is in 
      * oidData->oid.data so we simply prepend 0x06 and OID length
@@ -1974,16 +2205,131 @@ getECParams(const char *curve)
     ecparams->data[0] = SEC_ASN1_OBJECT_ID;
     ecparams->data[1] = oidData->oid.len;
     memcpy(ecparams->data + 2, oidData->oid.data, oidData->oid.len);
 
     return ecparams;
 }
 
 /*
+ * HASH_ functions are available to full NSS apps and internally inside
+ * freebl, but not exported to users of freebl. Create short stubs to
+ * replace the functionality for fipstest.
+ */
+SECStatus
+fips_hashBuf(HASH_HashType type, unsigned char *hashBuf, 
+                                        unsigned char *msg, int len)
+{
+    SECStatus rv = SECFailure;
+
+    switch (type) {
+    case HASH_AlgSHA1:
+        rv = SHA1_HashBuf(hashBuf, msg, len);
+        break;
+    case HASH_AlgSHA224:
+        rv = SHA224_HashBuf(hashBuf, msg, len);
+        break;
+    case HASH_AlgSHA256:
+        rv = SHA256_HashBuf(hashBuf, msg, len);
+        break;
+    case HASH_AlgSHA384:
+        rv = SHA384_HashBuf(hashBuf, msg, len);
+        break;
+    case HASH_AlgSHA512:
+        rv = SHA512_HashBuf(hashBuf, msg, len);
+        break;
+    default:
+        break;
+    }
+    return rv;
+}
+
+int
+fips_hashLen(HASH_HashType type)
+{
+    int len = 0;
+
+    switch (type) {
+    case HASH_AlgSHA1:
+        len = SHA1_LENGTH;
+        break;
+    case HASH_AlgSHA224:
+        len = SHA224_LENGTH;
+        break;
+    case HASH_AlgSHA256:
+        len = SHA256_LENGTH;
+        break;
+    case HASH_AlgSHA384:
+        len = SHA384_LENGTH;
+        break;
+    case HASH_AlgSHA512:
+        len = SHA512_LENGTH;
+        break;
+    default:
+        break;
+    }
+    return len;
+}
+
+SECOidTag
+fips_hashOid(HASH_HashType type)
+{
+    SECOidTag oid = SEC_OID_UNKNOWN;
+
+    switch (type) {
+    case HASH_AlgSHA1:
+        oid = SEC_OID_SHA1;
+        break;
+    case HASH_AlgSHA224:
+        oid = SEC_OID_SHA224;
+        break;
+    case HASH_AlgSHA256:
+        oid = SEC_OID_SHA256;
+        break;
+    case HASH_AlgSHA384:
+        oid = SEC_OID_SHA384;
+        break;
+    case HASH_AlgSHA512:
+        oid = SEC_OID_SHA512;
+        break;
+    default:
+        break;
+    }
+    return oid;
+}
+
+HASH_HashType
+sha_get_hashType(int hashbits)
+{
+    HASH_HashType hashType = HASH_AlgNULL;
+
+    switch (hashbits) {
+    case 1:
+    case (SHA1_LENGTH*PR_BITS_PER_BYTE): 
+        hashType = HASH_AlgSHA1;
+        break;
+    case (SHA224_LENGTH*PR_BITS_PER_BYTE): 
+        hashType = HASH_AlgSHA224;
+        break;
+    case (SHA256_LENGTH*PR_BITS_PER_BYTE): 
+        hashType = HASH_AlgSHA256;
+        break;
+    case (SHA384_LENGTH*PR_BITS_PER_BYTE): 
+        hashType = HASH_AlgSHA384;
+        break;
+    case (SHA512_LENGTH*PR_BITS_PER_BYTE): 
+        hashType = HASH_AlgSHA512;
+        break;
+    default:
+        break;
+    }
+    return hashType;
+}
+
+/*
  * Perform the ECDSA Key Pair Generation Test.
  *
  * reqfn is the pathname of the REQUEST file.
  *
  * The output RESPONSE file is written to stdout.
  */
 void
 ecdsa_keypair_test(char *reqfn)
@@ -1991,100 +2337,114 @@ ecdsa_keypair_test(char *reqfn)
     char buf[256];      /* holds one line from the input REQUEST file
                          * or to the output RESPONSE file.
                          * needs to be large enough to hold the longest
                          * line "Qx = <144 hex digits>\n".
                          */
     FILE *ecdsareq;     /* input stream from the REQUEST file */
     FILE *ecdsaresp;    /* output stream to the RESPONSE file */
     char curve[16];     /* "nistxddd" */
-    ECParams *ecparams;
+    ECParams *ecparams = NULL;
     int N;
     int i;
     unsigned int len;
 
     ecdsareq = fopen(reqfn, "r");
     ecdsaresp = stdout;
     strcpy(curve, "nist");
     while (fgets(buf, sizeof buf, ecdsareq) != NULL) {
-	/* a comment or blank line */
-	if (buf[0] == '#' || buf[0] == '\n') {
-	    fputs(buf, ecdsaresp);
-	    continue;
-	}
-	/* [X-ddd] */
-	if (buf[0] == '[') {
-	    const char *src;
-	    char *dst;
-	    SECItem *encodedparams;
-
-	    src = &buf[1];
-	    dst = &curve[4];
-	    *dst++ = tolower(*src);
-	    src += 2;  /* skip the hyphen */
-	    *dst++ = *src++;
-	    *dst++ = *src++;
-	    *dst++ = *src++;
-	    *dst = '\0';
-	    encodedparams = getECParams(curve);
-	    if (encodedparams == NULL) {
-		goto loser;
-	    }
-	    if (EC_DecodeParams(encodedparams, &ecparams) != SECSuccess) {
-		goto loser;
-	    }
-	    SECITEM_FreeItem(encodedparams, PR_TRUE);
-	    fputs(buf, ecdsaresp);
-	    continue;
-	}
-	/* N = x */
-	if (buf[0] == 'N') {
-	    if (sscanf(buf, "N = %d", &N) != 1) {
-		goto loser;
-	    }
-	    for (i = 0; i < N; i++) {
-		ECPrivateKey *ecpriv;
-
-		if (EC_NewKey(ecparams, &ecpriv) != SECSuccess) {
-		    goto loser;
-		}
-		fputs("d = ", ecdsaresp);
-		to_hex_str(buf, ecpriv->privateValue.data,
-			   ecpriv->privateValue.len);
-		fputs(buf, ecdsaresp);
-		fputc('\n', ecdsaresp);
-		if (EC_ValidatePublicKey(ecparams, &ecpriv->publicValue)
-		    != SECSuccess) {
-		    goto loser;
-		}
-		len = ecpriv->publicValue.len;
-		if (len%2 == 0) {
-		    goto loser;
-		}
-		len = (len-1)/2;
-		if (ecpriv->publicValue.data[0]
-		    != EC_POINT_FORM_UNCOMPRESSED) {
-		    goto loser;
-		}
-		fputs("Qx = ", ecdsaresp);
-		to_hex_str(buf, &ecpriv->publicValue.data[1], len);
-		fputs(buf, ecdsaresp);
-		fputc('\n', ecdsaresp);
-		fputs("Qy = ", ecdsaresp);
-		to_hex_str(buf, &ecpriv->publicValue.data[1+len], len);
-		fputs(buf, ecdsaresp);
-		fputc('\n', ecdsaresp);
-		fputc('\n', ecdsaresp);
-		PORT_FreeArena(ecpriv->ecParams.arena, PR_TRUE);
-	    }
-	    PORT_FreeArena(ecparams->arena, PR_FALSE);
-	    continue;
-	}
+        /* a comment or blank line */
+        if (buf[0] == '#' || buf[0] == '\n') {
+            fputs(buf, ecdsaresp);
+            continue;
+        }
+        /* [X-ddd] */
+        if (buf[0] == '[') {
+            const char *src;
+            char *dst;
+            SECItem *encodedparams;
+
+            if (buf[1] == 'B') {
+                fputs(buf, ecdsaresp);
+                continue;
+            }
+            if (ecparams) {
+                PORT_FreeArena(ecparams->arena, PR_FALSE);
+                ecparams = NULL;
+            }
+
+            src = &buf[1];
+            dst = &curve[4];
+            *dst++ = tolower(*src);
+            src += 2;  /* skip the hyphen */
+            *dst++ = *src++;
+            *dst++ = *src++;
+            *dst++ = *src++;
+            *dst = '\0';
+            encodedparams = getECParams(curve);
+            if (encodedparams == NULL) {
+                fprintf(stderr, "Unknown curve %s.", curve);
+                goto loser;
+            }
+            if (EC_DecodeParams(encodedparams, &ecparams) != SECSuccess) {
+                fprintf(stderr, "Curve %s not supported.\n", curve);
+                goto loser;
+            }
+            SECITEM_FreeItem(encodedparams, PR_TRUE);
+            fputs(buf, ecdsaresp);
+            continue;
+        }
+        /* N = x */
+        if (buf[0] == 'N') {
+            if (sscanf(buf, "N = %d", &N) != 1) {
+                goto loser;
+            }
+            for (i = 0; i < N; i++) {
+                ECPrivateKey *ecpriv;
+
+                if (EC_NewKey(ecparams, &ecpriv) != SECSuccess) {
+                    goto loser;
+                }
+                fputs("d = ", ecdsaresp);
+                to_hex_str(buf, ecpriv->privateValue.data,
+                           ecpriv->privateValue.len);
+                fputs(buf, ecdsaresp);
+                fputc('\n', ecdsaresp);
+                if (EC_ValidatePublicKey(ecparams, &ecpriv->publicValue)
+                    != SECSuccess) {
+                    goto loser;
+                }
+                len = ecpriv->publicValue.len;
+                if (len%2 == 0) {
+                    goto loser;
+                }
+                len = (len-1)/2;
+                if (ecpriv->publicValue.data[0]
+                    != EC_POINT_FORM_UNCOMPRESSED) {
+                    goto loser;
+                }
+                fputs("Qx = ", ecdsaresp);
+                to_hex_str(buf, &ecpriv->publicValue.data[1], len);
+                fputs(buf, ecdsaresp);
+                fputc('\n', ecdsaresp);
+                fputs("Qy = ", ecdsaresp);
+                to_hex_str(buf, &ecpriv->publicValue.data[1+len], len);
+                fputs(buf, ecdsaresp);
+                fputc('\n', ecdsaresp);
+                fputc('\n', ecdsaresp);
+                PORT_FreeArena(ecpriv->ecParams.arena, PR_TRUE);
+            }
+            continue;
+        }
     }
 loser:
+    if (ecparams) {
+        PORT_FreeArena(ecparams->arena, PR_FALSE);
+        ecparams = NULL;
+    }
     fclose(ecdsareq);
 }
 
 /*
  * Perform the ECDSA Public Key Validation Test.
  *
  * reqfn is the pathname of the REQUEST file.
  *
@@ -2098,110 +2458,112 @@ ecdsa_pkv_test(char *reqfn)
                          * line "Qx = <144 hex digits>\n".
                          */
     FILE *ecdsareq;     /* input stream from the REQUEST file */
     FILE *ecdsaresp;    /* output stream to the RESPONSE file */
     char curve[16];     /* "nistxddd" */
     ECParams *ecparams = NULL;
     SECItem pubkey;
     unsigned int i;
-    unsigned int len;
+    unsigned int len = 0;
     PRBool keyvalid = PR_TRUE;
 
     ecdsareq = fopen(reqfn, "r");
     ecdsaresp = stdout;
     strcpy(curve, "nist");
     pubkey.data = NULL;
     while (fgets(buf, sizeof buf, ecdsareq) != NULL) {
-	/* a comment or blank line */
-	if (buf[0] == '#' || buf[0] == '\n') {
-	    fputs(buf, ecdsaresp);
-	    continue;
-	}
-	/* [X-ddd] */
-	if (buf[0] == '[') {
-	    const char *src;
-	    char *dst;
-	    SECItem *encodedparams;
-
-	    src = &buf[1];
-	    dst = &curve[4];
-	    *dst++ = tolower(*src);
-	    src += 2;  /* skip the hyphen */
-	    *dst++ = *src++;
-	    *dst++ = *src++;
-	    *dst++ = *src++;
-	    *dst = '\0';
-	    if (ecparams != NULL) {
-		PORT_FreeArena(ecparams->arena, PR_FALSE);
-		ecparams = NULL;
-	    }
-	    encodedparams = getECParams(curve);
-	    if (encodedparams == NULL) {
-		goto loser;
-	    }
-	    if (EC_DecodeParams(encodedparams, &ecparams) != SECSuccess) {
-		goto loser;
-	    }
-	    SECITEM_FreeItem(encodedparams, PR_TRUE);
-	    len = (ecparams->fieldID.size + 7) >> 3;
-	    if (pubkey.data != NULL) {
-		PORT_Free(pubkey.data);
-		pubkey.data = NULL;
-	    }
-	    SECITEM_AllocItem(NULL, &pubkey, 2*len+1);
-	    if (pubkey.data == NULL) {
-		goto loser;
-	    }
-	    pubkey.data[0] = EC_POINT_FORM_UNCOMPRESSED;
-	    fputs(buf, ecdsaresp);
-	    continue;
-	}
-	/* Qx = ... */
-	if (strncmp(buf, "Qx", 2) == 0) {
-	    fputs(buf, ecdsaresp);
-	    i = 2;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    keyvalid = from_hex_str(&pubkey.data[1], len, &buf[i]);
-	    continue;
-	}
-	/* Qy = ... */
-	if (strncmp(buf, "Qy", 2) == 0) {
-	    fputs(buf, ecdsaresp);
-	    if (!keyvalid) {
-		fputs("Result = F\n", ecdsaresp);
-		continue;
-	    }
-	    i = 2;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    keyvalid = from_hex_str(&pubkey.data[1+len], len, &buf[i]);
-	    if (!keyvalid) {
-		fputs("Result = F\n", ecdsaresp);
-		continue;
-	    }
-	    if (EC_ValidatePublicKey(ecparams, &pubkey) == SECSuccess) {
-		fputs("Result = P\n", ecdsaresp);
-	    } else if (PORT_GetError() == SEC_ERROR_BAD_KEY) {
-		fputs("Result = F\n", ecdsaresp);
-	    } else {
-		goto loser;
-	    }
-	    continue;
-	}
+        /* a comment or blank line */
+        if (buf[0] == '#' || buf[0] == '\n') {
+            fputs(buf, ecdsaresp);
+            continue;
+        }
+        /* [X-ddd] */
+        if (buf[0] == '[') {
+            const char *src;
+            char *dst;
+            SECItem *encodedparams;
+
+            src = &buf[1];
+            dst = &curve[4];
+            *dst++ = tolower(*src);
+            src += 2;  /* skip the hyphen */
+            *dst++ = *src++;
+            *dst++ = *src++;
+            *dst++ = *src++;
+            *dst = '\0';
+            if (ecparams != NULL) {
+                PORT_FreeArena(ecparams->arena, PR_FALSE);
+                ecparams = NULL;
+            }
+            encodedparams = getECParams(curve);
+            if (encodedparams == NULL) {
+                fprintf(stderr, "Unknown curve %s.", curve);
+                goto loser;
+            }
+            if (EC_DecodeParams(encodedparams, &ecparams) != SECSuccess) {
+                fprintf(stderr, "Curve %s not supported.\n", curve);
+                goto loser;
+            }
+            SECITEM_FreeItem(encodedparams, PR_TRUE);
+            len = (ecparams->fieldID.size + 7) >> 3;
+            if (pubkey.data != NULL) {
+                PORT_Free(pubkey.data);
+                pubkey.data = NULL;
+            }
+            SECITEM_AllocItem(NULL, &pubkey, 2*len+1);
+            if (pubkey.data == NULL) {
+                goto loser;
+            }
+            pubkey.data[0] = EC_POINT_FORM_UNCOMPRESSED;
+            fputs(buf, ecdsaresp);
+            continue;
+        }
+        /* Qx = ... */
+        if (strncmp(buf, "Qx", 2) == 0) {
+            fputs(buf, ecdsaresp);
+            i = 2;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            keyvalid = from_hex_str(&pubkey.data[1], len, &buf[i]);
+            continue;
+        }
+        /* Qy = ... */
+        if (strncmp(buf, "Qy", 2) == 0) {
+            fputs(buf, ecdsaresp);
+            if (!keyvalid) {
+                fputs("Result = F\n", ecdsaresp);
+                continue;
+            }
+            i = 2;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            keyvalid = from_hex_str(&pubkey.data[1+len], len, &buf[i]);
+            if (!keyvalid) {
+                fputs("Result = F\n", ecdsaresp);
+                continue;
+            }
+            if (EC_ValidatePublicKey(ecparams, &pubkey) == SECSuccess) {
+                fputs("Result = P\n", ecdsaresp);
+            } else if (PORT_GetError() == SEC_ERROR_BAD_KEY) {
+                fputs("Result = F\n", ecdsaresp);
+            } else {
+                goto loser;
+            }
+            continue;
+        }
     }
 loser:
     if (ecparams != NULL) {
-	PORT_FreeArena(ecparams->arena, PR_FALSE);
+        PORT_FreeArena(ecparams->arena, PR_FALSE);
     }
     if (pubkey.data != NULL) {
-	PORT_Free(pubkey.data);
+        PORT_Free(pubkey.data);
     }
     fclose(ecdsareq);
 }
 
 /*
  * Perform the ECDSA Signature Generation Test.
  *
  * reqfn is the pathname of the REQUEST file.
@@ -2219,129 +2581,155 @@ ecdsa_siggen_test(char *reqfn)
     FILE *ecdsareq;     /* input stream from the REQUEST file */
     FILE *ecdsaresp;    /* output stream to the RESPONSE file */
     char curve[16];     /* "nistxddd" */
     ECParams *ecparams = NULL;
     int i, j;
     unsigned int len;
     unsigned char msg[512];  /* message to be signed (<= 128 bytes) */
     unsigned int msglen;
-    unsigned char sha1[20];  /* SHA-1 hash (160 bits) */
+    unsigned char  sha[HASH_LENGTH_MAX];    /* SHA digest */
+    unsigned int   shaLength = 0;           /* length of SHA */
+    HASH_HashType  shaAlg = HASH_AlgNULL;   /* type of SHA Alg */
     unsigned char sig[2*MAX_ECKEY_LEN];
     SECItem signature, digest;
 
     ecdsareq = fopen(reqfn, "r");
     ecdsaresp = stdout;
     strcpy(curve, "nist");
     while (fgets(buf, sizeof buf, ecdsareq) != NULL) {
-	/* a comment or blank line */
-	if (buf[0] == '#' || buf[0] == '\n') {
-	    fputs(buf, ecdsaresp);
-	    continue;
-	}
-	/* [X-ddd] */
-	if (buf[0] == '[') {
-	    const char *src;
-	    char *dst;
-	    SECItem *encodedparams;
-
-	    src = &buf[1];
-	    dst = &curve[4];
-	    *dst++ = tolower(*src);
-	    src += 2;  /* skip the hyphen */
-	    *dst++ = *src++;
-	    *dst++ = *src++;
-	    *dst++ = *src++;
-	    *dst = '\0';
-	    if (ecparams != NULL) {
-		PORT_FreeArena(ecparams->arena, PR_FALSE);
-		ecparams = NULL;
-	    }
-	    encodedparams = getECParams(curve);
-	    if (encodedparams == NULL) {
-		goto loser;
-	    }
-	    if (EC_DecodeParams(encodedparams, &ecparams) != SECSuccess) {
-		goto loser;
-	    }
-	    SECITEM_FreeItem(encodedparams, PR_TRUE);
-	    fputs(buf, ecdsaresp);
-	    continue;
-	}
-	/* Msg = ... */
-	if (strncmp(buf, "Msg", 3) == 0) {
-	    ECPrivateKey *ecpriv;
-
-	    i = 3;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; isxdigit(buf[i]); i+=2,j++) {
-		hex_to_byteval(&buf[i], &msg[j]);
-	    }
-	    msglen = j;
-	    if (SHA1_HashBuf(sha1, msg, msglen) != SECSuccess) {
-		goto loser;
-	    }
-	    fputs(buf, ecdsaresp);
-
-	    if (EC_NewKey(ecparams, &ecpriv) != SECSuccess) {
-		goto loser;
-	    }
-	    if (EC_ValidatePublicKey(ecparams, &ecpriv->publicValue)
-		!= SECSuccess) {
-		goto loser;
-	    }
-	    len = ecpriv->publicValue.len;
-	    if (len%2 == 0) {
-		goto loser;
-	    }
-	    len = (len-1)/2;
-	    if (ecpriv->publicValue.data[0] != EC_POINT_FORM_UNCOMPRESSED) {
-		goto loser;
-	    }
-	    fputs("Qx = ", ecdsaresp);
-	    to_hex_str(buf, &ecpriv->publicValue.data[1], len);
-	    fputs(buf, ecdsaresp);
-	    fputc('\n', ecdsaresp);
-	    fputs("Qy = ", ecdsaresp);
-	    to_hex_str(buf, &ecpriv->publicValue.data[1+len], len);
-	    fputs(buf, ecdsaresp);
-	    fputc('\n', ecdsaresp);
-
-	    digest.type = siBuffer;
-	    digest.data = sha1;
-	    digest.len = sizeof sha1;
-	    signature.type = siBuffer;
-	    signature.data = sig;
-	    signature.len = sizeof sig;
-	    if (ECDSA_SignDigest(ecpriv, &signature, &digest) != SECSuccess) {
-		goto loser;
-	    }
-	    len = signature.len;
-	    if (len%2 != 0) {
-		goto loser;
-	    }
-	    len = len/2;
-	    fputs("R = ", ecdsaresp);
-	    to_hex_str(buf, &signature.data[0], len);
-	    fputs(buf, ecdsaresp);
-	    fputc('\n', ecdsaresp);
-	    fputs("S = ", ecdsaresp);
-	    to_hex_str(buf, &signature.data[len], len);
-	    fputs(buf, ecdsaresp);
-	    fputc('\n', ecdsaresp);
-
-	    PORT_FreeArena(ecpriv->ecParams.arena, PR_TRUE);
-	    continue;
-	}
+        /* a comment or blank line */
+        if (buf[0] == '#' || buf[0] == '\n') {
+            fputs(buf, ecdsaresp);
+            continue;
+        }
+        /* [X-ddd] */
+        if (buf[0] == '[') {
+            const char *src;
+            char *dst;
+            SECItem *encodedparams;
+
+            src = &buf[1];
+            dst = &curve[4];
+            *dst++ = tolower(*src);
+            src += 2;  /* skip the hyphen */
+            *dst++ = *src++;
+            *dst++ = *src++;
+            *dst++ = *src++;
+            *dst = '\0';
+            src++; /* skip the comma */
+            /* set the SHA Algorithm */
+            if (strncmp(src, "SHA-1", 5) == 0) {
+                shaAlg = HASH_AlgSHA1;
+            } else if (strncmp(src, "SHA-224", 7) == 0) {
+                shaAlg = HASH_AlgSHA224;
+            } else if (strncmp(src, "SHA-256", 7) == 0) {
+                shaAlg = HASH_AlgSHA256;
+            } else if (strncmp(src, "SHA-384", 7)== 0) {
+               shaAlg = HASH_AlgSHA384;
+            } else if (strncmp(src, "SHA-512", 7) == 0) {
+               shaAlg = HASH_AlgSHA512;
+            } else {
+               fprintf(ecdsaresp, "ERROR: Unable to find SHAAlg type");
+               goto loser;
+            }
+            if (ecparams != NULL) {
+                PORT_FreeArena(ecparams->arena, PR_FALSE);
+                ecparams = NULL;
+            }
+            encodedparams = getECParams(curve);
+            if (encodedparams == NULL) {
+                fprintf(stderr, "Unknown curve %s.", curve);
+                goto loser;
+            }
+            if (EC_DecodeParams(encodedparams, &ecparams) != SECSuccess) {
+                fprintf(stderr, "Curve %s not supported.\n", curve);
+                goto loser;
+            }
+            SECITEM_FreeItem(encodedparams, PR_TRUE);
+            fputs(buf, ecdsaresp);
+            continue;
+        }
+        /* Msg = ... */
+        if (strncmp(buf, "Msg", 3) == 0) {
+            ECPrivateKey *ecpriv;
+
+            i = 3;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &msg[j]);
+            }
+            msglen = j;
+            shaLength = fips_hashLen(shaAlg);
+            if (fips_hashBuf(shaAlg,sha,msg,msglen) != SECSuccess) {
+                if (shaLength == 0) {
+                        fprintf(ecdsaresp, "ERROR: SHAAlg not defined.");
+                }
+                fprintf(ecdsaresp, "ERROR: Unable to generate SHA%x",
+                        shaLength == 160 ? 1 : shaLength);
+                goto loser;
+            }
+            fputs(buf, ecdsaresp);
+
+            if (EC_NewKey(ecparams, &ecpriv) != SECSuccess) {
+                goto loser;
+            }
+            if (EC_ValidatePublicKey(ecparams, &ecpriv->publicValue)
+                != SECSuccess) {
+                goto loser;
+            }
+            len = ecpriv->publicValue.len;
+            if (len%2 == 0) {
+                goto loser;
+            }
+            len = (len-1)/2;
+            if (ecpriv->publicValue.data[0] != EC_POINT_FORM_UNCOMPRESSED) {
+                goto loser;
+            }
+            fputs("Qx = ", ecdsaresp);
+            to_hex_str(buf, &ecpriv->publicValue.data[1], len);
+            fputs(buf, ecdsaresp);
+            fputc('\n', ecdsaresp);
+            fputs("Qy = ", ecdsaresp);
+            to_hex_str(buf, &ecpriv->publicValue.data[1+len], len);
+            fputs(buf, ecdsaresp);
+            fputc('\n', ecdsaresp);
+
+            digest.type = siBuffer;
+            digest.data = sha;
+            digest.len = shaLength;
+            signature.type = siBuffer;
+            signature.data = sig;
+            signature.len = sizeof sig;
+            if (ECDSA_SignDigest(ecpriv, &signature, &digest) != SECSuccess) {
+                goto loser;
+            }
+            len = signature.len;
+            if (len%2 != 0) {
+                goto loser;
+            }
+            len = len/2;
+            fputs("R = ", ecdsaresp);
+            to_hex_str(buf, &signature.data[0], len);
+            fputs(buf, ecdsaresp);
+            fputc('\n', ecdsaresp);
+            fputs("S = ", ecdsaresp);
+            to_hex_str(buf, &signature.data[len], len);
+            fputs(buf, ecdsaresp);
+            fputc('\n', ecdsaresp);
+
+            PORT_FreeArena(ecpriv->ecParams.arena, PR_TRUE);
+            continue;
+        }
     }
 loser:
     if (ecparams != NULL) {
-	PORT_FreeArena(ecparams->arena, PR_FALSE);
+        PORT_FreeArena(ecparams->arena, PR_FALSE);
     }
     fclose(ecdsareq);
 }
 
 /*
  * Perform the ECDSA Signature Verification Test.
  *
  * reqfn is the pathname of the REQUEST file.
@@ -2355,231 +2743,220 @@ ecdsa_sigver_test(char *reqfn)
                          * needs to be large enough to hold the longest
                          * line "Msg = <256 hex digits>\n".
                          */
     FILE *ecdsareq;     /* input stream from the REQUEST file */
     FILE *ecdsaresp;    /* output stream to the RESPONSE file */
     char curve[16];     /* "nistxddd" */
     ECPublicKey ecpub;
     unsigned int i, j;
-    unsigned int flen;  /* length in bytes of the field size */
-    unsigned int olen;  /* length in bytes of the base point order */
+    unsigned int flen = 0;  /* length in bytes of the field size */
+    unsigned int olen = 0;  /* length in bytes of the base point order */
     unsigned char msg[512];  /* message that was signed (<= 128 bytes) */
-    unsigned int msglen;
-    unsigned char sha1[20];  /* SHA-1 hash (160 bits) */
+    unsigned int msglen = 0;
+    unsigned char  sha[HASH_LENGTH_MAX];    /* SHA digest */
+    unsigned int   shaLength = 0;           /* length of SHA */
+    HASH_HashType  shaAlg = HASH_AlgNULL;   /* type of SHA Alg */
     unsigned char sig[2*MAX_ECKEY_LEN];
     SECItem signature, digest;
     PRBool keyvalid = PR_TRUE;
     PRBool sigvalid = PR_TRUE;
 
     ecdsareq = fopen(reqfn, "r");
     ecdsaresp = stdout;
     ecpub.ecParams.arena = NULL;
     strcpy(curve, "nist");
     while (fgets(buf, sizeof buf, ecdsareq) != NULL) {
-	/* a comment or blank line */
-	if (buf[0] == '#' || buf[0] == '\n') {
-	    fputs(buf, ecdsaresp);
-	    continue;
-	}
-	/* [X-ddd] */
-	if (buf[0] == '[') {
-	    const char *src;
-	    char *dst;
-	    SECItem *encodedparams;
-	    ECParams *ecparams;
-
-	    src = &buf[1];
-	    dst = &curve[4];
-	    *dst++ = tolower(*src);
-	    src += 2;  /* skip the hyphen */
-	    *dst++ = *src++;
-	    *dst++ = *src++;
-	    *dst++ = *src++;
-	    *dst = '\0';
-	    encodedparams = getECParams(curve);
-	    if (encodedparams == NULL) {
-		goto loser;
-	    }
-	    if (EC_DecodeParams(encodedparams, &ecparams) != SECSuccess) {
-		goto loser;
-	    }
-	    SECITEM_FreeItem(encodedparams, PR_TRUE);
-	    if (ecpub.ecParams.arena != NULL) {
-		PORT_FreeArena(ecpub.ecParams.arena, PR_FALSE);
-	    }
-	    ecpub.ecParams.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
-	    if (ecpub.ecParams.arena == NULL) {
-		goto loser;
-	    }
-	    if (EC_CopyParams(ecpub.ecParams.arena, &ecpub.ecParams, ecparams)
-		!= SECSuccess) {
-		goto loser;
-	    }
-	    PORT_FreeArena(ecparams->arena, PR_FALSE);
-	    flen = (ecpub.ecParams.fieldID.size + 7) >> 3;
-	    olen = ecpub.ecParams.order.len;
-	    if (2*olen > sizeof sig) {
-		goto loser;
-	    }
-	    ecpub.publicValue.type = siBuffer;
-	    ecpub.publicValue.data = NULL;
-	    ecpub.publicValue.len = 0;
-	    SECITEM_AllocItem(ecpub.ecParams.arena,
-			      &ecpub.publicValue, 2*flen+1);
-	    if (ecpub.publicValue.data == NULL) {
-		goto loser;
-	    }
-	    ecpub.publicValue.data[0] = EC_POINT_FORM_UNCOMPRESSED;
-	    fputs(buf, ecdsaresp);
-	    continue;
-	}
-	/* Msg = ... */
-	if (strncmp(buf, "Msg", 3) == 0) {
-	    i = 3;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; isxdigit(buf[i]); i+=2,j++) {
-		hex_to_byteval(&buf[i], &msg[j]);
-	    }
-	    msglen = j;
-	    if (SHA1_HashBuf(sha1, msg, msglen) != SECSuccess) {
-		goto loser;
-	    }
-	    fputs(buf, ecdsaresp);
-
-	    digest.type = siBuffer;
-	    digest.data = sha1;
-	    digest.len = sizeof sha1;
-
-	    continue;
-	}
-	/* Qx = ... */
-	if (strncmp(buf, "Qx", 2) == 0) {
-	    fputs(buf, ecdsaresp);
-	    i = 2;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    keyvalid = from_hex_str(&ecpub.publicValue.data[1], flen,
-				    &buf[i]);
-	    continue;
-	}
-	/* Qy = ... */
-	if (strncmp(buf, "Qy", 2) == 0) {
-	    fputs(buf, ecdsaresp);
-	    if (!keyvalid) {
-		continue;
-	    }
-	    i = 2;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    keyvalid = from_hex_str(&ecpub.publicValue.data[1+flen], flen,
-				    &buf[i]);
-	    if (!keyvalid) {
-		continue;
-	    }
-	    if (EC_ValidatePublicKey(&ecpub.ecParams, &ecpub.publicValue)
-		!= SECSuccess) {
-		if (PORT_GetError() == SEC_ERROR_BAD_KEY) {
-		    keyvalid = PR_FALSE;
-		} else {
-		    goto loser;
-		}
-	    }
-	    continue;
-	}
-	/* R = ... */
-	if (buf[0] == 'R') {
-	    fputs(buf, ecdsaresp);
-	    i = 1;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    sigvalid = from_hex_str(sig, olen, &buf[i]);
-	    continue;
-	}
-	/* S = ... */
-	if (buf[0] == 'S') {
-	    fputs(buf, ecdsaresp);
-	    i = 1;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    if (sigvalid) {
-		sigvalid = from_hex_str(&sig[olen], olen, &buf[i]);
-	    }
-	    signature.type = siBuffer;
-	    signature.data = sig;
-	    signature.len = 2*olen;
-
-	    if (!keyvalid || !sigvalid) {
-		fputs("Result = F\n", ecdsaresp);
-	    } else if (ECDSA_VerifyDigest(&ecpub, &signature, &digest)
-		== SECSuccess) {
-		fputs("Result = P\n", ecdsaresp);
-	    } else {
-		fputs("Result = F\n", ecdsaresp);
-	    }
-	    continue;
-	}
+        /* a comment or blank line */
+        if (buf[0] == '#' || buf[0] == '\n') {
+            fputs(buf, ecdsaresp);
+            continue;
+        }
+        /* [X-ddd] */
+        if (buf[0] == '[') {
+            const char *src;
+            char *dst;
+            SECItem *encodedparams;
+            ECParams *ecparams;
+
+            src = &buf[1];
+            dst = &curve[4];
+            *dst++ = tolower(*src);
+            src += 2;  /* skip the hyphen */
+            *dst++ = *src++;
+            *dst++ = *src++;
+            *dst++ = *src++;
+            *dst = '\0';
+            src++; /* skip the comma */
+            /* set the SHA Algorithm */
+            if (strncmp(src, "SHA-1", 5) == 0) {
+                shaAlg = HASH_AlgSHA1;
+            } else if (strncmp(src, "SHA-224", 7) == 0) {
+                shaAlg = HASH_AlgSHA224;
+            } else if (strncmp(src, "SHA-256", 7) == 0) {
+                shaAlg = HASH_AlgSHA256;
+            } else if (strncmp(src, "SHA-384", 7)== 0) {
+               shaAlg = HASH_AlgSHA384;
+            } else if (strncmp(src, "SHA-512", 7) == 0) {
+               shaAlg = HASH_AlgSHA512;
+            } else {
+               fprintf(ecdsaresp, "ERROR: Unable to find SHAAlg type");
+               goto loser;
+            }
+            encodedparams = getECParams(curve);
+            if (encodedparams == NULL) {
+                fprintf(stderr, "Unknown curve %s.", curve);
+                goto loser;
+            }
+            if (EC_DecodeParams(encodedparams, &ecparams) != SECSuccess) {
+                fprintf(stderr, "Curve %s not supported.\n", curve);
+                goto loser;
+            }
+            SECITEM_FreeItem(encodedparams, PR_TRUE);
+            if (ecpub.ecParams.arena != NULL) {
+                PORT_FreeArena(ecpub.ecParams.arena, PR_FALSE);
+            }
+            ecpub.ecParams.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
+            if (ecpub.ecParams.arena == NULL) {
+                goto loser;
+            }
+            if (EC_CopyParams(ecpub.ecParams.arena, &ecpub.ecParams, ecparams)
+                != SECSuccess) {
+                goto loser;
+            }
+            PORT_FreeArena(ecparams->arena, PR_FALSE);
+            flen = (ecpub.ecParams.fieldID.size + 7) >> 3;
+            olen = ecpub.ecParams.order.len;
+            if (2*olen > sizeof sig) {
+                goto loser;
+            }
+            ecpub.publicValue.type = siBuffer;
+            ecpub.publicValue.data = NULL;
+            ecpub.publicValue.len = 0;
+            SECITEM_AllocItem(ecpub.ecParams.arena,
+                              &ecpub.publicValue, 2*flen+1);
+            if (ecpub.publicValue.data == NULL) {
+                goto loser;
+            }
+            ecpub.publicValue.data[0] = EC_POINT_FORM_UNCOMPRESSED;
+            fputs(buf, ecdsaresp);
+            continue;
+        }
+        /* Msg = ... */
+        if (strncmp(buf, "Msg", 3) == 0) {
+            i = 3;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; isxdigit(buf[i]); i+=2,j++) {
+                hex_to_byteval(&buf[i], &msg[j]);
+            }
+            msglen = j;
+            shaLength = fips_hashLen(shaAlg);
+            if (fips_hashBuf(shaAlg,sha,msg,msglen) != SECSuccess) {
+                if (shaLength == 0) {
+                        fprintf(ecdsaresp, "ERROR: SHAAlg not defined.");
+                }
+                fprintf(ecdsaresp, "ERROR: Unable to generate SHA%x",
+                        shaLength == 160 ? 1 : shaLength);
+                goto loser;
+            }
+            fputs(buf, ecdsaresp);
+
+            digest.type = siBuffer;
+            digest.data = sha;
+            digest.len = shaLength;
+
+            continue;
+        }
+        /* Qx = ... */
+        if (strncmp(buf, "Qx", 2) == 0) {
+            fputs(buf, ecdsaresp);
+            i = 2;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            keyvalid = from_hex_str(&ecpub.publicValue.data[1], flen,
+                                    &buf[i]);
+            continue;
+        }
+        /* Qy = ... */
+        if (strncmp(buf, "Qy", 2) == 0) {
+            fputs(buf, ecdsaresp);
+            if (!keyvalid) {
+                continue;
+            }
+            i = 2;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            keyvalid = from_hex_str(&ecpub.publicValue.data[1+flen], flen,
+                                    &buf[i]);
+            if (!keyvalid) {
+                continue;
+            }
+            if (EC_ValidatePublicKey(&ecpub.ecParams, &ecpub.publicValue)
+                != SECSuccess) {
+                if (PORT_GetError() == SEC_ERROR_BAD_KEY) {
+                    keyvalid = PR_FALSE;
+                } else {
+                    goto loser;
+                }
+            }
+            continue;
+        }
+        /* R = ... */
+        if (buf[0] == 'R') {
+            fputs(buf, ecdsaresp);
+            i = 1;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            sigvalid = from_hex_str(sig, olen, &buf[i]);
+            continue;
+        }
+        /* S = ... */
+        if (buf[0] == 'S') {
+            fputs(buf, ecdsaresp);
+            i = 1;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            if (sigvalid) {
+                sigvalid = from_hex_str(&sig[olen], olen, &buf[i]);
+            }
+            signature.type = siBuffer;
+            signature.data = sig;
+            signature.len = 2*olen;
+
+            if (!keyvalid || !sigvalid) {
+                fputs("Result = F\n", ecdsaresp);
+            } else if (ECDSA_VerifyDigest(&ecpub, &signature, &digest)
+                == SECSuccess) {
+                fputs("Result = P\n", ecdsaresp);
+            } else {
+                fputs("Result = F\n", ecdsaresp);
+            }
+            continue;
+        }
     }
 loser:
     if (ecpub.ecParams.arena != NULL) {
-	PORT_FreeArena(ecpub.ecParams.arena, PR_FALSE);
+        PORT_FreeArena(ecpub.ecParams.arena, PR_FALSE);
     }
     fclose(ecdsareq);
 }
 #endif /* NSS_DISABLE_ECC */
 
-
-/*
- * Read a value from the test and allocate the result.
- */
-static unsigned char *
-alloc_value(char *buf, int *len)
-{
-    unsigned char * value;
-    int i, count;
-
-    if (strncmp(buf, "<None>", 6) == 0) {
-	*len = 0;
-	return NULL;
-    }
-
-    /* find the length of the number */
-    for (count = 0; isxdigit(buf[count]); count++);
-    *len = count/2;
-
-    if (*len == 0) {
-	return NULL;
-    }
-
-    value = PORT_Alloc(*len);
-    if (!value) {
-	*len = 0;
-	return NULL;
-    }
-	
-    for (i=0; i<*len; buf+=2 , i++) {
-	hex_to_byteval(buf, &value[i]);
-    }
-    
-
-    return value;
-}
-
 PRBool
 isblankline(char *b)
 {
    while (isspace(*b)) b++;
    if ((*b == '\n') || (*b == 0)) {
-	return PR_TRUE;
+        return PR_TRUE;
    }
    return PR_FALSE;
 }
 
 static int debug = 0;
 
 /*
  * Perform the Hash_DRBG (CAVS) for the RNG algorithm
@@ -2594,112 +2971,114 @@ drbg(char *reqfn)
     char buf[2000];   /* test case has some very long lines, returned bits
      * as high as 800 bytes (6400 bits). That 1600 byte
      * plus a tag */
     char buf2[2000]; 
     FILE *rngreq;       /* input stream from the REQUEST file */
     FILE *rngresp;      /* output stream to the RESPONSE file */
     
     unsigned int i, j;
+#ifdef HANDLE_PREDICTION_RESISTANCE
     PRBool predictionResistance = PR_FALSE;
+#endif
     unsigned char *nonce =  NULL;
     int nonceLen = 0;
     unsigned char *personalizationString =  NULL;
     int personalizationStringLen = 0;
     unsigned char *additionalInput =  NULL;
     int additionalInputLen = 0;
     unsigned char *entropyInput = NULL;
     int entropyInputLen = 0;
-    unsigned char predictedreturn_bytes[SHA256_LENGTH];
-    unsigned char return_bytes[SHA256_LENGTH];
-    int return_bytes_len = SHA256_LENGTH;
+    unsigned char *predictedreturn_bytes = NULL;
+    unsigned char *return_bytes = NULL;
+    int return_bytes_len = 0;
     enum { NONE, INSTANTIATE, GENERATE, RESEED, RESULT } command =
     NONE;
     PRBool genResult = PR_FALSE;
     SECStatus rv;
     
     rngreq = fopen(reqfn, "r");
     rngresp = stdout;
     while (fgets(buf, sizeof buf, rngreq) != NULL) {
        switch (command) {
             case INSTANTIATE:
-		if (debug) {
-		    fputs("# PRNGTEST_Instantiate(",rngresp);
-		    to_hex_str(buf2,entropyInput, entropyInputLen);
-		    fputs(buf2,rngresp);
-		    fprintf(rngresp,",%d,",entropyInputLen);
-		    to_hex_str(buf2,nonce, nonceLen);
-		    fputs(buf2,rngresp);
-		    fprintf(rngresp,",%d,",nonceLen);
-		    to_hex_str(buf2,personalizationString, 
-					personalizationStringLen);
-		    fputs(buf2,rngresp);
-		    fprintf(rngresp,",%d)\n", personalizationStringLen);
-		}
+                if (debug) {
+                    fputs("# PRNGTEST_Instantiate(",rngresp);
+                    to_hex_str(buf2,entropyInput, entropyInputLen);
+                    fputs(buf2,rngresp);
+                    fprintf(rngresp,",%d,",entropyInputLen);
+                    to_hex_str(buf2,nonce, nonceLen);
+                    fputs(buf2,rngresp);
+                    fprintf(rngresp,",%d,",nonceLen);
+                    to_hex_str(buf2,personalizationString, 
+                                        personalizationStringLen);
+                    fputs(buf2,rngresp);
+                    fprintf(rngresp,",%d)\n", personalizationStringLen);
+                }
                 rv = PRNGTEST_Instantiate(entropyInput, entropyInputLen,
                                           nonce, nonceLen,
                                           personalizationString, 
-				          personalizationStringLen);
+                                          personalizationStringLen);
                 if (rv != SECSuccess) {
                     goto loser;
                 }
                 break;
                     
             case GENERATE:
             case RESULT:
                 memset(return_bytes, 0, return_bytes_len);
-		if (debug) {
-		    fputs("# PRNGTEST_Generate(returnbytes",rngresp);
-		    fprintf(rngresp,",%d,", return_bytes_len);
-		    to_hex_str(buf2,additionalInput, additionalInputLen);
-		    fputs(buf2,rngresp);
-		    fprintf(rngresp,",%d)\n",additionalInputLen);
-		}
+                if (debug) {
+                    fputs("# PRNGTEST_Generate(returnbytes",rngresp);
+                    fprintf(rngresp,",%d,", return_bytes_len);
+                    to_hex_str(buf2,additionalInput, additionalInputLen);
+                    fputs(buf2,rngresp);
+                    fprintf(rngresp,",%d)\n",additionalInputLen);
+                }
                 rv = PRNGTEST_Generate((PRUint8 *) return_bytes, 
-					return_bytes_len,
+                                        return_bytes_len,
                                        (PRUint8 *) additionalInput, 
-					additionalInputLen);
+                                        additionalInputLen);
                 if (rv != SECSuccess) {
                     goto loser;
                 }
                     
                 if (command == RESULT) {
                     fputs("ReturnedBits = ", rngresp);
                     to_hex_str(buf2, return_bytes, return_bytes_len);
                     fputs(buf2, rngresp);
                     fputc('\n', rngresp);
-		    if (debug) {
-			fputs("# PRNGTEST_Uninstantiate()\n",rngresp);
-		    }
+                    if (debug) {
+                        fputs("# PRNGTEST_Uninstantiate()\n",rngresp);
+                    }
                     rv = PRNGTEST_Uninstantiate();
                     if (rv != SECSuccess) {
                         goto loser;
                     }
                 } else if (debug) {
                     fputs("#ReturnedBits = ", rngresp);
                     to_hex_str(buf2, return_bytes, return_bytes_len);
                     fputs(buf2, rngresp);
                     fputc('\n', rngresp);
-		}
+                }
                     
                 memset(additionalInput, 0, additionalInputLen);
                 break;
                     
             case RESEED:
                 if (entropyInput || additionalInput) {
-		    if (debug) {
-			fputs("# PRNGTEST_Reseed(",rngresp);
-			fprintf(rngresp,",%d,", return_bytes_len);
-			to_hex_str(buf2,entropyInput, entropyInputLen);
-			fputs(buf2,rngresp);
-			fprintf(rngresp,",%d,", entropyInputLen);
-			to_hex_str(buf2,additionalInput, additionalInputLen);
-			fputs(buf2,rngresp);
-			fprintf(rngresp,",%d)\n",additionalInputLen);
-		    }	
+                    if (debug) {
+                        fputs("# PRNGTEST_Reseed(",rngresp);
+                        fprintf(rngresp,",%d,", return_bytes_len);
+                        to_hex_str(buf2,entropyInput, entropyInputLen);
+                        fputs(buf2,rngresp);
+                        fprintf(rngresp,",%d,", entropyInputLen);
+                        to_hex_str(buf2,additionalInput, additionalInputLen);
+                        fputs(buf2,rngresp);
+                        fprintf(rngresp,",%d)\n",additionalInputLen);
+                    }        
                     rv = PRNGTEST_Reseed(entropyInput, entropyInputLen,
                                              additionalInput, additionalInputLen);
                     if (rv != SECSuccess) {
                         goto loser;
                     }
                 }
                 memset(entropyInput, 0, entropyInputLen);
                 memset(additionalInput, 0, additionalInputLen);
@@ -2718,40 +3097,64 @@ drbg(char *reqfn)
         
         /* [Hash - SHA256] */
         if (strncmp(buf, "[SHA-256]", 9) == 0) {
             fputs(buf, rngresp);
             continue;
         }
         
         if (strncmp(buf, "[PredictionResistance", 21)  == 0) {
+#ifdef HANDLE_PREDICTION_RESISTANCE
             i = 21;
             while (isspace(buf[i]) || buf[i] == '=') {
                 i++;
             }    
             if (strncmp(buf, "False", 5) == 0) {
                 predictionResistance = PR_FALSE;
             } else {
                 predictionResistance = PR_TRUE;
             }
+#endif
             
             fputs(buf, rngresp);
             continue;
         }
+
+        if (strncmp(buf, "[ReturnedBitsLen", 16)  == 0) {
+            if (return_bytes) {
+                PORT_ZFree(return_bytes, return_bytes_len);
+                return_bytes = NULL;
+            }
+	    if (predictedreturn_bytes) {
+                PORT_ZFree(predictedreturn_bytes, return_bytes_len);
+                predictedreturn_bytes = NULL;
+            }
+            return_bytes_len = 0;
+            if (sscanf(buf, "[ReturnedBitsLen = %d]", &return_bytes_len) != 1) {
+                goto loser;
+            }
+            return_bytes_len = return_bytes_len/8;
+            if (return_bytes_len > 0) {
+                return_bytes = PORT_Alloc(return_bytes_len);
+                predictedreturn_bytes = PORT_Alloc(return_bytes_len);
+            }
+            fputs(buf, rngresp);
+            continue;
+        }
         
         if (strncmp(buf, "[EntropyInputLen", 16)  == 0) {
             if (entropyInput) {
                 PORT_ZFree(entropyInput, entropyInputLen);
                 entropyInput = NULL;
                 entropyInputLen = 0;
             }
             if (sscanf(buf, "[EntropyInputLen = %d]", &entropyInputLen) != 1) {
                 goto loser;
             }
-	    entropyInputLen = entropyInputLen/8;
+            entropyInputLen = entropyInputLen/8;
             if (entropyInputLen > 0) {
                 entropyInput = PORT_Alloc(entropyInputLen);
             }
             fputs(buf, rngresp);
             continue;
         }
         
         if (strncmp(buf, "[NonceLen", 9)  == 0) {
@@ -2759,17 +3162,17 @@ drbg(char *reqfn)
                 PORT_ZFree(nonce, nonceLen);
                 nonce = NULL;
                 nonceLen = 0;
             }
             
             if (sscanf(buf, "[NonceLen = %d]", &nonceLen) != 1) {
                 goto loser;
             }
-	    nonceLen = nonceLen/8;
+            nonceLen = nonceLen/8;
             if (nonceLen > 0) {
                 nonce = PORT_Alloc(nonceLen);
             }               
             fputs(buf, rngresp);
             continue;
         }
         
         if (strncmp(buf, "[PersonalizationStringLen", 16)  == 0) {
@@ -2777,17 +3180,17 @@ drbg(char *reqfn)
                 PORT_ZFree(personalizationString, personalizationStringLen);
                 personalizationString = NULL;
                 personalizationStringLen = 0;
             }
             
             if (sscanf(buf, "[PersonalizationStringLen = %d]", &personalizationStringLen) != 1) {
                 goto loser;
             }
-	    personalizationStringLen = personalizationStringLen / 8;
+            personalizationStringLen = personalizationStringLen / 8;
             if (personalizationStringLen > 0) {
                 personalizationString = PORT_Alloc(personalizationStringLen);
             }
             fputs(buf, rngresp);
             
             continue;
         }
         
@@ -2796,17 +3199,17 @@ drbg(char *reqfn)
                 PORT_ZFree(additionalInput, additionalInputLen);
                 additionalInput = NULL;
                 additionalInputLen = 0;
             }
             
             if (sscanf(buf, "[AdditionalInputLen = %d]", &additionalInputLen) != 1) {
                 goto loser;
             }
-	    additionalInputLen = additionalInputLen/8;
+            additionalInputLen = additionalInputLen/8;
             if (additionalInputLen > 0) {
                 additionalInput = PORT_Alloc(additionalInputLen);
             }
             fputs(buf, rngresp);
             continue;
         }
         
         if (strncmp(buf, "COUNT", 5) == 0) {
@@ -2933,38 +3336,38 @@ drbg(char *reqfn)
                 i++;
             }
             for (j=0; isxdigit(buf[i]); i+=2,j++) { /*j<additionalInputLen*/
                 hex_to_byteval(&buf[i], &predictedreturn_bytes[j]);
             }          
 
             if (memcmp(return_bytes, 
                        predictedreturn_bytes, return_bytes_len) != 0) {
-		if (debug) {
+                if (debug) {
                 fprintf(rngresp, "# Generate failed:\n");
                 fputs(  "#   predicted=", rngresp);
                 to_hex_str(buf, predictedreturn_bytes, 
                            return_bytes_len);
                 fputs(buf, rngresp);
                 fputs("\n#   actual  = ", rngresp);
                 fputs(buf2, rngresp);
                 fputc('\n', rngresp);
 
-		} else {
+                } else {
                 fprintf(stderr, "Generate failed:\n");
                 fputs(  "   predicted=", stderr);
                 to_hex_str(buf, predictedreturn_bytes, 
                            return_bytes_len);
                 fputs(buf, stderr);
                 fputs("\n   actual  = ", stderr);
                 fputs(buf2, stderr);
                 fputc('\n', stderr);
-		}
-            }
-            memset(predictedreturn_bytes, 0 , sizeof predictedreturn_bytes);
+                }
+            }
+            memset(predictedreturn_bytes, 0 , return_bytes_len);
 
             continue;
         }
     }
 loser:
     fclose(rngreq);
 }
 
@@ -2985,112 +3388,112 @@ rng_vst(char *reqfn)
                          * needs to be large enough to hold the longest
                          * line "XSeed = <128 hex digits>\n".
                          */
     FILE *rngreq;       /* input stream from the REQUEST file */
     FILE *rngresp;      /* output stream to the RESPONSE file */
     unsigned int i, j;
     unsigned char Q[DSA1_SUBPRIME_LEN];
     PRBool hasQ = PR_FALSE;
-    unsigned int b;  /* 160 <= b <= 512, b is a multiple of 8 */
+    unsigned int b = 0;  /* 160 <= b <= 512, b is a multiple of 8 */
     unsigned char XKey[512/8];
     unsigned char XSeed[512/8];
     unsigned char GENX[DSA1_SIGNATURE_LEN];
     unsigned char DSAX[DSA1_SUBPRIME_LEN];
     SECStatus rv;
 
     rngreq = fopen(reqfn, "r");
     rngresp = stdout;
     while (fgets(buf, sizeof buf, rngreq) != NULL) {
-	/* a comment or blank line */
-	if (buf[0] == '#' || buf[0] == '\n') {
-	    fputs(buf, rngresp);
-	    continue;
-	}
-	/* [Xchange - SHA1] */
-	if (buf[0] == '[') {
-	    fputs(buf, rngresp);
-	    continue;
-	}
-	/* Q = ... */
-	if (buf[0] == 'Q') {
-	    i = 1;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; j<sizeof Q; i+=2,j++) {
-		hex_to_byteval(&buf[i], &Q[j]);
-	    }
-	    fputs(buf, rngresp);
-	    hasQ = PR_TRUE;
-	    continue;
-	}
-	/* "COUNT = x" begins a new data set */
-	if (strncmp(buf, "COUNT", 5) == 0) {
-	    /* zeroize the variables for the test with this data set */
-	    b = 0;
-	    memset(XKey, 0, sizeof XKey);
-	    memset(XSeed, 0, sizeof XSeed);
-	    fputs(buf, rngresp);
-	    continue;
-	}
-	/* b = ... */
-	if (buf[0] == 'b') {
-	    i = 1;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    b = atoi(&buf[i]);
-	    if (b < 160 || b > 512 || b%8 != 0) {
-		goto loser;
-	    }
-	    fputs(buf, rngresp);
-	    continue;
-	}
-	/* XKey = ... */
-	if (strncmp(buf, "XKey", 4) == 0) {
-	    i = 4;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; j<b/8; i+=2,j++) {
-		hex_to_byteval(&buf[i], &XKey[j]);
-	    }
-	    fputs(buf, rngresp);
-	    continue;
-	}
-	/* XSeed = ... */
-	if (strncmp(buf, "XSeed", 5) == 0) {
-	    i = 5;
-	    while (isspace(buf[i]) || buf[i] == '=') {
-		i++;
-	    }
-	    for (j=0; j<b/8; i+=2,j++) {
-		hex_to_byteval(&buf[i], &XSeed[j]);
-	    }
-	    fputs(buf, rngresp);
-
-	    rv = FIPS186Change_GenerateX(XKey, XSeed, GENX);
-	    if (rv != SECSuccess) {
-		goto loser;
-	    }
-	    fputs("X = ", rngresp);
-	    if (hasQ) {
-		rv = FIPS186Change_ReduceModQForDSA(GENX, Q, DSAX);
-		if (rv != SECSuccess) {
-		    goto loser;
-		}
-		to_hex_str(buf, DSAX, sizeof DSAX);
-	    } else {
-		to_hex_str(buf, GENX, sizeof GENX);
-	    }
-	    fputs(buf, rngresp);
-	    fputc('\n', rngresp);
-	    continue;
-	}
+        /* a comment or blank line */
+        if (buf[0] == '#' || buf[0] == '\n') {
+            fputs(buf, rngresp);
+            continue;
+        }
+        /* [Xchange - SHA1] */
+        if (buf[0] == '[') {
+            fputs(buf, rngresp);
+            continue;
+        }
+        /* Q = ... */
+        if (buf[0] == 'Q') {
+            i = 1;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<sizeof Q; i+=2,j++) {
+                hex_to_byteval(&buf[i], &Q[j]);
+            }
+            fputs(buf, rngresp);
+            hasQ = PR_TRUE;
+            continue;
+        }
+        /* "COUNT = x" begins a new data set */
+        if (strncmp(buf, "COUNT", 5) == 0) {
+            /* zeroize the variables for the test with this data set */
+            b = 0;
+            memset(XKey, 0, sizeof XKey);
+            memset(XSeed, 0, sizeof XSeed);
+            fputs(buf, rngresp);
+            continue;
+        }
+        /* b = ... */
+        if (buf[0] == 'b') {
+            i = 1;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            b = atoi(&buf[i]);
+            if (b < 160 || b > 512 || b%8 != 0) {
+                goto loser;
+            }
+            fputs(buf, rngresp);
+            continue;
+        }
+        /* XKey = ... */
+        if (strncmp(buf, "XKey", 4) == 0) {
+            i = 4;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<b/8; i+=2,j++) {
+                hex_to_byteval(&buf[i], &XKey[j]);
+            }
+            fputs(buf, rngresp);
+            continue;
+        }
+        /* XSeed = ... */
+        if (strncmp(buf, "XSeed", 5) == 0) {
+            i = 5;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<b/8; i+=2,j++) {
+                hex_to_byteval(&buf[i], &XSeed[j]);
+            }
+            fputs(buf, rngresp);
+
+            rv = FIPS186Change_GenerateX(XKey, XSeed, GENX);
+            if (rv != SECSuccess) {
+                goto loser;
+            }
+            fputs("X = ", rngresp);
+            if (hasQ) {
+                rv = FIPS186Change_ReduceModQForDSA(GENX, Q, DSAX);
+                if (rv != SECSuccess) {
+                    goto loser;
+                }
+                to_hex_str(buf, DSAX, sizeof DSAX);
+            } else {
+                to_hex_str(buf, GENX, sizeof GENX);
+            }
+            fputs(buf, rngresp);
+            fputc('\n', rngresp);
+            continue;
+        }
     }
 loser:
     fclose(rngreq);
 }
 
 /*
  * Perform the RNG Monte Carlo Test (MCT) for the RNG algorithm
  * "DSA - Generation of X", used both as specified and as a generic
@@ -3108,17 +3511,17 @@ rng_mct(char *reqfn)
                          * needs to be large enough to hold the longest
                          * line "XSeed = <128 hex digits>\n".
                          */
     FILE *rngreq;       /* input stream from the REQUEST file */
     FILE *rngresp;      /* output stream to the RESPONSE file */
     unsigned int i, j;
     unsigned char Q[DSA1_SUBPRIME_LEN];
     PRBool hasQ = PR_FALSE;
-    unsigned int b;  /* 160 <= b <= 512, b is a multiple of 8 */
+    unsigned int b = 0;  /* 160 <= b <= 512, b is a multiple of 8 */
     unsigned char XKey[512/8];
     unsigned char XSeed[512/8];
     unsigned char GENX[2*SHA1_LENGTH];
     unsigned char DSAX[DSA1_SUBPRIME_LEN];
     SECStatus rv;
 
     rngreq = fopen(reqfn, "r");
     rngresp = stdout;
@@ -3213,131 +3616,16 @@ rng_mct(char *reqfn)
 	    continue;
 	}
     }
 loser:
     fclose(rngreq);
 }
 
 /*
- * HASH_ functions are available to full NSS apps and internally inside
- * freebl, but not exported to users of freebl. Create short stubs to
- * replace the functionality for fipstest.
- */
-SECStatus
-fips_hashBuf(HASH_HashType type, unsigned char *hashBuf, 
-					unsigned char *msg, int len)
-{
-    SECStatus rv = SECFailure;
-
-    switch (type) {
-    case HASH_AlgSHA1:
-	rv = SHA1_HashBuf(hashBuf, msg, len);
-	break;
-    case HASH_AlgSHA224:
-	rv = SHA224_HashBuf(hashBuf, msg, len);
-	break;
-    case HASH_AlgSHA256:
-	rv = SHA256_HashBuf(hashBuf, msg, len);
-	break;
-    case HASH_AlgSHA384:
-	rv = SHA384_HashBuf(hashBuf, msg, len);
-	break;
-    case HASH_AlgSHA512:
-	rv = SHA512_HashBuf(hashBuf, msg, len);
-	break;
-    default:
-	break;
-    }
-    return rv;
-}
-
-int
-fips_hashLen(HASH_HashType type)
-{
-    int len = 0;
-
-    switch (type) {
-    case HASH_AlgSHA1:
-	len = SHA1_LENGTH;
-	break;
-    case HASH_AlgSHA224:
-	len = SHA224_LENGTH;
-	break;
-    case HASH_AlgSHA256:
-	len = SHA256_LENGTH;
-	break;
-    case HASH_AlgSHA384:
-	len = SHA384_LENGTH;
-	break;
-    case HASH_AlgSHA512:
-	len = SHA512_LENGTH;
-	break;
-    default:
-	break;
-    }
-    return len;
-}
-
-SECOidTag
-fips_hashOid(HASH_HashType type)
-{
-    SECOidTag oid = SEC_OID_UNKNOWN;
-
-    switch (type) {
-    case HASH_AlgSHA1:
-	oid = SEC_OID_SHA1;
-	break;
-    case HASH_AlgSHA224:
-	oid = SEC_OID_SHA224;
-	break;
-    case HASH_AlgSHA256:
-	oid = SEC_OID_SHA256;
-	break;
-    case HASH_AlgSHA384:
-	oid = SEC_OID_SHA384;
-	break;
-    case HASH_AlgSHA512:
-	oid = SEC_OID_SHA512;
-	break;
-    default:
-	break;
-    }
-    return oid;
-}
-
-HASH_HashType
-sha_get_hashType(int hashbits)
-{
-    HASH_HashType hashType = HASH_AlgNULL;
-
-    switch (hashbits) {
-    case 1:
-    case (SHA1_LENGTH*PR_BITS_PER_BYTE):
-	hashType = HASH_AlgSHA1;
-	break;
-    case (SHA224_LENGTH*PR_BITS_PER_BYTE):
-	hashType = HASH_AlgSHA224;
-	break;
-    case (SHA256_LENGTH*PR_BITS_PER_BYTE):
-	hashType = HASH_AlgSHA256;
-	break;
-    case (SHA384_LENGTH*PR_BITS_PER_BYTE):
-	hashType = HASH_AlgSHA384;
-	break;
-    case (SHA512_LENGTH*PR_BITS_PER_BYTE):
-	hashType = HASH_AlgSHA512;
-	break;
-    default:
-	break;
-    }
-    return hashType;
-}
-
-/*
  * Calculate the SHA Message Digest 
  *
  * MD = Message digest 
  * MDLen = length of Message Digest and SHA_Type
  * msg = message to digest 
  * msgLen = length of message to digest
  */
 SECStatus sha_calcMD(unsigned char *MD, unsigned int MDLen, unsigned char *msg, unsigned int msgLen) 
@@ -3411,20 +3699,20 @@ SECStatus sha_mct_test(unsigned int MDLe
  *
  * reqfn is the pathname of the input REQUEST file.
  *
  * The output RESPONSE file is written to stdout.
  */
 void sha_test(char *reqfn) 
 {
     unsigned int i, j;
-    unsigned int MDlen;   /* the length of the Message Digest in Bytes  */
-    unsigned int msgLen;  /* the length of the input Message in Bytes */
+    unsigned int MDlen = 0;   /* the length of the Message Digest in Bytes  */
+    unsigned int msgLen = 0;  /* the length of the input Message in Bytes */
     unsigned char *msg = NULL; /* holds the message to digest.*/
-    size_t bufSize = 25608; /*MAX buffer size */
+    size_t bufSize = 256*128; /*MAX buffer size */
     char *buf = NULL;      /* holds one line from the input REQUEST file.*/
     unsigned char seed[HASH_LENGTH_MAX];   /* max size of seed 64 bytes */
     unsigned char MD[HASH_LENGTH_MAX];     /* message digest */
 
     FILE *req = NULL;  /* input stream from the REQUEST file */
     FILE *resp;        /* output stream to the RESPONSE file */
 
     buf = PORT_ZAlloc(bufSize);
@@ -3589,28 +3877,28 @@ hmac_calc(unsigned char *hmac_computed,
  *
  * The output RESPONSE file is written to stdout.
  */
 void hmac_test(char *reqfn) 
 {
     unsigned int i, j;
     size_t bufSize =      400;    /* MAX buffer size */
     char *buf = NULL;  /* holds one line from the input REQUEST file.*/
-    unsigned int keyLen;          /* Key Length */  
+    unsigned int keyLen = 0;      /* Key Length */  
     unsigned char key[200];       /* key MAX size = 184 */
     unsigned int msgLen = 128;    /* the length of the input  */
                                   /*  Message is always 128 Bytes */
     unsigned char *msg = NULL;    /* holds the message to digest.*/
-    unsigned int HMACLen;         /* the length of the HMAC Bytes  */
-    unsigned int TLen;            /* the length of the requested */
+    unsigned int HMACLen = 0;     /* the length of the HMAC Bytes  */
+    unsigned int TLen = 0;        /* the length of the requested */
                                   /* truncated HMAC Bytes */
     unsigned char HMAC[HASH_LENGTH_MAX];  /* computed HMAC */
     unsigned char expectedHMAC[HASH_LENGTH_MAX]; /* for .fax files that have */ 
                                                  /* supplied known answer */
-    HASH_HashType hash_alg;       /* HMAC type */
+    HASH_HashType hash_alg = HASH_AlgNULL;       /* HMAC type */
     
 
     FILE *req = NULL;  /* input stream from the REQUEST file */
     FILE *resp;        /* output stream to the RESPONSE file */
 
     buf = PORT_ZAlloc(bufSize);
     if (buf == NULL) {
         goto loser;
@@ -3721,17 +4009,17 @@ void hmac_test(char *reqfn)
                 hex_to_byteval(&buf[i], &msg[j]);
             }
            fputs(buf, resp);
            /* calculate the HMAC and output */ 
            if (hmac_calc(HMAC, HMACLen, key, keyLen,   
                          msg, msgLen, hash_alg) != SECSuccess) {
                goto loser;
            }
-           fputs("MAC = ", resp);
+           fputs("Mac = ", resp);
            to_hex_str(buf, HMAC, TLen);
            fputs(buf, resp);
            fputc('\n', resp);
            continue;
         }
     }
 loser:
     if (req) {
@@ -3786,48 +4074,48 @@ dsa_keypair_test(char *reqfn)
                 pqg = NULL;
             }
             if(vfy!=NULL) {
                 PQG_DestroyVerify(vfy);
                 vfy = NULL;
             }
 
             if (sscanf(buf, "[mod = L=%d, N=%d]", &L, &N) != 2) {
-		use_dsa1 = PR_TRUE;
+                use_dsa1 = PR_TRUE;
                 if (sscanf(buf, "[mod = %d]", &L) != 1) {
                     goto loser;
-		}
+                }
             }
             fputs(buf, dsaresp);
             fputc('\n', dsaresp);
 
-	    if (use_dsa1) {
+            if (use_dsa1) {
                 /*************************************************************
                  * PQG_ParamGenSeedLen doesn't take a key size, it takes an 
-		 * index that points to a valid key size.
+                 * index that points to a valid key size.
                  */
                 keySizeIndex = PQG_PBITS_TO_INDEX(L);
                 if(keySizeIndex == -1 || L<512 || L>1024) {
                    fprintf(dsaresp,
                         "DSA key size must be a multiple of 64 between 512 "
                         "and 1024, inclusive");
                     goto loser;
                 }
 
                 /* Generate the parameters P, Q, and G */
                 if (PQG_ParamGenSeedLen(keySizeIndex, PQG_TEST_SEED_BYTES,
                     &pqg, &vfy) != SECSuccess) {
                     fprintf(dsaresp, 
-				"ERROR: Unable to generate PQG parameters");
+                                "ERROR: Unable to generate PQG parameters");
                     goto loser;
                 }
-	    } else {
+            } else {
                 if (PQG_ParamGenV2(L, N, N, &pqg, &vfy) != SECSuccess) {
                     fprintf(dsaresp, 
-				"ERROR: Unable to generate PQG parameters");
+                                "ERROR: Unable to generate PQG parameters");
                     goto loser;
                 }
             }
 
             /* output P, Q, and G */
             to_hex_str(buf, pqg->prime.data, pqg->prime.len);
             fprintf(dsaresp, "P = %s\n", buf);
             to_hex_str(buf, pqg->subPrime.data, pqg->subPrime.len);
@@ -3866,17 +4154,17 @@ loser:
     fclose(dsareq);
 }
 
 /*
  * pqg generation type
  */
 typedef enum {
     FIPS186_1,/* Generate/Verify P,Q & G  according to FIPS 186-1 */
-    A_1_1_2, /* Generate Probable P & Q */
+    A_1_2_1, /* Generate Provable P & Q */
     A_1_1_3, /* Verify Probable P & Q */
     A_1_2_2, /* Verify Provable P & Q */
     A_2_1,   /* Generate Unverifiable G */
     A_2_2,   /* Assure Unverifiable G */
     A_2_3,   /* Generate Verifiable G */
     A_2_4    /* Verify Verifiable G */
 } dsa_pqg_type;
 
@@ -3896,17 +4184,17 @@ dsa_pqgver_test(char *reqfn)
                          */
     FILE *dsareq;     /* input stream from the REQUEST file */
     FILE *dsaresp;    /* output stream to the RESPONSE file */
     int N;
     int L;
     unsigned int i, j;
     PQGParams pqg;
     PQGVerify vfy;
-    unsigned int pghSize;        /* size for p, g, and h */
+    unsigned int pghSize = 0;    /* size for p, g, and h */
     dsa_pqg_type type = FIPS186_1;
 
     dsareq = fopen(reqfn, "r");
     dsaresp = stdout;
     memset(&pqg, 0, sizeof(pqg));
     memset(&vfy, 0, sizeof(vfy));
 
     while (fgets(buf, sizeof buf, dsareq) != NULL) {
@@ -3914,47 +4202,47 @@ dsa_pqgver_test(char *reqfn)
         if (buf[0] == '#' || buf[0] == '\n') {
             fputs(buf, dsaresp);
             continue;
         }
 
         /* [A.xxxxx ] */
         if (buf[0] == '['  && buf[1] == 'A') {
 
-	    if (strncmp(&buf[1],"A.1.1.3",7) == 0) {
-		type = A_1_1_3;
-	    } else if (strncmp(&buf[1],"A.2.2",5) == 0) {
-		type = A_2_2;
-	    } else if (strncmp(&buf[1],"A.2.4",5) == 0) {
-		type = A_2_4;
-	    } else if (strncmp(&buf[1],"A.1.2.2",7) == 0) {
-		type = A_1_2_2;
-	    /* validate our output from PQGGEN */
-	    } else if (strncmp(&buf[1],"A.1.1.2",7) == 0) {
-		type = A_2_4; /* validate PQ and G together */
-	    } else {
-		fprintf(stderr, "Unknown dsa ver test %s\n", &buf[1]);
-		exit(1);
-	    }
-		
+            if (strncmp(&buf[1],"A.1.1.3",7) == 0) {
+                type = A_1_1_3;
+            } else if (strncmp(&buf[1],"A.2.2",5) == 0) {
+                type = A_2_2;
+            } else if (strncmp(&buf[1],"A.2.4",5) == 0) {
+                type = A_2_4;
+            } else if (strncmp(&buf[1],"A.1.2.2",7) == 0) {
+                type = A_1_2_2;
+            /* validate our output from PQGGEN */
+            } else if (strncmp(&buf[1],"A.1.1.2",7) == 0) {
+                type = A_2_4; /* validate PQ and G together */
+            } else {
+                fprintf(stderr, "Unknown dsa ver test %s\n", &buf[1]);
+                exit(1);
+            }
+                
             fputs(buf, dsaresp);
             continue;
         }
-	
+        
 
         /* [Mod = x] */
         if (buf[0] == '[') {
 
-	    if (type == FIPS186_1) {
+            if (type == FIPS186_1) {
                 N=160;
                 if (sscanf(buf, "[mod = %d]", &L) != 1) {
                     goto loser;
-		}
-	    } else if (sscanf(buf, "[mod = L=%d, N=%d", &L, &N) != 2) {
-		goto loser;
+                }
+            } else if (sscanf(buf, "[mod = L=%d, N=%d", &L, &N) != 2) {
+                goto loser;
             }
 
             if (pqg.prime.data) { /* P */
                 SECITEM_ZfreeItem(&pqg.prime, PR_FALSE);
             }
             if (pqg.subPrime.data) { /* Q */
                 SECITEM_ZfreeItem(&pqg.subPrime, PR_FALSE);
             }
@@ -3968,27 +4256,27 @@ dsa_pqgver_test(char *reqfn)
                 SECITEM_ZfreeItem(&vfy.h, PR_FALSE);
             }
 
             fputs(buf, dsaresp);
 
             /*calculate the size of p, g, and h then allocate items  */
             pghSize = L/8;
 
-	    pqg.base.data = vfy.h.data = NULL;
-	    vfy.seed.len = pqg.base.len = vfy.h.len = 0;
+            pqg.base.data = vfy.h.data = NULL;
+            vfy.seed.len = pqg.base.len = vfy.h.len = 0;
             SECITEM_AllocItem(NULL, &pqg.prime, pghSize);
             SECITEM_AllocItem(NULL, &vfy.seed, pghSize*3);
-	    if (type == A_2_2) {
-		SECITEM_AllocItem(NULL, &vfy.h, pghSize);
-	    	vfy.h.len = pghSize;
-	    } else if (type == A_2_4) {
-		SECITEM_AllocItem(NULL, &vfy.h, 1);
-	    	vfy.h.len = 1;
-	    }
+            if (type == A_2_2) {
+                SECITEM_AllocItem(NULL, &vfy.h, pghSize);
+                    vfy.h.len = pghSize;
+            } else if (type == A_2_4) {
+                SECITEM_AllocItem(NULL, &vfy.h, 1);
+                    vfy.h.len = 1;
+            }
             pqg.prime.len = pghSize;
             /* q is always N bits */
             SECITEM_AllocItem(NULL, &pqg.subPrime, N/8);
             pqg.subPrime.len = N/8;
             vfy.counter = -1;
 
             continue;
         }
@@ -4037,150 +4325,150 @@ dsa_pqgver_test(char *reqfn)
             fputs(buf, dsaresp);
             continue;
         }
 
         /* Seed = ...  or domain_parameter_seed = ... */
         if (strncmp(buf, "Seed", 4) == 0) {
             i = 4;
         } else if (strncmp(buf, "domain_parameter_seed", 21) == 0) {
-	    i = 21;
-	} else if (strncmp(buf,"firstseed",9) == 0) {
-	    i = 9;
-	} else {
-	    i = 0;
-	}
-	if (i) {
+            i = 21;
+        } else if (strncmp(buf,"firstseed",9) == 0) {
+            i = 9;
+        } else {
+            i = 0;
+        }
+        if (i) {
             while (isspace(buf[i]) || buf[i] == '=') {
                 i++;
             }
             for (j=0; isxdigit(buf[i]); i+=2,j++) {
                 hex_to_byteval(&buf[i], &vfy.seed.data[j]);
             }
-	    vfy.seed.len = j;
+            vfy.seed.len = j;
 
             fputs(buf, dsaresp);
-	    if (type == A_2_4) {
-		SECStatus result;
+            if (type == A_2_4) {
+                SECStatus result;
 
                 /* Verify the Parameters */
                 SECStatus rv = PQG_VerifyParams(&pqg, &vfy, &result);
                 if (rv != SECSuccess) {
                     goto loser;
                 }
                 if (result == SECSuccess) {
                     fprintf(dsaresp, "Result = P\n");
                 } else {
                     fprintf(dsaresp, "Result = F\n");
                 }
-	    }
+            }
             continue;
         }
-	if ((strncmp(buf,"pseed",5) == 0) ||
-	    (strncmp(buf,"qseed",5) == 0))
-	{
-	    i = 5;
+        if ((strncmp(buf,"pseed",5) == 0) ||
+            (strncmp(buf,"qseed",5) == 0))
+        {
+            i = 5;
             while (isspace(buf[i]) || buf[i] == '=') {
                 i++;
             }
             for (j=vfy.seed.len; isxdigit(buf[i]); i+=2,j++) {
                 hex_to_byteval(&buf[i], &vfy.seed.data[j]);
             }
-	    vfy.seed.len = j;
+            vfy.seed.len = j;
             fputs(buf, dsaresp);
 
             continue;
-	}
+        }
         if (strncmp(buf, "index", 4) == 0) {
-	    i=5;
+            i=5;
             while (isspace(buf[i]) || buf[i] == '=') {
                 i++;
             }
-	    hex_to_byteval(&buf[i], &vfy.h.data[0]);
-	    vfy.h.len = 1;
+            hex_to_byteval(&buf[i], &vfy.h.data[0]);
+            vfy.h.len = 1;
             fputs(buf, dsaresp);
-	}
+        }
 
         /* c = ...  or counter=*/
         if (buf[0] == 'c')  {
-	    if (strncmp(buf,"counter", 7) == 0) {
+            if (strncmp(buf,"counter", 7) == 0) {
                 if (sscanf(buf, "counter = %u", &vfy.counter) != 1) {
                     goto loser;
-		}
-	    } else {
+                }
+            } else {
                 if (sscanf(buf, "c = %u", &vfy.counter) != 1) {
                     goto loser;
-		}
+                }
             }
 
             fputs(buf, dsaresp);
             if (type == A_1_1_3) {
-		SECStatus result;
+                SECStatus result;
                 /* only verify P and Q, we have everything now. do it */
                 SECStatus rv = PQG_VerifyParams(&pqg, &vfy, &result);
                 if (rv != SECSuccess) {
                     goto loser;
                 }
                 if (result == SECSuccess) {
                     fprintf(dsaresp, "Result = P\n");
                 } else {
                     fprintf(dsaresp, "Result = F\n");
                 }
                 fprintf(dsaresp, "\n");
             }
             continue;
         }
-	if (strncmp(buf,"pgen_counter", 12) == 0) {
+        if (strncmp(buf,"pgen_counter", 12) == 0) {
             if (sscanf(buf, "pgen_counter = %u", &vfy.counter) != 1) {
                 goto loser;
-            }	
+            }        
             fputs(buf, dsaresp);
-	    continue;
-	}
-	if (strncmp(buf,"qgen_counter", 12) == 0) {
+            continue;
+        }
+        if (strncmp(buf,"qgen_counter", 12) == 0) {
             fputs(buf, dsaresp);
             if (type == A_1_2_2) {
-		SECStatus result;
+                SECStatus result;
                 /* only verify P and Q, we have everything now. do it */
                 SECStatus rv = PQG_VerifyParams(&pqg, &vfy, &result);
                 if (rv != SECSuccess) {
                     goto loser;
                 }
                 if (result == SECSuccess) {
                     fprintf(dsaresp, "Result = P\n");
                 } else {
                     fprintf(dsaresp, "Result = F\n");
                 }
                 fprintf(dsaresp, "\n");
             } 
-	    continue;
-	}
+            continue;
+        }
         /* H = ... */
         if (buf[0] == 'H') {
             SECStatus rv, result = SECFailure;
 
             i = 1;
             while (isspace(buf[i]) || buf[i] == '=') {
                 i++;
             }
             for (j=0; isxdigit(buf[i]); i+=2,j++) {
                 hex_to_byteval(&buf[i], &vfy.h.data[j]);
             }
-	    vfy.h.len = j;
+            vfy.h.len = j;
             fputs(buf, dsaresp);
 
-	    /* this should be a byte value. Remove the leading zeros. If
-	     * it doesn't reduce to a byte, PQG_VerifyParams will catch it 
-	    if (type == A_2_2) {
-		data_save = vfy.h.data;
-		while(vfy.h.data[0] && (vfy.h.len > 1)) {
-			vfy.h.data++;
-			vfy.h.len--;
-		}
-	    } */
+            /* this should be a byte value. Remove the leading zeros. If
+             * it doesn't reduce to a byte, PQG_VerifyParams will catch it 
+            if (type == A_2_2) {
+                data_save = vfy.h.data;
+                while(vfy.h.data[0] && (vfy.h.len > 1)) {
+                        vfy.h.data++;
+                        vfy.h.len--;
+                }
+            } */
 
             /* Verify the Parameters */
             rv = PQG_VerifyParams(&pqg, &vfy, &result);
             if (rv != SECSuccess) {
                 goto loser;
             }
             if (result == SECSuccess) {
                 fprintf(dsaresp, "Result = P\n");
@@ -4227,84 +4515,91 @@ dsa_pqggen_test(char *reqfn)
                          */
     FILE *dsareq;     /* input stream from the REQUEST file */
     FILE *dsaresp;    /* output stream to the RESPONSE file */
     int count;            /* number of times to generate parameters */
     int N;
     int L;
     int i;
     unsigned int j;
+    int output_g = 1;
     PQGParams *pqg = NULL;
     PQGVerify *vfy = NULL;
-    unsigned int keySizeIndex;
+    unsigned int keySizeIndex = 0;
     dsa_pqg_type type = FIPS186_1;
 
     dsareq = fopen(reqfn, "r");
     dsaresp = stdout;
     while (fgets(buf, sizeof buf, dsareq) != NULL) {
         /* a comment or blank line */
         if (buf[0] == '#' || buf[0] == '\n') {
             fputs(buf, dsaresp);
             continue;
         }
 
         /* [A.xxxxx ] */
         if (buf[0] == '['  && buf[1] == 'A') {
-	    if (strncmp(&buf[1],"A.1.1.2",7) == 0) {
-		type = A_1_1_2;
-	    } else if (strncmp(&buf[1],"A.2.1",5) == 0) {
-		fprintf(stderr, "NSS only Generates G with P&Q\n");
-		exit(1);
-	    } else if (strncmp(&buf[1],"A.2.3",5) == 0) {
-		fprintf(stderr, "NSS only Generates G with P&Q\n");
+            if (strncmp(&buf[1],"A.1.1.2",7) == 0) {
+                fprintf(stderr, "NSS does Generate Probablistic Primes\n");
 		exit(1);
-	    } else if (strncmp(&buf[1],"A.1.2.1",7) == 0) {
-		fprintf(stderr, "NSS does not support Shawe-Taylor Primes\n");
-		exit(1);
-	    } else {
-		fprintf(stderr, "Unknown dsa ver test %s\n", &buf[1]);
-		exit(1);
-	    }
+            } else if (strncmp(&buf[1],"A.2.1",5) == 0) {
+                type = A_1_2_1;
+		output_g = 1;
+                exit(1);
+            } else if (strncmp(&buf[1],"A.2.3",5) == 0) {
+                fprintf(stderr, "NSS only Generates G with P&Q\n");
+                exit(1);
+            } else if (strncmp(&buf[1],"A.1.2.1",7) == 0) {
+                type = A_1_2_1;
+		output_g = 0;
+            } else {
+                fprintf(stderr, "Unknown dsa pqggen test %s\n", &buf[1]);
+                exit(1);
+            }
             fputs(buf, dsaresp);
             continue;
         }
 
         /* [Mod = ... ] */
         if (buf[0] == '[') {
 
-	    if (type == FIPS186_1) {
+            if (type == FIPS186_1) {
                 N=160;
                 if (sscanf(buf, "[mod = %d]", &L) != 1) {
                     goto loser;
-		}
-	    } else if (sscanf(buf, "[mod = L=%d, N=%d", &L, &N) != 2) {
-		goto loser;
+                }
+            } else if (sscanf(buf, "[mod = L=%d, N=%d", &L, &N) != 2) {
+                goto loser;
             }
 
             fputs(buf, dsaresp);
             fputc('\n', dsaresp);
 
-	    if (type == FIPS186_1) {
+            if (type == FIPS186_1) {
                 /************************************************************
                  * PQG_ParamGenSeedLen doesn't take a key size, it takes an
                  * index that points to a valid key size.
                  */
                 keySizeIndex = PQG_PBITS_TO_INDEX(L);
                 if(keySizeIndex == -1 || L<512 || L>1024) {
                    fprintf(dsaresp,
                         "DSA key size must be a multiple of 64 between 512 "
                         "and 1024, inclusive");
                     goto loser;
                 }
             }
             continue;
         }
         /* N = ... */
         if (buf[0] == 'N') {
-            if (sscanf(buf, "N = %d", &count) != 1) {
+	    if (strncmp(buf, "Num", 3) == 0) {
+                if (sscanf(buf, "Num = %d", &count) != 1) {
+                    goto loser;
+                }
+            } else if (sscanf(buf, "N = %d", &count) != 1) {
                 goto loser;
             }
             for (i = 0; i < count; i++) {
                 SECStatus rv;
 
                 if (type == FIPS186_1) {
                     rv = PQG_ParamGenSeedLen(keySizeIndex, PQG_TEST_SEED_BYTES,
                          &pqg, &vfy);
@@ -4315,34 +4610,48 @@ dsa_pqggen_test(char *reqfn)
                     fprintf(dsaresp,
                             "ERROR: Unable to generate PQG parameters");
                     goto loser;
                 }
                 to_hex_str(buf, pqg->prime.data, pqg->prime.len);
                 fprintf(dsaresp, "P = %s\n", buf);
                 to_hex_str(buf, pqg->subPrime.data, pqg->subPrime.len);
                 fprintf(dsaresp, "Q = %s\n", buf);
-                to_hex_str(buf, pqg->base.data, pqg->base.len);
-                fprintf(dsaresp, "G = %s\n", buf);
-		if (type == FIPS186_1) {
+		if (output_g) {
+                    to_hex_str(buf, pqg->base.data, pqg->base.len);
+                    fprintf(dsaresp, "G = %s\n", buf);
+		}
+                if (type == FIPS186_1) {
                     to_hex_str(buf, vfy->seed.data, vfy->seed.len);
                     fprintf(dsaresp, "Seed = %s\n", buf);
                     fprintf(dsaresp, "c = %d\n", vfy->counter);
                     to_hex_str(buf, vfy->h.data, vfy->h.len);
                     fputs("H = ", dsaresp);
                     for (j=vfy->h.len; j< pqg->prime.len; j++) {
-                	fprintf(dsaresp, "00");
+                        fprintf(dsaresp, "00");
                     }
                     fprintf(dsaresp, "%s\n", buf);
-		} else {
-                    fprintf(dsaresp, "counter = %d\n", vfy->counter);
-		    fprintf(dsaresp, "index = %02x\n", vfy->h.data[0]);
-                    to_hex_str(buf, vfy->seed.data, vfy->seed.len);
-                    fprintf(dsaresp, "domain_parameter_seed = %s\n", buf);
-		}
+                } else {
+                    unsigned int seedlen = vfy->seed.len/2;
+		    unsigned int pgen_counter = vfy->counter >> 16;
+		    unsigned int qgen_counter = vfy->counter & 0xffff;
+                    /*fprintf(dsaresp, "index = %02x\n", vfy->h.data[0]); */
+                    to_hex_str(buf, vfy->seed.data, seedlen);
+                    fprintf(dsaresp, "pseed = %s\n", buf);
+                    to_hex_str(buf, vfy->seed.data+seedlen, seedlen);
+                    fprintf(dsaresp, "qseed = %s\n", buf);
+                    fprintf(dsaresp, "pgen_counter = %d\n", pgen_counter);
+                    fprintf(dsaresp, "qgen_counter = %d\n", qgen_counter);
+		    if (output_g) {
+                        to_hex_str(buf, vfy->seed.data, vfy->seed.len);
+                        fprintf(dsaresp, "domain_parameter_seed = %s\n", buf);
+		        fprintf(dsaresp, "index = %02x\n", vfy->h.data[0]);
+		    }
+		
+                }
                 fputc('\n', dsaresp);
                 if(pqg!=NULL) {
                     PQG_DestroyParams(pqg);
                     pqg = NULL;
                 }
                 if(vfy!=NULL) {
                     PQG_DestroyVerify(vfy);
                     vfy = NULL;
@@ -4418,17 +4727,17 @@ dsa_siggen_test(char *reqfn)
             if (dsakey != NULL) {
                     PORT_FreeArena(dsakey->params.arena, PR_TRUE);
                     dsakey = NULL;
             }
 
             if (sscanf(buf, "[mod = L=%d,  N=%d, SHA-%d]", &L, & N,
                 &hashNum) != 3) {
                 use_dsa1 = PR_TRUE;
-		hashNum = 1;
+                hashNum = 1;
                 if (sscanf(buf, "[mod = %d]", &modulus) != 1) {
                     goto loser;
                 }
             }
             fputs(buf, dsaresp);
             fputc('\n', dsaresp);
 
             /****************************************************************
@@ -4465,47 +4774,47 @@ dsa_siggen_test(char *reqfn)
             fprintf(dsaresp, "G = %s\n", buf);
 
             /* create DSA Key */
             if (DSA_NewKey(pqg, &dsakey) != SECSuccess) {
                 fprintf(dsaresp, "ERROR: Unable to generate DSA key");
                 goto loser;
             }
  
-	    hashType = sha_get_hashType(hashNum);
-	    if (hashType == HASH_AlgNULL) {
-		fprintf(dsaresp, "ERROR: invalid hash (SHA-%d)",hashNum);
-		goto loser;
-	    }
+            hashType = sha_get_hashType(hashNum);
+            if (hashType == HASH_AlgNULL) {
+                fprintf(dsaresp, "ERROR: invalid hash (SHA-%d)",hashNum);
+                goto loser;
+            }
             continue;
         }
 
         /* Msg = ... */
         if (strncmp(buf, "Msg", 3) == 0) {
             unsigned char msg[128]; /* MAX msg 128 */
             unsigned int len = 0;
 
-	    if (hashType == HASH_AlgNULL) {
-		fprintf(dsaresp, "ERROR: Hash Alg not set");
-		goto loser;
-	    }
+            if (hashType == HASH_AlgNULL) {
+                fprintf(dsaresp, "ERROR: Hash Alg not set");
+                goto loser;
+            }
 
             memset(hashBuf, 0, sizeof hashBuf);
             memset(sig,  0, sizeof sig);
 
             i = 3;
             while (isspace(buf[i]) || buf[i] == '=') {
                 i++;
             }
             for (j=0; isxdigit(buf[i]); i+=2,j++) {
                 hex_to_byteval(&buf[i], &msg[j]);
             }
             if (fips_hashBuf(hashType, hashBuf, msg, j) != SECSuccess) {
                  fprintf(dsaresp, "ERROR: Unable to generate SHA% digest", 
-			 hashNum);
+                         hashNum);
                  goto loser;
             }
 
 
             digest.type = siBuffer;
             digest.data = hashBuf;
             digest.len = fips_hashLen(hashType);
             signature.type = siBuffer;
@@ -4590,18 +4899,18 @@ dsa_sigver_test(char *reqfn)
             continue;
         }
 
         /* [Mod = x] */
         if (buf[0] == '[') {
 
             if (sscanf(buf, "[mod = L=%d,  N=%d, SHA-%d]", &L, & N,
                 &hashNum) != 3) {
-		N=160;
-		hashNum = 1;
+                N=160;
+                hashNum = 1;
                 if (sscanf(buf, "[mod = %d]", &L) != 1) {
                     goto loser;
                 }
             }
 
             if (pubkey.params.prime.data) { /* P */
                 SECITEM_ZfreeItem(&pubkey.params.prime, PR_FALSE);
             }
@@ -4623,21 +4932,21 @@ dsa_sigver_test(char *reqfn)
             SECITEM_AllocItem(NULL, &pubkey.publicValue, pgySize);
             pubkey.params.prime.len = pubkey.params.base.len = pgySize;
             pubkey.publicValue.len = pgySize;
 
             /* q always N/8 bytes */
             SECITEM_AllocItem(NULL, &pubkey.params.subPrime, N/8);
             pubkey.params.subPrime.len = N/8;
 
-	    hashType = sha_get_hashType(hashNum);
-	    if (hashType == HASH_AlgNULL) {
-		fprintf(dsaresp, "ERROR: invalid hash (SHA-%d)",hashNum);
-		goto loser;
-	    }
+            hashType = sha_get_hashType(hashNum);
+            if (hashType == HASH_AlgNULL) {
+                fprintf(dsaresp, "ERROR: invalid hash (SHA-%d)",hashNum);
+                goto loser;
+            }
 
             continue;
         }
         /* P = ... */
         if (buf[0] == 'P') {
             i = 1;
             while (isspace(buf[i]) || buf[i] == '=') {
                 i++;
@@ -4681,31 +4990,31 @@ dsa_sigver_test(char *reqfn)
             continue;
         }
 
         /* Msg = ... */
         if (strncmp(buf, "Msg", 3) == 0) {
             unsigned char msg[128]; /* MAX msg 128 */
             memset(hashBuf, 0, sizeof hashBuf);
 
-	    if (hashType == HASH_AlgNULL) {
-		fprintf(dsaresp, "ERROR: Hash Alg not set");
-		goto loser;
-	    }
+            if (hashType == HASH_AlgNULL) {
+                fprintf(dsaresp, "ERROR: Hash Alg not set");
+                goto loser;
+            }
 
             i = 3;
             while (isspace(buf[i]) || buf[i] == '=') {
                 i++;
             }
             for (j=0; isxdigit(buf[i]); i+=2,j++) {
                 hex_to_byteval(&buf[i], &msg[j]);
             }
             if (fips_hashBuf(hashType, hashBuf, msg, j) != SECSuccess) {
                 fprintf(dsaresp, "ERROR: Unable to generate SHA-%d digest",
-								hashNum);
+                                                                hashNum);
                 goto loser;
             }
 
             fputs(buf, dsaresp);
             continue;
         }
 
         /* Y = ... */
@@ -4735,44 +5044,44 @@ dsa_sigver_test(char *reqfn)
             }
 
             fputs(buf, dsaresp);
             continue;
         }
 
         /* S = ... */
         if (buf[0] == 'S') {
-	    if (hashType == HASH_AlgNULL) {
-		fprintf(dsaresp, "ERROR: Hash Alg not set");
-		goto loser;
-	    }
+            if (hashType == HASH_AlgNULL) {
+                fprintf(dsaresp, "ERROR: Hash Alg not set");
+                goto loser;
+            }
 
             i = 1;
             while (isspace(buf[i]) || buf[i] == '=') {
                 i++;
             }
             for (j=pubkey.params.subPrime.len; 
-				j< pubkey.params.subPrime.len*2; i+=2,j++) {
+                                j< pubkey.params.subPrime.len*2; i+=2,j++) {
                 hex_to_byteval(&buf[i], &sig[j]);
             }
             fputs(buf, dsaresp);
 
             digest.type = siBuffer;
             digest.data = hashBuf;
             digest.len = fips_hashLen(hashType);
             signature.type = siBuffer;
             signature.data = sig;
             signature.len = pubkey.params.subPrime.len*2;
 
             if (DSA_VerifyDigest(&pubkey, &signature, &digest) == SECSuccess) {
                 fprintf(dsaresp, "Result = P\n");
             } else {
                 fprintf(dsaresp, "Result = F\n");
             }
-	    fprintf(dsaresp, "\n");
+            fprintf(dsaresp, "\n");
             continue;
         }
     }
 loser:
     fclose(dsareq);
     if (pubkey.params.prime.data) { /* P */
         SECITEM_ZfreeItem(&pubkey.params.prime, PR_FALSE);
     }
@@ -4782,16 +5091,128 @@ loser:
     if (pubkey.params.base.data) {    /* G */
         SECITEM_ZfreeItem(&pubkey.params.base, PR_FALSE);
     }
     if (pubkey.publicValue.data) {    /* Y */
         SECITEM_ZfreeItem(&pubkey.publicValue, PR_FALSE);
     }
 }
 
+static void 
+pad(unsigned char *buf, int pad_len, unsigned char *src, int src_len) 
+{
+    int offset = 0;
+    /* this shouldn't happen, fail right away rather than produce bad output */
+    if (pad_len < src_len) {
+	fprintf(stderr, "data bigger than expected! %d > %d\n", src_len, pad_len);
+	exit(1);
+    }
+
+    offset = pad_len - src_len;
+    memset(buf, 0, offset);
+    memcpy(buf+offset, src, src_len);
+    return;
+}
+
+
+/*
+ * Perform the DSA Key Pair Generation Test.
+ *
+ * reqfn is the pathname of the REQUEST file.
+ *
+ * The output RESPONSE file is written to stdout.
+ */
+void
+rsa_keypair_test(char *reqfn)
+{
+    char buf[800];       /* holds one line from the input REQUEST file
+                         * or to the output RESPONSE file.
+                         * 800 to hold (384 public key (x2 for HEX) + 1'\n'
+                         */
+    unsigned char buf2[400];   /* can't need more then 1/2 buf length */
+    FILE *rsareq;     /* input stream from the REQUEST file */
+    FILE *rsaresp;    /* output stream to the RESPONSE file */
+    int count;
+    int i;
+    int keySize;   /* key size in bits*/
+    int len = 0;       /* key size in bytes */
+    int len2 = 0;      /* key size in bytes/2 (prime size) */
+    SECItem e;
+    unsigned char default_e[] = { 0x1, 0x0, 0x1 };
+
+    e.data = default_e;
+    e.len = sizeof (default_e);
+
+    rsareq = fopen(reqfn, "r");
+    rsaresp = stdout;
+    while (fgets(buf, sizeof buf, rsareq) != NULL) {
+        /* a comment or blank line */
+        if (buf[0] == '#' || buf[0] == '\n') {
+            fputs(buf, rsaresp);
+            continue;
+        }
+
+        /* [Mod = x] */
+        if (buf[0] == '[') {
+	    if (buf[1] == 'm') {
+        	if (sscanf(buf, "[mod = %d]", &keySize) != 1) {
+                    goto loser;
+        	}
+		len = keySize/8;
+		len2 = keySize/16;
+	    }
+            fputs(buf, rsaresp);
+            continue;
+        }
+        /* N = ...*/
+        if (buf[0] == 'N') {
+
+            if (sscanf(buf, "N = %d", &count) != 1) {
+                goto loser;
+            }
+
+            /* Generate a DSA key, and output the key pair for N times */
+            for (i = 0; i < count; i++) {
+                RSAPrivateKey *rsakey = NULL;
+                if ((rsakey = RSA_NewKey(keySize, &e)) == NULL) {
+                    fprintf(rsaresp, "ERROR: Unable to generate RSA key");
+                    goto loser;
+                }
+	        pad(buf2,len,rsakey->publicExponent.data,
+					 rsakey->publicExponent.len);
+                to_hex_str(buf, buf2, len);
+                fprintf(rsaresp, "e = %s\n", buf);
+	        pad(buf2,len2,rsakey->prime1.data,
+					 rsakey->prime1.len);
+                to_hex_str(buf, buf2, len2);
+                fprintf(rsaresp, "p = %s\n", buf);
+	        pad(buf2,len2,rsakey->prime2.data,
+					 rsakey->prime2.len);
+                to_hex_str(buf, buf2, len2);
+                fprintf(rsaresp, "q = %s\n", buf);
+	        pad(buf2,len,rsakey->modulus.data,
+					 rsakey->modulus.len);
+                to_hex_str(buf, buf2, len);
+                fprintf(rsaresp, "n = %s\n", buf);
+	        pad(buf2,len,rsakey->privateExponent.data,
+					 rsakey->privateExponent.len);
+                to_hex_str(buf, buf2, len);
+                fprintf(rsaresp, "d = %s\n", buf);
+                fprintf(rsaresp, "\n");
+                PORT_FreeArena(rsakey->arena, PR_TRUE);
+                rsakey = NULL;
+            }
+            continue;
+        }
+
+    }
+loser:
+    fclose(rsareq);
+}
+
 /*
  * Perform the RSA Signature Generation Test.
  *
  * reqfn is the pathname of the REQUEST file.
  *
  * The output RESPONSE file is written to stdout.
  */
 void
@@ -4940,26 +5361,26 @@ rsa_siggen_test(char *reqfn)
 
             i = 3;
             while (isspace(buf[i]) || buf[i] == '=') {
                 i++;
             }
             for (j=0; isxdigit(buf[i]) && j < sizeof(msg); i+=2,j++) {
                 hex_to_byteval(&buf[i], &msg[j]);
             }
-	    shaLength = fips_hashLen(shaAlg);
-	    if (fips_hashBuf(shaAlg,sha,msg,j) != SECSuccess) {
-		if (shaLength == 0) {
-            	    fprintf(rsaresp, "ERROR: SHAAlg not defined.");
-		}
+            shaLength = fips_hashLen(shaAlg);
+            if (fips_hashBuf(shaAlg,sha,msg,j) != SECSuccess) {
+                if (shaLength == 0) {
+                        fprintf(rsaresp, "ERROR: SHAAlg not defined.");
+                }
                 fprintf(rsaresp, "ERROR: Unable to generate SHA%x",
-			shaLength == 160 ? 1 : shaLength);
+                        shaLength == 160 ? 1 : shaLength);
                 goto loser;
             }
-	    shaOid = fips_hashOid(shaAlg);
+            shaOid = fips_hashOid(shaAlg);
 
             /* Perform RSA signature with the RSA private key. */
             rv = RSA_HashSign( shaOid,
                                rsa_private_key,
                                rsa_computed_signature,
                                &rsa_bytes_signed,
                                nsslowkey_PrivateModulusLen(rsa_private_key),
                                sha,
@@ -5164,23 +5585,23 @@ rsa_sigver_test(char *reqfn)
             while (isspace(buf[i]) || buf[i] == '=') {
                 i++;
             }
 
             for (j=0; isxdigit(buf[i]) && j < sizeof msg; i+=2,j++) {
                 hex_to_byteval(&buf[i], &msg[j]);
             }
 
-	    shaLength = fips_hashLen(shaAlg);
-	    if (fips_hashBuf(shaAlg,sha,msg,j) != SECSuccess) {
-		if (shaLength == 0) {
-            	    fprintf(rsaresp, "ERROR: SHAAlg not defined.");
-		}
+            shaLength = fips_hashLen(shaAlg);
+            if (fips_hashBuf(shaAlg,sha,msg,j) != SECSuccess) {
+                if (shaLength == 0) {
+                        fprintf(rsaresp, "ERROR: SHAAlg not defined.");
+                }
                 fprintf(rsaresp, "ERROR: Unable to generate SHA%x",
-			shaLength == 160 ? 1 : shaLength);
+                        shaLength == 160 ? 1 : shaLength);
                 goto loser;
             }
 
             fputs(buf, rsaresp);
             continue;
 
         }
 
@@ -5203,16 +5624,18 @@ rsa_sigver_test(char *reqfn)
 
             for (j=0; isxdigit(buf[i]) && j < sizeof signature; i+=2,j++) {
                 hex_to_byteval(&buf[i], &signature[j]);
             }
 
             signatureLength = j;
             fputs(buf, rsaresp);
 
+            shaOid = fips_hashOid(shaAlg);
+
             /* Perform RSA verification with the RSA public key. */
             rv = RSA_HashCheckSign( shaOid,
                                     rsa_public_key,
                                     signature,
                                     signatureLength,
                                     sha,
                                     shaLength);
             if( rv == SECSuccess ) {
@@ -5228,16 +5651,312 @@ loser:
     if (rsaBlapiPublicKey.modulus.data) { /* n */
         SECITEM_ZfreeItem(&rsaBlapiPublicKey.modulus, PR_FALSE);
     }
     if (rsaBlapiPublicKey.publicExponent.data) { /* e */
         SECITEM_ZfreeItem(&rsaBlapiPublicKey.publicExponent, PR_FALSE);
     }
 }
 
+void
+tls(char *reqfn)
+{
+    char buf[256];      /* holds one line from the input REQUEST file.
+                         * needs to be large enough to hold the longest
+                         * line "XSeed = <128 hex digits>\n".
+                         */
+    unsigned char *pms = NULL;
+    int pms_len;
+    unsigned char *master_secret = NULL;
+    unsigned char *key_block = NULL;
+    int key_block_len;
+    unsigned char serverHello_random[SSL3_RANDOM_LENGTH];
+    unsigned char clientHello_random[SSL3_RANDOM_LENGTH];
+    unsigned char server_random[SSL3_RANDOM_LENGTH];
+    unsigned char client_random[SSL3_RANDOM_LENGTH];
+    FILE *tlsreq = NULL; /* input stream from the REQUEST file */
+    FILE *tlsresp;       /* output stream to the RESPONSE file */
+    unsigned int i, j;
+    CK_SLOT_ID slotList[10];
+    CK_SLOT_ID slotID;
+    CK_ULONG slotListCount = sizeof(slotList)/sizeof(slotList[0]);
+    CK_ULONG count;
+    static const CK_C_INITIALIZE_ARGS pk11args= {
+	NULL, NULL, NULL, NULL, CKF_LIBRARY_CANT_CREATE_OS_THREADS , 
+	(void *)"flags=readOnly,noCertDB,noModDB", NULL };
+    static CK_OBJECT_CLASS ck_secret = CKO_SECRET_KEY;
+    static CK_KEY_TYPE ck_generic = CKK_GENERIC_SECRET;
+    static CK_BBOOL ck_true = CK_TRUE;
+    static CK_ULONG one = 1;
+    CK_ATTRIBUTE create_template[] = {
+	{ CKA_VALUE,        NULL,        0                  },
+	{ CKA_CLASS,        &ck_secret,  sizeof(ck_secret)  },
+	{ CKA_KEY_TYPE,     &ck_generic, sizeof(ck_generic) },
+	{ CKA_DERIVE,       &ck_true,    sizeof (ck_true)   },
+    };
+    CK_ULONG create_template_count = 
+			sizeof(create_template)/sizeof(create_template[0]);
+    CK_ATTRIBUTE derive_template[] = {
+	{ CKA_CLASS,        &ck_secret,  sizeof(ck_secret)  },
+	{ CKA_KEY_TYPE,     &ck_generic, sizeof(ck_generic) },
+	{ CKA_DERIVE,       &ck_true,    sizeof(ck_true)    },
+	{ CKA_VALUE_LEN,    &one,        sizeof(one)        },
+    };
+    CK_ULONG derive_template_count = 
+			sizeof(derive_template)/sizeof(derive_template[0]);
+    CK_ATTRIBUTE master_template = 
+	{ CKA_VALUE, NULL, 0 };
+    CK_ATTRIBUTE kb1_template = 
+	{ CKA_VALUE, NULL, 0 };
+    CK_ATTRIBUTE kb2_template = 
+	{ CKA_VALUE, NULL, 0 };
+    
+
+    CK_MECHANISM master_mech = { CKM_TLS_MASTER_KEY_DERIVE , NULL, 0 };
+    CK_MECHANISM key_block_mech = { CKM_TLS_KEY_AND_MAC_DERIVE , NULL, 0};
+    CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params;
+    CK_SSL3_KEY_MAT_PARAMS key_block_params;
+    CK_SSL3_KEY_MAT_OUT key_material;
+    CK_RV crv;
+
+    /* set up PKCS #11 parameters */
+    master_params.pVersion = NULL;
+    master_params.RandomInfo.pClientRandom = clientHello_random;
+    master_params.RandomInfo.ulClientRandomLen = sizeof(clientHello_random);
+    master_params.RandomInfo.pServerRandom = serverHello_random;
+    master_params.RandomInfo.ulServerRandomLen = sizeof(serverHello_random);
+    master_mech.pParameter = (void *) &master_params;
+    master_mech.ulParameterLen = sizeof(master_params);
+    key_block_params.ulMacSizeInBits = 0;
+    key_block_params.ulKeySizeInBits = 0;
+    key_block_params.ulIVSizeInBits = 0;
+    key_block_params.bIsExport = PR_FALSE; /* ignored anyway for TLS mech */
+    key_block_params.RandomInfo.pClientRandom = client_random;
+    key_block_params.RandomInfo.ulClientRandomLen = sizeof(client_random);
+    key_block_params.RandomInfo.pServerRandom = server_random;
+    key_block_params.RandomInfo.ulServerRandomLen = sizeof(server_random);
+    key_block_params.pReturnedKeyMaterial = &key_material;
+    key_block_mech.pParameter = (void *) &key_block_params;
+    key_block_mech.ulParameterLen = sizeof(key_block_params);
+    
+
+    crv = NSC_Initialize((CK_VOID_PTR)&pk11args);
+    if (crv != CKR_OK) {
+	fprintf(stderr,"NSC_Initialize failed crv=0x%x\n",(unsigned int)crv);
+	goto loser;
+    }
+    count = slotListCount;
+    crv = NSC_GetSlotList(PR_TRUE,slotList, &count);
+    if (crv != CKR_OK) {
+	fprintf(stderr,"NSC_GetSlotList failed crv=0x%x\n",(unsigned int)crv);
+	goto loser;
+    }
+    if ((count > slotListCount) || count < 1) {
+	fprintf(stderr,
+"NSC_GetSlotList returned too many or too few slots: %d slots max=%d min=1\n",
+		(int) count, (int) slotListCount);
+	goto loser;
+    }
+    slotID = slotList[0];
+    tlsreq = fopen(reqfn, "r");
+    tlsresp = stdout;
+    while (fgets(buf, sizeof buf, tlsreq) != NULL) {
+        /* a comment or blank line */
+        if (buf[0] == '#' || buf[0] == '\n') {
+            fputs(buf, tlsresp);
+            continue;
+        }
+        /* [Xchange - SHA1] */
+        if (buf[0] == '[') {
+            if (strncmp(buf, "[TLS", 4)  == 0) {
+		if (buf[7] == '0') {
+    		    master_mech.mechanism = CKM_TLS_MASTER_KEY_DERIVE;
+    		    key_block_mech.mechanism = CKM_TLS_KEY_AND_MAC_DERIVE;
+		} else if (buf[7] == '2') {
+    		    master_mech.mechanism = 
+					CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256;
+    		    key_block_mech.mechanism = 
+					CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
+		} else {
+		    fprintf(stderr, "Unknown TLS type %x\n", 
+						(unsigned int)buf[0]);
+		    goto loser;
+		} 
+	    }
+            if (strncmp(buf, "[pre-master", 11)  == 0) {
+                if (sscanf(buf, "[pre-master secret length = %d]", 
+				&pms_len) != 1) {
+                    goto loser;
+                }
+                pms_len = pms_len/8;
+		pms = malloc(pms_len);
+	 	master_secret = malloc(pms_len);
+		create_template[0].pValue = pms;
+		create_template[0].ulValueLen = pms_len;
+		master_template.pValue = master_secret;
+		master_template.ulValueLen = pms_len;
+            } 
+            if (strncmp(buf, "[key", 4)  == 0) {
+                if (sscanf(buf, "[key block length = %d]", &key_block_len) != 1) {
+                    goto loser;
+                }
+    		key_block_params.ulKeySizeInBits = 8;
+    		key_block_params.ulIVSizeInBits = key_block_len/2-8;
+                key_block_len=key_block_len/8;
+		key_block = malloc(key_block_len);
+		kb1_template.pValue = &key_block[0];
+		kb1_template.ulValueLen = 1;
+		kb2_template.pValue = &key_block[1];
+		kb2_template.ulValueLen = 1;
+		key_material.pIVClient = &key_block[2];
+		key_material.pIVServer = &key_block[2+key_block_len/2-1];
+            } 
+            fputs(buf, tlsresp);
+            continue;
+        }
+        /* "COUNT = x" begins a new data set */
+        if (strncmp(buf, "COUNT", 5) == 0) {
+            /* zeroize the variables for the test with this data set */
+            memset(pms, 0, pms_len);
+            memset(master_secret, 0, pms_len);
+            memset(key_block, 0, key_block_len);
+            fputs(buf, tlsresp);
+            continue;
+        }
+        /* pre_master_secret = ... */
+        if (strncmp(buf, "pre_master_secret", 17) == 0) {
+            i = 17;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<pms_len; i+=2,j++) {
+                hex_to_byteval(&buf[i], &pms[j]);
+            }
+            fputs(buf, tlsresp);
+            continue;
+        }
+        /* serverHello_random = ... */
+        if (strncmp(buf, "serverHello_random", 18) == 0) {
+            i = 18;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<SSL3_RANDOM_LENGTH; i+=2,j++) {
+                hex_to_byteval(&buf[i], &serverHello_random[j]);
+            }
+            fputs(buf, tlsresp);
+            continue;
+        }
+        /* clientHello_random = ... */
+        if (strncmp(buf, "clientHello_random", 18) == 0) {
+            i = 18;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<SSL3_RANDOM_LENGTH; i+=2,j++) {
+                hex_to_byteval(&buf[i], &clientHello_random[j]);
+            }
+            fputs(buf, tlsresp);
+            continue;
+        }
+        /* server_random = ... */
+        if (strncmp(buf, "server_random", 13) == 0) {
+            i = 13;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<SSL3_RANDOM_LENGTH; i+=2,j++) {
+                hex_to_byteval(&buf[i], &server_random[j]);
+            }
+            fputs(buf, tlsresp);
+            continue;
+        }
+        /* client_random = ... */
+        if (strncmp(buf, "client_random", 13) == 0) {
+	    CK_SESSION_HANDLE session;
+ 	    CK_OBJECT_HANDLE pms_handle;
+ 	    CK_OBJECT_HANDLE master_handle;
+ 	    CK_OBJECT_HANDLE fake_handle;
+            i = 13;
+            while (isspace(buf[i]) || buf[i] == '=') {
+                i++;
+            }
+            for (j=0; j<SSL3_RANDOM_LENGTH; i+=2,j++) {
+                hex_to_byteval(&buf[i], &client_random[j]);
+            }
+            fputs(buf, tlsresp);
+	    crv = NSC_OpenSession(slotID, 0, NULL, NULL, &session);
+	    if (crv != CKR_OK) {
+		fprintf(stderr,"NSC_OpenSession failed crv=0x%x\n",
+							(unsigned int)crv);
+		goto loser;
+	    }
+	    crv = NSC_CreateObject(session, create_template, 
+					create_template_count, &pms_handle);
+	    if (crv != CKR_OK) {
+		fprintf(stderr,"NSC_CreateObject failed crv=0x%x\n",
+							(unsigned int)crv);
+		goto loser;
+	    }
+	    crv = NSC_DeriveKey(session, &master_mech, pms_handle, 
+		derive_template, derive_template_count-1, &master_handle);
+	    if (crv != CKR_OK) {
+		fprintf(stderr,"NSC_DeriveKey(master) failed crv=0x%x\n",
+							(unsigned int) crv);
+		goto loser;
+	    }
+	    crv = NSC_GetAttributeValue(session, master_handle, 
+							&master_template, 1);
+	    if (crv != CKR_OK) {
+		fprintf(stderr,"NSC_GetAttribute failed crv=0x%x\n",
+							(unsigned int) crv);
+		goto loser;
+	    }
+            fputs("master_secret = ", tlsresp);
+            to_hex_str(buf, master_secret, pms_len);
+            fputs(buf, tlsresp);
+            fputc('\n', tlsresp);
+	    crv = NSC_DeriveKey(session, &key_block_mech, master_handle,
+			derive_template, derive_template_count, &fake_handle);
+	    if (crv != CKR_OK) {
+		fprintf(stderr,
+			"NSC_DeriveKey(keyblock) failed crv=0x%x\n",
+							(unsigned int) crv);
+		goto loser;
+	    }
+	    crv = NSC_GetAttributeValue(session, key_material.hClientKey, 
+							&kb1_template, 1);
+	    if (crv != CKR_OK) {
+		fprintf(stderr,"NSC_GetAttribute failed crv=0x%x\n",
+							(unsigned int) crv);
+		goto loser;
+	    }
+	    crv = NSC_GetAttributeValue(session, key_material.hServerKey, 
+							&kb2_template, 1);
+	    if (crv != CKR_OK) {
+		fprintf(stderr,"NSC_GetAttribute failed crv=0x%x\n",
+							(unsigned int) crv);
+		goto loser;
+	    }
+            fputs("key_block = ", tlsresp);
+            to_hex_str(buf, key_block, key_block_len);
+            fputs(buf, tlsresp);
+            fputc('\n', tlsresp);
+	    crv = NSC_CloseSession(session);
+            continue;
+        }
+    }
+loser:
+    NSC_Finalize(NULL);
+    if (pms) free(pms);
+    if (master_secret) free(master_secret);
+    if (key_block) free(key_block);
+    if (tlsreq) fclose(tlsreq);
+}
+
 int main(int argc, char **argv)
 {
     if (argc < 2) exit (-1);
 
     RNG_RNGInit();
     SECOID_Init();
 
     /*************/
@@ -5260,33 +5979,41 @@ int main(int argc, char **argv)
                     /* CBC mode */
                     tdea_mct(NSS_DES_EDE3_CBC, argv[4]);
                 }
         }
     /*************/
     /*   AES     */
     /*************/
     } else if (strcmp(argv[1], "aes") == 0) {
-	/* argv[2]=kat|mmt|mct argv[3]=ecb|cbc argv[4]=<test name>.req */
-	if (       strcmp(argv[2], "kat") == 0) {
-	    /* Known Answer Test (KAT) */
-	    aes_kat_mmt(argv[4]);
-	} else if (strcmp(argv[2], "mmt") == 0) {
-	    /* Multi-block Message Test (MMT) */
-	    aes_kat_mmt(argv[4]);
-	} else if (strcmp(argv[2], "mct") == 0) {
-	    /* Monte Carlo Test (MCT) */
-	    if (       strcmp(argv[3], "ecb") == 0) {
-		/* ECB mode */
-		aes_ecb_mct(argv[4]);
-	    } else if (strcmp(argv[3], "cbc") == 0) {
-		/* CBC mode */
-		aes_cbc_mct(argv[4]);
-	    }
-	}
+        /* argv[2]=kat|mmt|mct argv[3]=ecb|cbc argv[4]=<test name>.req */
+        if (       strcmp(argv[2], "kat") == 0) {
+            /* Known Answer Test (KAT) */
+            aes_kat_mmt(argv[4]);
+        } else if (strcmp(argv[2], "mmt") == 0) {
+            /* Multi-block Message Test (MMT) */
+            aes_kat_mmt(argv[4]);
+        } else if (strcmp(argv[2], "gcm") == 0) {
+            if (       strcmp(argv[3], "decrypt") == 0) {
+                aes_gcm(argv[4],0);
+            } else if (strcmp(argv[3], "encrypt_extiv") == 0) {
+                aes_gcm(argv[4],1);
+            } else if (strcmp(argv[3], "encrypt_intiv") == 0) {
+                aes_gcm(argv[4],2);
+            }
+        } else if (strcmp(argv[2], "mct") == 0) {
+            /* Monte Carlo Test (MCT) */
+            if (       strcmp(argv[3], "ecb") == 0) {
+                /* ECB mode */
+                aes_ecb_mct(argv[4]);
+            } else if (strcmp(argv[3], "cbc") == 0) {
+                /* CBC mode */
+                aes_cbc_mct(argv[4]);
+            }
+        }
     /*************/
     /*   SHA     */
     /*************/
     } else if (strcmp(argv[1], "sha") == 0) {
         sha_test(argv[2]);
     /*************/
     /*   RSA     */
     /*************/
@@ -5294,17 +6021,20 @@ int main(int argc, char **argv)
         /* argv[2]=siggen|sigver */
         /* argv[3]=<test name>.req */
         if (strcmp(argv[2], "siggen") == 0) {
             /* Signature Generation Test */
             rsa_siggen_test(argv[3]);
         } else if (strcmp(argv[2], "sigver") == 0) {
             /* Signature Verification Test */
             rsa_sigver_test(argv[3]);
-        }
+        } else if (strcmp(argv[2], "keypair") == 0) {
+            /* Key Pair Generation Test */
+            rsa_keypair_test(argv[3]);
+	}
     /*************/
     /*   HMAC    */
     /*************/
     } else if (strcmp(argv[1], "hmac") == 0) {
         hmac_test(argv[2]);
     /*************/
     /*   DSA     */
     /*************/
--- a/security/nss/cmd/httpserv/httpserv.c
+++ b/security/nss/cmd/httpserv/httpserv.c
@@ -334,17 +334,16 @@ typedef struct caRevoInfoStr caRevoInfo;
 static caRevoInfo *caRevoInfos = NULL;
 
 static enum { 
   ocspGetOnly, ocspPostOnly, ocspGetAndPost, ocspRandomGetFailure, ocspGetUnknown
 } ocspMethodsAllowed = ocspGetAndPost;
 
 static const char stopCmd[] = { "GET /stop " };
 static const char getCmd[]  = { "GET " };
-static const char EOFmsg[]  = { "EOF\r\n\r\n\r\n" };
 static const char outHeader[] = {
     "HTTP/1.0 200 OK\r\n"
     "Server: Generic Web Server\r\n"
     "Date: Tue, 26 Aug 1997 22:10:05 GMT\r\n"
     "Content-type: text/plain\r\n"
     "\r\n"
 };
 static const char outOcspHeader[] = {
@@ -707,18 +706,18 @@ handle_connection(
 		  if (entry) {
 		      /* revoked status response */
 		      revoked = PR_TRUE;
 		      DER_DecodeTimeChoice(&revoDate, &entry->revocationDate);
 		  } else {
 		      /* else good status response */
 		      if (!isPost && ocspMethodsAllowed == ocspGetUnknown) {
 			  unknown = PR_TRUE;
-			  nextUpdate = PR_Now() + 60*60*24 * PR_USEC_PER_SEC; /*tomorrow*/
-			  revoDate = PR_Now() - 60*60*24 * PR_USEC_PER_SEC; /*yesterday*/
+			  nextUpdate = PR_Now() + (PRTime)60*60*24 * PR_USEC_PER_SEC; /*tomorrow*/
+			  revoDate = PR_Now() - (PRTime)60*60*24 * PR_USEC_PER_SEC; /*yesterday*/
 		      }
 		  }
 	      }
 
 	      {
 		  PRTime now = PR_Now();
 		  PLArenaPool *arena = NULL;
 		  CERTOCSPSingleResponse *sr;
--- a/security/nss/cmd/lib/basicutil.c
+++ b/security/nss/cmd/lib/basicutil.c
@@ -679,17 +679,17 @@ static unsigned char nibble(char c) {
     c = PORT_Tolower(c);
     return ( c >= '0' && c <= '9') ? c - '0' :
            ( c >= 'a' && c <= 'f') ? c - 'a' +10 : -1;
 }
 
 SECStatus
 SECU_SECItemHexStringToBinary(SECItem* srcdest)
 {
-    int i;
+    unsigned int i;
 
     if (!srcdest) {
         PORT_SetError(SEC_ERROR_INVALID_ARGS);
         return SECFailure;
     }
     if (srcdest->len < 4 || (srcdest->len % 2) ) {
         /* too short to convert, or even number of characters */
         PORT_SetError(SEC_ERROR_BAD_DATA);
--- a/security/nss/cmd/lib/derprint.c
+++ b/security/nss/cmd/lib/derprint.c
@@ -441,17 +441,17 @@ prettyPrintLength(FILE *out, const unsig
 	    if (il < 0) return -1;
 	    *lenp = (unsigned) il;
 	} else {
 	    *lenp = 0;
 	    *indefinitep = PR_TRUE;
 	}
 	lenLen = nb + 1;
 	if (raw) {
-	    int i;
+	    unsigned int i;
 
 	    rv = prettyPrintByte(out, lbyte, lv);
 	    if (rv < 0)
 		return rv;
 	    for (i = 0; i < nb; i++) {
 		rv = prettyPrintByte(out, data[i], lv);
 		if (rv < 0)
 		    return rv;
@@ -498,19 +498,20 @@ prettyPrintItem(FILE *out, const unsigne
 	data += slen;
 
 	lenLen = prettyPrintLength(out, data, end, &slen, &indefinite, lv, raw);
 	if (lenLen < 0)
 	    return lenLen;
 	data += lenLen;
 
 	/*
-	 * Just quit now if slen more bytes puts us off the end.
+	 * Just quit now if slen more bytes puts us off the end,
+	 * or if there's no more data to process.
 	 */
-	if ((data + slen) > end) {
+	if ((data + slen) >= end) {
 	    PORT_SetError(SEC_ERROR_BAD_DER);
 	    return -1;
 	}
 
         if (code & SEC_ASN1_CONSTRUCTED) {
 	    if (slen > 0 || indefinite) {
 		slen = prettyPrintItem(out, data,
 				       slen == 0 ? end : data + slen,
--- a/security/nss/cmd/lib/pk11table.c
+++ b/security/nss/cmd/lib/pk11table.c
@@ -572,17 +572,17 @@ const Constant _consts[] = {
 	mkEntry(CKT_NSS_TRUST_UNKNOWN, Trust),
 	mkEntry(CKT_NSS_VALID_DELEGATOR, Trust),
 
 	mkEntry(CK_EFFECTIVELY_INFINITE, AvailableSizes),
 	mkEntry(CK_UNAVAILABLE_INFORMATION, CurrentSize),
 };
 
 const Constant *consts = &_consts[0];
-const int constCount = sizeof(_consts)/sizeof(_consts[0]);
+const unsigned int constCount = sizeof(_consts)/sizeof(_consts[0]);
 
 const Commands _commands[] = {
     {"C_Initialize", F_C_Initialize,
 "C_Initialize pInitArgs\n\n"
 "C_Initialize initializes the PKCS #11 library.\n"
 "  pInitArgs  if this is not NULL_PTR it gets cast to and dereferenced\n",
 	{ArgInitializeArgs, ArgNone, ArgNone, ArgNone, ArgNone,
 	 ArgNone, ArgNone, ArgNone, ArgNone, ArgNone }},
@@ -1384,17 +1384,17 @@ const Topics _topics[] = {
 };
 
 const Topics  *topics= &_topics[0];
 const int topicCount = sizeof(_topics) / sizeof(_topics[0]);
 
 const char *
 getName(CK_ULONG value, ConstType type)
 {
-    int i;
+    unsigned int i;
     
     for (i=0; i < constCount; i++) {
         if (consts[i].type == type && consts[i].value == value) {
             return consts[i].name;
         }
         if (type == ConstNone && consts[i].value == value) {
             return consts[i].name;
         }
@@ -1404,17 +1404,17 @@ getName(CK_ULONG value, ConstType type)
 }
 
 const char *
 getNameFromAttribute(CK_ATTRIBUTE_TYPE type)
 {
     return getName(type, ConstAttribute);
 }
 
-int totalKnownType(ConstType type) {
-    int count = 0;
-    int i;
+unsigned int totalKnownType(ConstType type) {
+    unsigned int count = 0;
+    unsigned int i;
  
     for (i=0; i < constCount; i++) {
         if (consts[i].type == type) count++;
     }
     return count;
 }
--- a/security/nss/cmd/lib/pk11table.h
+++ b/security/nss/cmd/lib/pk11table.h
@@ -157,24 +157,24 @@ typedef struct _topics {
  * the command array itself. Make name to function and it's arguments
  */
 
 extern const char **valueString;
 extern const int valueCount;
 extern const char **constTypeString;
 extern const int constTypeCount;
 extern const Constant *consts;
-extern const int constCount;
+extern const unsigned int constCount;
 extern const Commands *commands;
 extern const int commandCount;
 extern const Topics *topics;
 extern const int topicCount;
 
 extern const char *
 getName(CK_ULONG value, ConstType type);
 
 extern const char *
 getNameFromAttribute(CK_ATTRIBUTE_TYPE type);
 
-extern int totalKnownType(ConstType type);
+extern unsigned int totalKnownType(ConstType type);
 
 #endif /* _PK11_TABLE_H_ */
 
--- a/security/nss/cmd/lib/secpwd.c
+++ b/security/nss/cmd/lib/secpwd.c
@@ -69,30 +69,32 @@ char *SEC_GetPassword(FILE *input, FILE 
     for (;;) {
 	/* Prompt for password */
 	if (isTTY) {
 	    fprintf(output, "%s", prompt);
             fflush (output);
 	    echoOff(infd);
 	}
 
-	QUIET_FGETS ( phrase, sizeof(phrase), input);
+	if (QUIET_FGETS(phrase, sizeof(phrase), input) == NULL) {
+            return NULL;
+        }
 
 	if (isTTY) {
 	    fprintf(output, "\n");
 	    echoOn(infd);
 	}
 
 	/* stomp on newline */
 	phrase[PORT_Strlen(phrase)-1] = 0;
 
 	/* Validate password */
 	if (!(*ok)(phrase)) {
 	    /* Not weird enough */
-	    if (!isTTY) return 0;
+	    if (!isTTY) return NULL;
 	    fprintf(output, "Password must be at least 8 characters long with one or more\n");
 	    fprintf(output, "non-alphabetic characters\n");
 	    continue;
 	}
 	return (char*) PORT_Strdup(phrase);
     }
 }
 
--- a/security/nss/cmd/lib/secutil.c
+++ b/security/nss/cmd/lib/secutil.c
@@ -370,40 +370,43 @@ SECU_ChangePW2(PK11SlotInfo *slot, char 
 
 	if (PK11_CheckUserPassword(slot, oldpw) != SECSuccess) {
 	    if (pwdata.source == PW_NONE) {
 		PR_fprintf(PR_STDERR, "Invalid password.  Try again.\n");
 	    } else {
 		PR_fprintf(PR_STDERR, "Invalid password.\n");
 		PORT_Memset(oldpw, 0, PL_strlen(oldpw));
 		PORT_Free(oldpw);
-		return SECFailure;
+		rv = SECFailure;
+                goto done;
 	    }
 	} else
 	    break;
 
 	PORT_Free(oldpw);
     }
 
     newpw = secu_InitSlotPassword(slot, PR_FALSE, &newpwdata);
 
-    if (PK11_ChangePW(slot, oldpw, newpw) != SECSuccess) {
+    rv = PK11_ChangePW(slot, oldpw, newpw);
+    if (rv != SECSuccess) {
 	PR_fprintf(PR_STDERR, "Failed to change password.\n");
-	return SECFailure;
+    } else {
+        PR_fprintf(PR_STDOUT, "Password changed successfully.\n");
     }
 
     PORT_Memset(oldpw, 0, PL_strlen(oldpw));
     PORT_Free(oldpw);
 
-    PR_fprintf(PR_STDOUT, "Password changed successfully.\n");
-
 done:
-    PORT_Memset(newpw, 0, PL_strlen(newpw));
-    PORT_Free(newpw);
-    return SECSuccess;
+    if (newpw) {
+        PORT_Memset(newpw, 0, PL_strlen(newpw));
+        PORT_Free(newpw);
+    }
+    return rv;
 }
 
 struct matchobj {
     SECItem index;
     char *nname;
     PRBool found;
 };
 
@@ -1545,17 +1548,17 @@ SECU_PrintDumpDerIssuerAndSerial(FILE *o
     }
 
     PORT_Free(derIssuerB64);
     PORT_Free(derSerialB64);
     
     fprintf(out, "Serial DER as C source: \n{ %d, \"", c->serialNumber.len);
 
     {
-      int i;
+      unsigned int i;
       for (i=0; i < c->serialNumber.len; ++i) {
         unsigned char *chardata = (unsigned char*)(c->serialNumber.data);
         unsigned char c = *(chardata + i);
         
         fprintf(out, "\\x%02x", c);
       }
       fprintf(out, "\" }\n");
     }
@@ -2412,17 +2415,16 @@ loser:
 }
 
 int
 SECU_PrintCertificateBasicInfo(FILE *out, const SECItem *der, const char *m, int level)
 {
     PLArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
     CERTCertificate *c;
     int rv = SEC_ERROR_NO_MEMORY;
-    int iv;
     
     if (!arena)
 	return rv;
 
     /* Decode certificate */
     c = PORT_ArenaZNew(arena, CERTCertificate);
     if (!c)
 	goto loser;
@@ -2738,17 +2740,17 @@ secu_PrintPKCS7Signed(FILE *out, SEC_PKC
 
     /* Parse and list certificates (if any) */
     if (src->rawCerts != NULL) {
 	SECU_Indent(out, level + 1);  fprintf(out, "Certificate List:\n");
 	iv = 0;
 	while ((aCert = src->rawCerts[iv++]) != NULL) {
 	    sprintf(om, "Certificate (%x)", iv);
 	    rv = SECU_PrintSignedData(out, aCert, om, level + 2, 
-				      SECU_PrintCertificate);
+				      (SECU_PPFunc)SECU_PrintCertificate);
 	    if (rv)
 		return rv;
 	}
     }
 
     /* Parse and list CRL's (if any) */
     if (src->crls != NULL) {
 	SECU_Indent(out, level + 1);  
@@ -2857,17 +2859,17 @@ secu_PrintPKCS7SignedAndEnveloped(FILE *
 
     /* Parse and list certificates (if any) */
     if (src->rawCerts != NULL) {
 	SECU_Indent(out, level + 1);  fprintf(out, "Certificate List:\n");
 	iv = 0;
 	while ((aCert = src->rawCerts[iv++]) != NULL) {
 	    sprintf(om, "Certificate (%x)", iv);
 	    rv = SECU_PrintSignedData(out, aCert, om, level + 2, 
-				      SECU_PrintCertificate);
+				      (SECU_PPFunc)SECU_PrintCertificate);
 	    if (rv)
 		return rv;
 	}
     }
 
     /* Parse and list CRL's (if any) */
     if (src->crls != NULL) {
 	SECU_Indent(out, level + 1);  
@@ -3187,17 +3189,17 @@ SEC_PrintCertificateAndTrust(CERTCertifi
     SECStatus rv;
     SECItem data;
     CERTCertTrust certTrust;
     
     data.data = cert->derCert.data;
     data.len = cert->derCert.len;
 
     rv = SECU_PrintSignedData(stdout, &data, label, 0,
-			      SECU_PrintCertificate);
+			      (SECU_PPFunc)SECU_PrintCertificate);
     if (rv) {
 	return(SECFailure);
     }
     if (trust) {
 	SECU_PrintTrustFlags(stdout, trust,
 	                     "Certificate Trust Flags", 1);
     } else if (CERT_GetCertTrust(cert, &certTrust) == SECSuccess) {
 	SECU_PrintTrustFlags(stdout, &certTrust,
@@ -3278,33 +3280,33 @@ SECU_displayVerifyLog(FILE *outfile, CER
 		    }
 		}
 	    }
 	    fprintf(outfile, "  ERROR %ld: %s\n", node->error,
 			    SECU_Strerror(node->error));
 	    errstr = NULL;
 	    switch (node->error) {
 	    case SEC_ERROR_INADEQUATE_KEY_USAGE:
-		flags = (unsigned int)node->arg;
+		flags = (unsigned int)((char *)node->arg - (char *)NULL);
 		switch (flags) {
 		case KU_DIGITAL_SIGNATURE:
 		    errstr = "Cert cannot sign.";
 		    break;
 		case KU_KEY_ENCIPHERMENT:
 		    errstr = "Cert cannot encrypt.";
 		    break;
 		case KU_KEY_CERT_SIGN:
 		    errstr = "Cert cannot sign other certs.";
 		    break;
 		default:
 		    errstr = "[unknown usage].";
 		    break;
 		}
 	    case SEC_ERROR_INADEQUATE_CERT_TYPE:
-		flags = (unsigned int)node->arg;
+		flags = (unsigned int)((char *)node->arg - (char *)NULL);
 		switch (flags) {
 		case NS_CERT_TYPE_SSL_CLIENT:
 		case NS_CERT_TYPE_SSL_SERVER:
 		    errstr = "Cert cannot be used for SSL.";
 		    break;
 		case NS_CERT_TYPE_SSL_CA:
 		    errstr = "Cert cannot be used as an SSL CA.";
 		    break;
--- a/security/nss/cmd/modutil/error.h
+++ b/security/nss/cmd/modutil/error.h
@@ -128,30 +128,12 @@ typedef enum {
 	DEFAULT_SUCCESS_MSG,
 	UNDEFAULT_SUCCESS_MSG,
 	BROWSER_RUNNING_MSG,
 	ABORTING_MSG,
 
 	LAST_MSG  /* must be last */
 } Message;
 
-static char *msgStrings[] = {
-	"FIPS mode enabled.\n",
-	"FIPS mode disabled.\n",
-	"Using database directory %s...\n",
-	"Creating \"%s\"...",
-	"Module \"%s\" added to database.\n",
-	"Module \"%s\" deleted from database.\n",
-	"Token \"%s\" password changed successfully.\n",
-	"Incorrect password, try again...\n",
-	"Passwords do not match, try again...\n",
-	"done.\n",
-	"Slot \"%s\" %s.\n",
-	"Successfully changed defaults.\n",
-	"Successfully changed defaults.\n",
-"\nWARNING: Performing this operation while the browser is running could cause"
-"\ncorruption of your security databases. If the browser is currently running,"
-"\nyou should exit browser before continuing this operation. Type "
-"\n'q <enter>' to abort, or <enter> to continue: ",
-	"\nAborting...\n"
-};
+/* defined in modutil.c */
+extern char *msgStrings[];
 
 #endif /* MODUTIL_ERROR_H */
--- a/security/nss/cmd/modutil/installparse.c
+++ b/security/nss/cmd/modutil/installparse.c
@@ -198,34 +198,34 @@ Pk11Install_yyerror(char *message)
 int
 yyparse()
 {
     register int yym, yyn, yystate;
 #if YYDEBUG
     register char *yys;
     extern char *getenv();
 
-    if (yys = getenv("YYDEBUG"))
+    if ((yys = getenv("YYDEBUG")) != NULL)
     {
         yyn = *yys;
         if (yyn >= '0' && yyn <= '9')
             yydebug = yyn - '0';
     }
 #endif
 
     yynerrs = 0;
     yyerrflag = 0;
     yychar = (-1);
 
     yyssp = yyss;
     yyvsp = yyvs;
     *yyssp = yystate = 0;
 
 yyloop:
-    if (yyn = yydefred[yystate]) goto yyreduce;
+    if ((yyn = yydefred[yystate]) != 0) goto yyreduce;
     if (yychar < 0)
     {
         if ((yychar = yylex()) < 0) yychar = 0;
 #if YYDEBUG
         if (yydebug)
         {
             yys = 0;
             if (yychar <= YYMAXTOKEN) yys = yyname[yychar];
--- a/security/nss/cmd/modutil/lex.Pk11Install_yy.c
+++ b/security/nss/cmd/modutil/lex.Pk11Install_yy.c
@@ -1095,16 +1095,17 @@ register char *yy_bp;
 
 	yytext_ptr = yy_bp;
 	yy_hold_char = *yy_cp;
 	yy_c_buf_p = yy_cp;
 	}
 #endif	/* ifndef YY_NO_UNPUT */
 
 
+#ifndef YY_NO_INPUT
 #ifdef __cplusplus
 static int yyinput()
 #else
 static int input()
 #endif
 	{
 	int c;
 
@@ -1166,16 +1167,17 @@ static int input()
 
 	c = *(unsigned char *) yy_c_buf_p;	/* cast for 8-bit char's */
 	*yy_c_buf_p = '\0';	/* preserve yytext */
 	yy_hold_char = *++yy_c_buf_p;
 
 
 	return c;
 	}
+#endif	/* ifndef YY_NO_INPUT */
 
 
 #ifdef YY_USE_PROTOS
 void yyrestart( FILE *input_file )
 #else
 void yyrestart( input_file )
 FILE *input_file;
 #endif
--- a/security/nss/cmd/modutil/manifest.mn
+++ b/security/nss/cmd/modutil/manifest.mn
@@ -19,16 +19,16 @@ CSRCS = modutil.c		\
 		$(NULL)
 
 CPPSRCS = 
 
 PROGRAM =  modutil
 
 REQUIRES = seccmd nss dbm
 
-DEFINES = -DNSPR20
+DEFINES = -DNSPR20 -DYY_NO_UNPUT -DYY_NO_INPUT
 
 # sigh
 #INCLUDES += -I$(CORE_DEPTH)/nss/lib/pk11wrap
 
 # USE_STATIC_LIBS = 1 
 
 EXTRA_LIBS = $(JAR_LIBS)
--- a/security/nss/cmd/modutil/modutil.c
+++ b/security/nss/cmd/modutil/modutil.c
@@ -117,16 +117,37 @@ static char *optionStrings[] = {
 	"-installdir",
 	"-tempdir",
 	"-secmod",
 	"-nocertdb",
 	"-string",
 	"-chkfips",
 };
 
+char *msgStrings[] = {
+	"FIPS mode enabled.\n",
+	"FIPS mode disabled.\n",
+	"Using database directory %s...\n",
+	"Creating \"%s\"...",
+	"Module \"%s\" added to database.\n",
+	"Module \"%s\" deleted from database.\n",
+	"Token \"%s\" password changed successfully.\n",
+	"Incorrect password, try again...\n",
+	"Passwords do not match, try again...\n",
+	"done.\n",
+	"Slot \"%s\" %s.\n",
+	"Successfully changed defaults.\n",
+	"Successfully changed defaults.\n",
+"\nWARNING: Performing this operation while the browser is running could cause"
+"\ncorruption of your security databases. If the browser is currently running,"
+"\nyou should exit browser before continuing this operation. Type "
+"\n'q <enter>' to abort, or <enter> to continue: ",
+	"\nAborting...\n"
+};
+
 /* Increment i if doing so would have i still be less than j.  If you
    are able to do this, return 0.  Otherwise return 1. */
 #define TRY_INC(i,j)  ( ((i+1)<j) ? (++i, 0) : 1 )
 
 /********************************************************************
  *
  * file-wide variables obtained from the command line
  */
--- a/security/nss/cmd/multinit/multinit.c
+++ b/security/nss/cmd/multinit/multinit.c
@@ -309,37 +309,16 @@ appendHex(unsigned char nibble)
     if (nibble <= 9) {
 	appendLabel('0'+nibble);
     } else {
 	appendLabel('a'+nibble-10);
     }
 }
 
 /*
- * append a secitem as colon separated hex bytes.
- */
-static void
-appendItem(SECItem *item)
-{
-    int i;
-
-    if (!buffer.data) {
-	return;
-    }
-
-    appendLabel(':');
-    for (i=0; i < item->len; i++) {
-	unsigned char byte=item->data[i];
-	appendHex(byte >> 4);
-	appendHex(byte & 0xf);
-	appendLabel(':');
-    }
-}
-
-/*
  * append a 32 bit integer (even on a 64 bit platform).
  * for simplicity append it as a hex value, full extension with 0x prefix.
  */
 static void
 appendInt(unsigned int value)
 {
     int i;
 
@@ -488,17 +467,17 @@ sort_CN(CERTCertificate *certa, CERTCert
  */
 void
 do_list_certs(const char *progName, int log)
 {
    CERTCertList *list;
    CERTCertList *sorted;
    CERTCertListNode *node;
    CERTCertTrust trust;
-   int i;
+   unsigned int i;
 
    list = PK11_ListCerts(PK11CertListUnique, NULL);
    if (list == NULL) {
 	fprintf(stderr,"ERROR: no certs found %s\n", 
 		SECU_Strerror(PORT_GetError()));
 	appendLabel('C');
 	appendString("none");
 	return;
--- a/security/nss/cmd/ocspclnt/ocspclnt.c
+++ b/security/nss/cmd/ocspclnt/ocspclnt.c
@@ -557,17 +557,17 @@ print_raw_certificates (FILE *out_file, 
 	fprintf (out_file, "No Certificates.\n");
 	return;
     }
 
     fprintf (out_file, "Certificate List:\n");
     while ((raw_cert = raw_certs[i++]) != NULL) {
 	sprintf (cert_label, "Certificate (%d)", i);
 	(void) SECU_PrintSignedData (out_file, raw_cert, cert_label, level + 1,
-				     SECU_PrintCertificate);
+				     (SECU_PPFunc)SECU_PrintCertificate);
     }
 }
 
 
 static void
 print_ocsp_extensions (FILE *out_file, CERTCertExtension **extensions,
 		       char *msg, int level)
 {
@@ -959,17 +959,17 @@ main (int argc, char **argv)
     int		 ccert, vcert;
     const char	*db_dir, *date_str, *cert_usage_str, *name;
     const char	*responder_name, *responder_url, *signer_name;
     PRBool	 add_acceptable_responses, add_service_locator;
     SECItem	*data = NULL;
     PLOptState	*optstate;
     SECStatus	 rv;
     CERTCertDBHandle *handle = NULL;
-    SECCertUsage cert_usage;
+    SECCertUsage cert_usage = certUsageSSLClient;
     PRTime	 verify_time;
     CERTCertificate *cert = NULL;
     PRBool ascii = PR_FALSE;
 
     retval = -1;		/* what we return/exit with on error */
 
     program_name = PL_strrchr(argv[0], '/');
     program_name = program_name ? (program_name + 1) : argv[0];
--- a/security/nss/cmd/ocspresp/ocspresp.c
+++ b/security/nss/cmd/ocspresp/ocspresp.c
@@ -124,25 +124,22 @@ main(int argc, char **argv)
     CERTCertDBHandle *certHandle = NULL;
     CERTCertificate *caCert = NULL, *cert = NULL;
     CERTOCSPCertID *cid = NULL;
     PLArenaPool *arena = NULL;
     PRTime now = PR_Now();
     
     SECItem *encoded = NULL;
     CERTOCSPResponse *decoded = NULL;
-    SECStatus statusDecoded;
 
     SECItem *encodedRev = NULL;
     CERTOCSPResponse *decodedRev = NULL;
-    SECStatus statusDecodedRev;
     
     SECItem *encodedFail = NULL;
     CERTOCSPResponse *decodedFail = NULL;
-    SECStatus statusDecodedFail;
 
     CERTCertificate *obtainedSignerCert = NULL;
 
     if (argc != 4 && argc != 6) {
         return Usage();
     }
 
     if (argc == 6) {
@@ -176,50 +173,57 @@ main(int argc, char **argv)
         goto loser;
 
     cid = CERT_CreateOCSPCertID(cert, now);
 
     arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
     encoded = encode(arena, cid, caCert);
     PORT_Assert(encoded);
     decoded = CERT_DecodeOCSPResponse(encoded);
-    statusDecoded = CERT_GetOCSPResponseStatus(decoded);
-    PORT_Assert(statusDecoded == SECSuccess);
+    PORT_CheckSuccess(CERT_GetOCSPResponseStatus(decoded));
 
-    statusDecoded = CERT_VerifyOCSPResponseSignature(decoded, certHandle, &pwdata,
-                                                &obtainedSignerCert, caCert);
-    PORT_Assert(statusDecoded == SECSuccess);
-    statusDecoded = CERT_GetOCSPStatusForCertID(certHandle, decoded, cid,
-                                                obtainedSignerCert, now);
-    PORT_Assert(statusDecoded == SECSuccess);
+    PORT_CheckSuccess(CERT_VerifyOCSPResponseSignature(decoded, certHandle, &pwdata,
+                                                        &obtainedSignerCert, caCert));
+    PORT_CheckSuccess(CERT_GetOCSPStatusForCertID(certHandle, decoded, cid,
+                                                   obtainedSignerCert, now));
     CERT_DestroyCertificate(obtainedSignerCert);
 
     encodedRev = encodeRevoked(arena, cid, caCert);
     PORT_Assert(encodedRev);
     decodedRev = CERT_DecodeOCSPResponse(encodedRev);
-    statusDecodedRev = CERT_GetOCSPResponseStatus(decodedRev);
-    PORT_Assert(statusDecodedRev == SECSuccess);
+    PORT_CheckSuccess(CERT_GetOCSPResponseStatus(decodedRev));
 
-    statusDecodedRev = CERT_VerifyOCSPResponseSignature(decodedRev, certHandle, &pwdata,
-                                                        &obtainedSignerCert, caCert);
-    PORT_Assert(statusDecodedRev == SECSuccess);
-    statusDecodedRev = CERT_GetOCSPStatusForCertID(certHandle, decodedRev, cid,
+    PORT_CheckSuccess(CERT_VerifyOCSPResponseSignature(decodedRev, certHandle, &pwdata,
+                                                        &obtainedSignerCert, caCert));
+#ifdef DEBUG
+    {
+        SECStatus rv = CERT_GetOCSPStatusForCertID(certHandle, decodedRev, cid,
                                                    obtainedSignerCert, now);
-    PORT_Assert(statusDecodedRev == SECFailure);
-    PORT_Assert(PORT_GetError() == SEC_ERROR_REVOKED_CERTIFICATE);
+        PORT_Assert(rv == SECFailure);
+        PORT_Assert(PORT_GetError() == SEC_ERROR_REVOKED_CERTIFICATE);
+    }
+#else
+    (void)CERT_GetOCSPStatusForCertID(certHandle, decodedRev, cid,
+                                      obtainedSignerCert, now);
+#endif
     CERT_DestroyCertificate(obtainedSignerCert);
     
     encodedFail = CERT_CreateEncodedOCSPErrorResponse(
         arena, SEC_ERROR_OCSP_TRY_SERVER_LATER);
     PORT_Assert(encodedFail);
     decodedFail = CERT_DecodeOCSPResponse(encodedFail);
-    statusDecodedFail = CERT_GetOCSPResponseStatus(decodedFail);
-    PORT_Assert(statusDecodedFail == SECFailure);
-    PORT_Assert(PORT_GetError() == SEC_ERROR_OCSP_TRY_SERVER_LATER);
-
+#ifdef DEBUG
+    {
+        SECStatus rv = CERT_GetOCSPResponseStatus(decodedFail);
+        PORT_Assert(rv == SECFailure);
+        PORT_Assert(PORT_GetError() == SEC_ERROR_OCSP_TRY_SERVER_LATER);
+    }
+#else
+    (void)CERT_GetOCSPResponseStatus(decodedFail);
+#endif
     retval = 0;
 loser:
     if (retval != 0)
         SECU_PrintError(argv[0], "tests failed");
     
     if (cid)
         CERT_DestroyOCSPCertID(cid);
     if (cert)
--- a/security/nss/cmd/oidcalc/oidcalc.c
+++ b/security/nss/cmd/oidcalc/oidcalc.c
@@ -39,23 +39,23 @@ main(int argc, char **argv)
     nextstr = strchr(curstr, '.');
 
     if ( nextstr ) {
 	*nextstr = '\0';
     }
 
     secondval = atoi(curstr);
     
-    if ( ( firstval < 0 ) || ( firstval > 2 ) ) {
+    if ( firstval > 2 ) {
 	fprintf(stderr, "first component out of range\n");
 	exit(-1);
 	
     }
     
-    if ( ( secondval < 0 ) || ( secondval > 39 ) ) {
+    if ( secondval > 39 ) {
 	fprintf(stderr, "second component out of range\n");
 	exit(-1);
     }
     
     printf("0x%x, ", ( firstval * 40 ) + secondval );
     while ( nextstr ) {
 	curstr = nextstr + 1;
 
--- a/security/nss/cmd/p7env/p7env.c
+++ b/security/nss/cmd/p7env/p7env.c
@@ -125,29 +125,27 @@ EncryptFile(FILE *outFile, FILE *inFile,
     return 0;
 }
 
 int
 main(int argc, char **argv)
 {
     char *progName;
     FILE *inFile, *outFile;
-    char *certName;
     CERTCertDBHandle *certHandle;
     struct recipient *recipients, *rcpt;
     PLOptState *optstate;
     PLOptStatus status;
     SECStatus rv;
 
     progName = strrchr(argv[0], '/');
     progName = progName ? progName+1 : argv[0];
 
     inFile = NULL;
     outFile = NULL;
-    certName = NULL;
     recipients = NULL;
     rcpt = NULL;
 
     /*
      * Parse command line arguments
      * XXX This needs to be enhanced to allow selection of algorithms
      * and key sizes (or to look up algorithms and key sizes for each
      * recipient in the magic database).
--- a/security/nss/cmd/pk11gcmtest/pk11gcmtest.c
+++ b/security/nss/cmd/pk11gcmtest/pk11gcmtest.c
@@ -161,32 +161,32 @@ aes_gcm_kat(const char *respfn)
 {
     char buf[512];      /* holds one line from the input REQUEST file.
                          * needs to be large enough to hold the longest
                          * line "CIPHERTEXT = <320 hex digits>\n".
                          */
     FILE *aesresp;      /* input stream from the RESPONSE file */
     int i, j;
     unsigned int test_group = 0;
-    unsigned int num_tests;
+    unsigned int num_tests = 0;
     PRBool is_encrypt;
     unsigned char key[32];              /* 128, 192, or 256 bits */
-    unsigned int keysize;
+    unsigned int keysize = 16;
     unsigned char iv[10*16];            /* 1 to 10 blocks */
-    unsigned int ivsize;
+    unsigned int ivsize = 12;
     unsigned char plaintext[10*16];     /* 1 to 10 blocks */
     unsigned int plaintextlen = 0;
     unsigned char aad[10*16];           /* 1 to 10 blocks */
     unsigned int aadlen = 0;
     unsigned char ciphertext[10*16];    /* 1 to 10 blocks */
-    unsigned int ciphertextlen;
+    unsigned int ciphertextlen = 0;
     unsigned char tag[16];
-    unsigned int tagsize;
+    unsigned int tagsize = 16;
     unsigned char output[10*16];         /* 1 to 10 blocks */
-    unsigned int outputlen;
+    unsigned int outputlen = 0;
 
     unsigned int expected_keylen = 0;
     unsigned int expected_ivlen = 0;
     unsigned int expected_ptlen = 0;
     unsigned int expected_aadlen = 0;
     unsigned int expected_taglen = 0;
     SECStatus rv;
 
--- a/security/nss/cmd/pk11mode/pk11mode.c
+++ b/security/nss/cmd/pk11mode/pk11mode.c
@@ -2085,27 +2085,27 @@ CK_RV PKM_Mechanism(CK_FUNCTION_LIST_PTR
                                             pMechanismList, &mechanismCount);
     if (crv != CKR_OK) {
         PKM_Error( "C_GetMechanismList failed with 0x%08X, %-26s\n", crv, 
                    PKM_CK_RVtoStr(crv));
         return crv;
     }
     PKM_LogIt("C_GetMechanismList returned the mechanism types:\n");
     if (verbose) {
-        for (i = 1; i <= mechanismCount; i++) {
-            mechName = getName(pMechanismList[(i-1)], ConstMechanism);
+        for (i = 0; i < mechanismCount; i++) {
+            mechName = getName(pMechanismList[(i)], ConstMechanism);
 
             /* output two mechanism name on each line */
             /* currently the longest known mechansim name length is 37 */
             if (mechName) {
                 printf("%-40s",mechName);
             } else {
                 printf("Unknown mechanism: 0x%08lX ", pMechanismList[i]);
             }    
-            if ((i != 0) && ((i % 2) == 0 )) printf("\n");
+            if ((i % 2) == 1 ) printf("\n");
         }
         printf("\n\n");
     }
 
     for ( i = 0; i < mechanismCount; i++ ) {
         CK_MECHANISM_INFO minfo;
 
         memset(&minfo, 0, sizeof(CK_MECHANISM_INFO));
@@ -3501,18 +3501,18 @@ CK_RV PKM_FindAllObjects(CK_FUNCTION_LIS
                          CK_UTF8CHAR_PTR pwd, CK_ULONG pwdLen) {
     CK_RV crv = CKR_OK;
 
     CK_SESSION_HANDLE h = (CK_SESSION_HANDLE)0;
     CK_SESSION_INFO sinfo;
     CK_ATTRIBUTE_PTR pTemplate;
     CK_ULONG tnObjects = 0;
     int curMode;
-    int i;
-    int  number_of_all_known_attribute_types = totalKnownType(ConstAttribute);
+    unsigned int i;
+    unsigned int  number_of_all_known_attribute_types = totalKnownType(ConstAttribute);
 
     NUMTESTS++; /* increment NUMTESTS */
 
     crv = pFunctionList->C_OpenSession(pSlotList[slotID], CKF_SERIAL_SESSION,
                                        NULL, NULL, &h);
     if ( CKR_OK != crv ) {
         PKM_Error("C_OpenSession(%lu, CKF_SERIAL_SESSION, , )"
                   "returned 0x%08X, %-26s\n", pSlotList[slotID], crv, 
@@ -4553,17 +4553,17 @@ CK_RV
 PKM_TLSMasterKeyDerive( CK_FUNCTION_LIST_PTR pFunctionList,
                         CK_SLOT_ID * pSlotList, CK_ULONG slotID,
                         CK_UTF8CHAR_PTR pwd, CK_ULONG pwdLen,
                         CK_MECHANISM_TYPE mechType,
                         enum_random_t rnd)  {
     CK_SESSION_HANDLE hSession;
     CK_RV crv;
     CK_MECHANISM            mk_mech;
-    CK_VERSION              expected_version, version;
+    CK_VERSION              version;
     CK_OBJECT_CLASS         class = CKO_SECRET_KEY;
     CK_KEY_TYPE             type = CKK_GENERIC_SECRET;
     CK_BBOOL                derive_bool = true;
     CK_ATTRIBUTE            attrs[4];
     CK_ULONG                attrs_count = 4;
     CK_OBJECT_HANDLE        pmk_obj = CK_INVALID_HANDLE;
     CK_OBJECT_HANDLE        mk_obj = CK_INVALID_HANDLE;
     CK_SSL3_MASTER_KEY_DERIVE_PARAMS mkd_params;
@@ -4620,18 +4620,16 @@ PKM_TLSMasterKeyDerive( CK_FUNCTION_LIST
 
     switch (mechType) {
     case CKM_TLS_MASTER_KEY_DERIVE_DH:
         isDH = true;
         /* FALLTHRU */
     case CKM_TLS_MASTER_KEY_DERIVE:
         attrs[3].pValue = NULL;
         attrs[3].ulValueLen = 0;
-        expected_version.major = 3;
-        expected_version.minor = 1;
 
         mkd_params.RandomInfo.pClientRandom = (unsigned char * ) TLSClientRandom;
         mkd_params.RandomInfo.ulClientRandomLen =
         sizeof (TLSClientRandom);
         mkd_params.RandomInfo.pServerRandom = (unsigned char * ) TLSServerRandom;
         mkd_params.RandomInfo.ulServerRandomLen =
         sizeof (TLSServerRandom);
         break;
--- a/security/nss/cmd/pk12util/pk12util.c
+++ b/security/nss/cmd/pk12util/pk12util.c
@@ -751,17 +751,17 @@ P12U_ListPKCS12File(char *in_file, PK11S
 			                    "Cannot create output file");
 			} else {
 			    PR_Write(fd, dip->der->data, dip->der->len);
 			    PR_Close(fd);
 			}
 		    } else 
                     if (SECU_PrintSignedData(stdout, dip->der,
                             (dip->hasKey) ? "(has private key)" : "",
-                             0, SECU_PrintCertificate) != 0) {
+                             0, (SECU_PPFunc)SECU_PrintCertificate) != 0) {
                         SECU_PrintError(progName,"PKCS12 print cert bag failed");
                     }
                     if (dip->friendlyName != NULL) {
                         printf("    Friendly Name: %s\n\n",
                                 dip->friendlyName->data);
                     }
 		    if (dip->shroudAlg) {
 			SECU_PrintAlgorithmID(stdout, dip->shroudAlg,
--- a/security/nss/cmd/pk1sign/pk1sign.c
+++ b/security/nss/cmd/pk1sign/pk1sign.c
@@ -170,17 +170,17 @@ SignFile(FILE *outFile, PRFileDesc *inFi
 int
 main(int argc, char **argv)
 {
     char *progName;
     FILE *outFile;
     PRFileDesc *inFile;
     char *keyName = NULL;
     CERTCertDBHandle *certHandle;
-    CERTCertificate *cert;
+    CERTCertificate *cert = NULL;
     PLOptState *optstate;
     PLOptStatus status;
     SECStatus rv;
 
     progName = strrchr(argv[0], '/');
     progName = progName ? progName+1 : argv[0];
 
     inFile = NULL;
--- a/security/nss/cmd/pp/pp.c
+++ b/security/nss/cmd/pp/pp.c
@@ -20,18 +20,21 @@ extern int fprintf(FILE *, char *, ...);
 #include "nss.h"
 
 static void Usage(char *progName)
 {
     fprintf(stderr,
 	    "Usage:  %s [-t type] [-a] [-i input] [-o output] [-w] [-u]\n",
 	    progName);
     fprintf(stderr, "Pretty prints a file containing ASN.1 data in DER or ascii format.\n");
-    fprintf(stderr, "%-14s Specify input and display type: %s (sk),\n",
-	    "-t type", SEC_CT_PRIVATE_KEY);
+    fprintf(stderr, "%-14s Specify input and display type:", "-t type");
+#ifdef HAVE_EPV_TEMPLATE
+    fprintf(stderr, " %s (sk),", SEC_CT_PRIVATE_KEY);
+#endif
+    fprintf(stderr, "\n");
     fprintf(stderr, "%-14s %s (pk), %s (c), %s (cr),\n", "", SEC_CT_PUBLIC_KEY,
 	    SEC_CT_CERTIFICATE, SEC_CT_CERTIFICATE_REQUEST);
     fprintf(stderr, "%-14s %s (ci), %s (p7), %s or %s (n).\n", "", SEC_CT_CERTIFICATE_ID,
             SEC_CT_PKCS7, SEC_CT_CRL, SEC_CT_NAME);
     fprintf(stderr, "%-14s (Use either the long type name or the shortcut.)\n", "");
     fprintf(stderr, "%-14s Input is in ascii encoded form (RFC1113)\n",
 	    "-a");
     fprintf(stderr, "%-14s Define an input file to use (default is stdin)\n",
@@ -131,17 +134,17 @@ int main(int argc, char **argv)
     data.len = der.len;
 
     SECU_EnableWrap(wrap);
 
     /* Pretty print it */
     if (PORT_Strcmp(typeTag, SEC_CT_CERTIFICATE) == 0 ||
         PORT_Strcmp(typeTag, "c") == 0) {
 	rv = SECU_PrintSignedData(outFile, &data, "Certificate", 0,
-			     SECU_PrintCertificate);
+			     (SECU_PPFunc)SECU_PrintCertificate);
     } else if (PORT_Strcmp(typeTag, SEC_CT_CERTIFICATE_ID) == 0 ||
                PORT_Strcmp(typeTag, "ci") == 0) {
         rv = SECU_PrintSignedContent(outFile, &data, 0, 0,
                                      SECU_PrintDumpDerIssuerAndSerial);
     } else if (PORT_Strcmp(typeTag, SEC_CT_CERTIFICATE_REQUEST) == 0 ||
                PORT_Strcmp(typeTag, "cr") == 0) {
 	rv = SECU_PrintSignedData(outFile, &data, "Certificate Request", 0,
 			     SECU_PrintCertificateRequest);
--- a/security/nss/cmd/sdrtest/sdrtest.c
+++ b/security/nss/cmd/sdrtest/sdrtest.c
@@ -66,19 +66,19 @@ long_usage (char *program_name)
     PR_fprintf (pr_stderr,
 		"  %-13s supply \"password\" on the command line\n",
 		"-p password");
 }
 
 int 
 readStdin(SECItem * result)
 {
-  int bufsize = 0;
+  unsigned int bufsize = 0;
   int cc;
-  int wanted  = 8192;
+  unsigned int wanted  = 8192U;
 
   result->len = 0;
   result->data = NULL;
   do {
     if (bufsize < wanted) {
       unsigned char * tmpData = (unsigned char *)PR_Realloc(result->data, wanted);
       if (!tmpData) {
 	if (verbose) PR_fprintf(pr_stderr, "Allocation of buffer failed\n");
--- a/security/nss/cmd/selfserv/selfserv.c
+++ b/security/nss/cmd/selfserv/selfserv.c
@@ -60,29 +60,29 @@ static int handle_connection( PRFileDesc
 
 static const char envVarName[] = { SSL_ENV_VAR_NAME };
 static const char inheritableSockName[] = { "SELFSERV_LISTEN_SOCKET" };
 
 #define DEFAULT_BULK_TEST 16384
 #define MAX_BULK_TEST     1048576 /* 1 MB */
 static PRBool testBulk;
 static PRUint32 testBulkSize       = DEFAULT_BULK_TEST;
-static PRUint32 testBulkTotal;
+static PRInt32 testBulkTotal;
 static char* testBulkBuf;
 static PRDescIdentity log_layer_id = PR_INVALID_IO_LAYER;
 static PRFileDesc *loggingFD;
 static PRIOMethods loggingMethods;
 
 static PRBool logStats;
 static PRBool loggingLayer;
 static int logPeriod = 30;
-static PRUint32 loggerOps;
-static PRUint32 loggerBytes;
-static PRUint32 loggerBytesTCP;
-static PRUint32 bulkSentChunks;
+static PRInt32 loggerOps;
+static PRInt32 loggerBytes;
+static PRInt32 loggerBytesTCP;
+static PRInt32 bulkSentChunks;
 static enum ocspStaplingModeEnum {
     osm_disabled,  /* server doesn't support stapling */
     osm_good,      /* supply a signed good status */
     osm_revoked,   /* supply a signed revoked status */
     osm_unknown,   /* supply a signed unknown status */
     osm_failure,   /* supply a unsigned failure status, "try later" */
     osm_badsig,    /* supply a good status response with a bad signature */
     osm_corrupted, /* supply a corrupted data block as the status */
@@ -423,20 +423,21 @@ printSecurityInfo(PRFileDesc *fd)
 	if (result == SECSuccess) {
 	    FPRINTF(stderr, 
 	    "selfserv: SSL version %d.%d using %d-bit %s with %d-bit %s MAC\n",
 	       channel.protocolVersion >> 8, channel.protocolVersion & 0xff,
 	       suite.effectiveKeyBits, suite.symCipherName, 
 	       suite.macBits, suite.macAlgorithmName);
 	    FPRINTF(stderr, 
 	    "selfserv: Server Auth: %d-bit %s, Key Exchange: %d-bit %s\n"
-	    "          Compression: %s\n",
+            "          Compression: %s, Extended Master Secret: %s\n",
 	       channel.authKeyBits, suite.authAlgorithmName,
 	       channel.keaKeyBits,  suite.keaTypeName,
-	       channel.compressionMethodName);
+               channel.compressionMethodName,
+               channel.extendedMasterSecretUsed ? "Yes": "No");
     	}
     }
     if (verbose) {
         SECItem *hostInfo  = SSL_GetNegotiatedHostInfo(fd);
         if (hostInfo) {
             char namePref[] = "selfserv: Negotiated server name: ";
 
             fprintf(stderr, "%s", namePref);
@@ -497,18 +498,18 @@ mySSLSNISocketConfig(PRFileDesc *fd, con
 
     PORT_Assert(fd && sniNameArr);
     if (!fd || !sniNameArr) {
 	return SSL_SNI_SEND_ALERT;
     }
 
     pwdata = SSL_RevealPinArg(fd);
 
-    for (;current && i < sniNameArrSize;i++) {
-        int j = 0;
+    for (;current && (PRUint32)i < sniNameArrSize;i++) {
+        unsigned int j = 0;
         for (;j < MAX_VIRT_SERVER_NAME_ARRAY_INDEX && nameArr[j];j++) {
             if (!PORT_Strncmp(nameArr[j],
                               (const char *)current[i].data,
                               current[i].len) &&
                 PORT_Strlen(nameArr[j]) == current[i].len) {
                 const char *nickName = nameArr[j];
                 if (j == 0) {
                     /* default cert */
@@ -746,18 +747,18 @@ terminateWorkerThreads(void)
 static void 
 logger(void *arg)
 {
     PRFloat64 seconds;
     PRFloat64 opsPerSec;
     PRIntervalTime period;
     PRIntervalTime previousTime;
     PRIntervalTime latestTime;
-    PRUint32 previousOps;
-    PRUint32 ops;
+    PRInt32 previousOps;
+    PRInt32 ops;
     PRIntervalTime logPeriodTicks = PR_TicksPerSecond();
     PRFloat64 secondsPerTick = 1.0 / (PRFloat64)logPeriodTicks;
     int iterations = 0;
     int secondsElapsed = 0;
     static PRInt64 totalPeriodBytes = 0;
     static PRInt64 totalPeriodBytesTCP = 0;
 
     previousOps = loggerOps;
@@ -766,17 +767,17 @@ logger(void *arg)
     for (;;) {
         /* OK, implementing a new sleep algorithm here... always sleep 
          * for 1 second but print out info at the user-specified interval.
          * This way, we don't overflow all of our PR_Atomic* functions and 
          * we don't have to use locks. 
          */
         PR_Sleep(logPeriodTicks);
         secondsElapsed++;
-        totalPeriodBytes +=  PR_ATOMIC_SET(&loggerBytes, 0);
+        totalPeriodBytes += PR_ATOMIC_SET(&loggerBytes, 0);
         totalPeriodBytesTCP += PR_ATOMIC_SET(&loggerBytesTCP, 0);
         if (secondsElapsed != logPeriod) {
             continue;
         }
         /* when we reach the user-specified logging interval, print out all
          * data 
          */
         secondsElapsed = 0;
@@ -832,16 +833,18 @@ PRBool NoReuse         = PR_FALSE;
 PRBool hasSidCache     = PR_FALSE;
 PRBool disableStepDown = PR_FALSE;
 PRBool bypassPKCS11    = PR_FALSE;
 PRBool disableLocking  = PR_FALSE;
 PRBool testbypass      = PR_FALSE;
 PRBool enableSessionTickets = PR_FALSE;
 PRBool enableCompression    = PR_FALSE;
 PRBool failedToNegotiateName  = PR_FALSE;
+PRBool enableExtendedMasterSecret = PR_FALSE;
+
 static char  *virtServerNameArray[MAX_VIRT_SERVER_NAME_ARRAY_INDEX];
 static int                  virtServerNameIndex = 1;
 
 
 static const char stopCmd[] = { "GET /stop " };
 static const char getCmd[]  = { "GET " };
 static const char EOFmsg[]  = { "EOF\r\n\r\n\r\n" };
 static const char outHeader[] = {
@@ -1124,48 +1127,48 @@ makeCorruptedOCSPResponse(PLArenaPool *a
 
 SECItemArray *
 makeSignedOCSPResponse(PLArenaPool *arena, ocspStaplingModeType osm,
 		       CERTCertificate *cert, secuPWData *pwdata)
 {
     SECItemArray *result = NULL;
     SECItem *ocspResponse = NULL;
     CERTOCSPSingleResponse **singleResponses;
-    CERTOCSPSingleResponse *sr;
+    CERTOCSPSingleResponse *sr = NULL;
     CERTOCSPCertID *cid = NULL;
     CERTCertificate *ca;
     PRTime now = PR_Now();
     PRTime nextUpdate;
 
     PORT_Assert(cert != NULL);
 
     ca = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), ocspStaplingCA);
     if (!ca)
 	errExit("cannot find CA");
 
     cid = CERT_CreateOCSPCertID(cert, now);
     if (!cid)
 	errExit("cannot created cid");
 
-    nextUpdate = now + 60*60*24 * PR_USEC_PER_SEC; /* plus 1 day */
+    nextUpdate = now + (PRTime)60*60*24 * PR_USEC_PER_SEC; /* plus 1 day */
 
     switch (osm) {
 	case osm_good:
 	case osm_badsig:
 	    sr = CERT_CreateOCSPSingleResponseGood(arena, cid, now,
 						   &nextUpdate);
 	    break;
 	case osm_unknown:
 	    sr = CERT_CreateOCSPSingleResponseUnknown(arena, cid, now,
 						      &nextUpdate);
 	    break;
 	case osm_revoked:
 	    sr = CERT_CreateOCSPSingleResponseRevoked(arena, cid, now,
 		&nextUpdate,
-		now - 60*60*24 * PR_USEC_PER_SEC, /* minus 1 day */
+		now - (PRTime)60*60*24 * PR_USEC_PER_SEC, /* minus 1 day */
 		NULL);
 	    break;
 	default:
 	    PORT_Assert(0);
 	    break;
     }
 
     if (!sr)
@@ -1937,16 +1940,23 @@ server_main(
 
     if (configureWeakDHE > -1) {
 	rv = SSL_EnableWeakDHEPrimeGroup(model_sock, (configureWeakDHE > 0));
         if (rv != SECSuccess) {
             errExit("error configuring weak DHE prime group");
         }
     }
 
+    if  (enableExtendedMasterSecret) {
+        rv = SSL_OptionSet(model_sock, SSL_ENABLE_EXTENDED_MASTER_SECRET, PR_TRUE);
+	if (rv != SECSuccess) {
+	    errExit("error enabling extended master secret ");
+	}
+    }
+
     for (kea = kt_rsa; kea < kt_kea_size; kea++) {
 	if (cert[kea] != NULL) {
 	    secStatus = SSL_ConfigSecureServer(model_sock, 
 	    		cert[kea], privKey[kea], kea);
 	    if (secStatus != SECSuccess)
 		errExit("SSL_ConfigSecureServer");
 	}
     }
@@ -2213,32 +2223,34 @@ main(int argc, char **argv)
 
     PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
     SSL_VersionRangeGetSupported(ssl_variant_stream, &enabledVersions);
 
     /* please keep this list of options in ASCII collating sequence.
     ** numbers, then capital letters, then lower case, alphabetical. 
     */
     optstate = PL_CreateOptState(argc, argv, 
-        "2:A:BC:DEH:L:M:NP:RS:T:U:V:W:Ya:bc:d:e:f:g:hi:jk:lmn:op:qrst:uvw:xyz");
+        "2:A:BC:DEGH:L:M:NP:RS:T:U:V:W:Ya:bc:d:e:f:g:hi:jk:lmn:op:qrst:uvw:xyz");
     while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
 	++optionsFound;
 	switch(optstate->option) {
 	case '2': fileName = optstate->value; break;
 
 	case 'A': ocspStaplingCA = PORT_Strdup(optstate->value); break;
 
 	case 'B': bypassPKCS11 = PR_TRUE; break;
 
         case 'C': if (optstate->value) NumSidCacheEntries = PORT_Atoi(optstate->value); break;
 
 	case 'D': noDelay = PR_TRUE; break;
 	case 'E': disableStepDown = PR_TRUE; break;
 	case 'H': configureDHE = (PORT_Atoi(optstate->value) != 0); break;
 
+        case 'G': enableExtendedMasterSecret = PR_TRUE; break;
+
 	case 'I': /* reserved for OCSP multi-stapling */ break;
 
         case 'L':
             logStats = PR_TRUE;
 	    if (optstate->value == NULL) {
 	    	logPeriod = 30;
 	    } else {
                 logPeriod  = PORT_Atoi(optstate->value);
--- a/security/nss/cmd/shlibsign/shlibsign.c
+++ b/security/nss/cmd/shlibsign/shlibsign.c
@@ -190,16 +190,20 @@ static const unsigned char base[] = {
     0x08, 0xcd, 0x68, 0x3a, 0x77, 0xc2, 0xc5, 0xf1, 
     0x99, 0x0f, 0x15, 0x1b, 0x6a, 0x8c, 0x3d, 0x18, 
     0x2b, 0x6f, 0xdc, 0x2b, 0xd8, 0xb5, 0x9b, 0xb8, 
     0x2d, 0x57, 0x92, 0x1c, 0x46, 0x27, 0xaf, 0x6d, 
     0xe1, 0x45, 0xcf, 0x0b, 0x3f, 0xfa, 0x07, 0xcc, 
     0x14, 0x8e, 0xe7, 0xb8, 0xaa, 0xd5, 0xd1, 0x36, 
     0x1d, 0x7e, 0x5e, 0x7d, 0xfa, 0x5b, 0x77, 0x1f };
 
+/*
+ * The constants h, seed, & counter aren't used in the code; they're provided
+ * here (commented-out) so that human readers can verify that our our PQG
+ * parameters were generated properly.
 static const unsigned char h[] = { 
     0x41, 0x87, 0x47, 0x79, 0xd8, 0xba, 0x4e, 0xac, 
     0x44, 0x4f, 0x6b, 0xd2, 0x16, 0x5e, 0x04, 0xc6, 
     0xc2, 0x29, 0x93, 0x5e, 0xbd, 0xc7, 0xa9, 0x8f, 
     0x23, 0xa1, 0xc8, 0xee, 0x80, 0x64, 0xd5, 0x67, 
     0x3c, 0xba, 0x59, 0x9a, 0x06, 0x0c, 0xcc, 0x29, 
     0x56, 0xc0, 0xb2, 0x21, 0xe0, 0x5b, 0x52, 0xcd, 
     0x84, 0x73, 0x57, 0xfd, 0xd8, 0xc3, 0x5b, 0x13, 
@@ -227,16 +231,17 @@ static const unsigned char seed[] = { 0x
     0x4f, 0x4c, 0x58, 0x1c, 0x7f, 0x61, 0x3c, 0x36, 
     0xd5, 0x2f, 0xa5, 0x66, 0xd8, 0x2f, 0xce, 0x6e, 
     0x8e, 0x20, 0x48, 0x4a, 0xbb, 0xe3, 0xe0, 0xb2, 
     0x50, 0x33, 0x63, 0x8a, 0x5b, 0x2d, 0x6a, 0xbe, 
     0x4c, 0x28, 0x81, 0x53, 0x5b, 0xe4, 0xf6, 0xfc, 
     0x64, 0x06, 0x13, 0x51, 0xeb, 0x4a, 0x91, 0x9c };
 
 static const unsigned int counter=1496;
+ */
 
 static const unsigned char prime2[] = { 0x00,
     0xa4, 0xc2, 0x83, 0x4f, 0x36, 0xd3, 0x4f, 0xae,
     0xa0, 0xb1, 0x47, 0x43, 0xa8, 0x15, 0xee, 0xad,
     0xa3, 0x98, 0xa3, 0x29, 0x45, 0xae, 0x5c, 0xd9,
     0x12, 0x99, 0x09, 0xdc, 0xef, 0x05, 0xb4, 0x98,
     0x05, 0xaa, 0x07, 0xaa, 0x83, 0x89, 0xd7, 0xba,
     0xd1, 0x25, 0x56, 0x58, 0xd1, 0x73, 0x3c, 0xd0,
@@ -302,16 +307,20 @@ static const unsigned char base2[] = { 0
     0xa2, 0x6f, 0xf8, 0xba, 0x99, 0x90, 0xc7, 0xe5,
     0xb1, 0x3c, 0x10, 0x34, 0x86, 0x6a, 0x6a, 0x1f,
     0x39, 0x63, 0x58, 0xe1, 0x5e, 0x97, 0x95, 0x45,
     0x40, 0x38, 0x45, 0x6f, 0x02, 0xb5, 0x86, 0x6e,
     0xae, 0x2f, 0x32, 0x7e, 0xa1, 0x3a, 0x34, 0x2c,
     0x1c, 0xd3, 0xff, 0x4e, 0x2c, 0x38, 0x1c, 0xaa,
     0x2e, 0x66, 0xbe, 0x32, 0x3e, 0x3c, 0x06, 0x5f };
 
+/*
+ * The constants h2, seed2, & counter2 aren't used in the code; they're provided
+ * here (commented-out) so that human readers can verify that our our PQG
+ * parameters were generated properly.
 static const unsigned char h2[] = { 
     0x30, 0x91, 0xa1, 0x2e, 0x40, 0xa5, 0x7d, 0xf7,
     0xdc, 0xed, 0xee, 0x05, 0xc2, 0x31, 0x91, 0x37,
     0xda, 0xc5, 0xe3, 0x47, 0xb5, 0x35, 0x4b, 0xfd,
     0x18, 0xb2, 0x7e, 0x67, 0x1e, 0x92, 0x22, 0xe7,
     0xf5, 0x00, 0x71, 0xc0, 0x86, 0x8d, 0x90, 0x31,
     0x36, 0x3e, 0xd0, 0x94, 0x5d, 0x2f, 0x9a, 0x68,
     0xd2, 0xf8, 0x3d, 0x5e, 0x84, 0x42, 0x35, 0xda,
@@ -371,16 +380,17 @@ static const unsigned char seed2[] = { 0
     0x2d, 0x91, 0xf9, 0x84, 0x45, 0x4d, 0xc7, 0xe1,
     0xee, 0xd4, 0xb8, 0x61, 0x3b, 0x13, 0xb7, 0xba,
     0x95, 0x39, 0xf6, 0x3d, 0x89, 0xbd, 0xa5, 0x80,
     0x93, 0xf7, 0xe5, 0x17, 0x05, 0xc5, 0x65, 0xb7,
     0xde, 0xc9, 0x9f, 0x04, 0x87, 0xcf, 0x4f, 0x86,
     0xc3, 0x29, 0x7d, 0xb7, 0x89, 0xbf, 0xe3, 0xde };
 
 static const unsigned int counter2=210;
+ */
 
 struct tuple_str {
     CK_RV         errNum;
     const char * errString;
 };
 
 typedef struct tuple_str tuple_str;
 
@@ -507,17 +517,17 @@ CK_RVtoStr(CK_RV errNum) {
             }
             lastNum = num;
         }
         initDone = 1;
     }
 
     /* Do binary search of table. */
     while (low + 1 < high) {
-        i = (low + high) / 2;
+        i = low + (high - low) / 2;
         num = errStrings[i].errNum;
         if (errNum == num)
             return errStrings[i].errString;
         if (errNum < num)
             high = i;
         else
             low = i;
     }
@@ -692,17 +702,17 @@ int main(int argc, char **argv)
     PRFileDesc *fd;
     PRStatus rv = PR_SUCCESS;
     const char  *input_file = NULL; /* read/create encrypted data from here */
     char  *output_file = NULL;	/* write new encrypted data here */
     int bytesRead;
     int bytesWritten;
     unsigned char file_buf[512];
     int count=0;
-    int keySize = 0;
+    unsigned int keySize = 0;
     int i;
     PRBool verify = PR_FALSE;
     static PRBool FIPSMODE = PR_FALSE;
     PRBool successful = PR_FALSE;
 
 #ifdef USES_LINKS
     int ret;
     struct stat stat_buf;
--- a/security/nss/cmd/signtool/certgen.c
+++ b/security/nss/cmd/signtool/certgen.c
@@ -68,16 +68,19 @@ GenerateCert(char *nickname, int keysize
 	    "must choose a different nickname.\n", nickname);
 	errorCount++;
 	exit(ERRX);
     }
 
     LL_L2UI(serial, PR_Now());
 
     subject = GetSubjectFromUser(serial);
+    if (!subject) {
+	FatalError("Unable to get subject from user");
+    }
 
     cert = GenerateSelfSignedObjectSigningCert(nickname, db, subject,
          		serial, keysize, token);
 
     if (cert) {
 	output_ca_cert(cert, db);
 	CERT_DestroyCertificate(cert);
     }
@@ -117,17 +120,19 @@ GetSubjectFromUser(unsigned long serial)
 #ifdef VERBOSE_PROMPTS
     PR_fprintf(PR_STDOUT, "\nCOMMON NAME\n"
         "Enter the full name you want to give your certificate. (Example: Test-Only\n"
         "Object Signing Certificate)\n"
         "-->");
 #else
     PR_fprintf(PR_STDOUT, "certificate common name: ");
 #endif
-    fgets(buf, STDIN_BUF_SIZE, stdin);
+    if (!fgets(buf, STDIN_BUF_SIZE, stdin)) {
+	return NULL;
+    }
     cp = chop(buf);
     if (*cp == '\0') {
 	sprintf(common_name_buf, "%s (%lu)", DEFAULT_COMMON_NAME,
 	     serial);
 	cp = common_name_buf;
     }
     common_name = PORT_ZAlloc(strlen(cp) + 6);
     if (!common_name) {
@@ -139,17 +144,19 @@ GetSubjectFromUser(unsigned long serial)
 #ifdef VERBOSE_PROMPTS
     PR_fprintf(PR_STDOUT, "\nORGANIZATION NAME\n"
         "Enter the name of your organization. For example, this could be the name\n"
         "of your company.\n"
         "-->");
 #else
     PR_fprintf(PR_STDOUT, "organization: ");
 #endif
-    fgets(buf, STDIN_BUF_SIZE, stdin);
+    if (!fgets(buf, STDIN_BUF_SIZE, stdin)) {
+	return NULL;
+    }
     cp = chop(buf);
     if (*cp != '\0') {
 	org = PORT_ZAlloc(strlen(cp) + 5);
 	if (!org) {
 	    out_of_memory();
 	}
 	sprintf(org, "O=%s, ", cp);
 	subjectlen += strlen(org);
@@ -158,17 +165,19 @@ GetSubjectFromUser(unsigned long serial)
 #ifdef VERBOSE_PROMPTS
     PR_fprintf(PR_STDOUT, "\nORGANIZATION UNIT\n"
         "Enter the name of your organization unit.  For example, this could be the\n"
         "name of your department.\n"
         "-->");
 #else
     PR_fprintf(PR_STDOUT, "organization unit: ");
 #endif
-    fgets(buf, STDIN_BUF_SIZE, stdin);
+    if (!fgets(buf, STDIN_BUF_SIZE, stdin)) {
+	return NULL;
+    }
     cp = chop(buf);
     if (*cp != '\0') {
 	orgunit = PORT_ZAlloc(strlen(cp) + 6);
 	if (!orgunit) {
 	    out_of_memory();
 	}
 	sprintf(orgunit, "OU=%s, ", cp);
 	subjectlen += strlen(orgunit);
@@ -176,17 +185,19 @@ GetSubjectFromUser(unsigned long serial)
 
 #ifdef VERBOSE_PROMPTS
     PR_fprintf(PR_STDOUT, "\nSTATE\n"
         "Enter the name of your state or province.\n"
         "-->");
 #else
     PR_fprintf(PR_STDOUT, "state or province: ");
 #endif
-    fgets(buf, STDIN_BUF_SIZE, stdin);
+    if (!fgets(buf, STDIN_BUF_SIZE, stdin)) {
+	return NULL;
+    }
     cp = chop(buf);
     if (*cp != '\0') {
 	state = PORT_ZAlloc(strlen(cp) + 6);
 	if (!state) {
 	    out_of_memory();
 	}
 	sprintf(state, "ST=%s, ", cp);
 	subjectlen += strlen(state);
@@ -194,17 +205,19 @@ GetSubjectFromUser(unsigned long serial)
 
 #ifdef VERBOSE_PROMPTS
     PR_fprintf(PR_STDOUT, "\nCOUNTRY\n"
         "Enter the 2-character abbreviation for the name of your country.\n"
         "-->");
 #else
     PR_fprintf(PR_STDOUT, "country (must be exactly 2 characters): ");
 #endif
-    fgets(buf, STDIN_BUF_SIZE, stdin);
+    if (!fgets(buf, STDIN_BUF_SIZE, stdin)) {
+	return NULL;
+    }
     cp = chop(cp);
     if (strlen(cp) != 2) {
 	*cp = '\0';	/* country code must be 2 chars */
     }
     if (*cp != '\0') {
 	country = PORT_ZAlloc(strlen(cp) + 5);
 	if (!country) {
 	    out_of_memory();
@@ -215,17 +228,19 @@ GetSubjectFromUser(unsigned long serial)
 
 #ifdef VERBOSE_PROMPTS
     PR_fprintf(PR_STDOUT, "\nUSERNAME\n"
         "Enter your system username or UID\n"
         "-->");
 #else
     PR_fprintf(PR_STDOUT, "username: ");
 #endif
-    fgets(buf, STDIN_BUF_SIZE, stdin);
+    if (!fgets(buf, STDIN_BUF_SIZE, stdin)) {
+	return NULL;
+    }
     cp = chop(buf);
     if (*cp != '\0') {
 	uid = PORT_ZAlloc(strlen(cp) + 7);
 	if (!uid) {
 	    out_of_memory();
 	}
 	sprintf(uid, "UID=%s, ", cp);
 	subjectlen += strlen(uid);
@@ -233,17 +248,19 @@ GetSubjectFromUser(unsigned long serial)
 
 #ifdef VERBOSE_PROMPTS
     PR_fprintf(PR_STDOUT, "\nEMAIL ADDRESS\n"
         "Enter your email address.\n"
         "-->");
 #else
     PR_fprintf(PR_STDOUT, "email address: ");
 #endif
-    fgets(buf, STDIN_BUF_SIZE, stdin);
+    if (!fgets(buf, STDIN_BUF_SIZE, stdin)) {
+	return NULL;
+    }
     cp = chop(buf);
     if (*cp != '\0') {
 	email = PORT_ZAlloc(strlen(cp) + 5);
 	if (!email) {
 	    out_of_memory();
 	}
 	sprintf(email, "E=%s,", cp);
 	subjectlen += strlen(email);
@@ -415,17 +432,16 @@ set_cert_type(CERTCertificate *cert, uns
 static SECItem *
 sign_cert(CERTCertificate *cert, SECKEYPrivateKey *privk)
 {
     SECStatus rv;
 
     SECItem der2;
     SECItem * result2;
 
-    void	*dummy;
     SECOidTag alg = SEC_OID_UNKNOWN;
 
     alg = SEC_GetSignatureAlgorithmOidTag(privk->keyType, SEC_OID_UNKNOWN);
     if (alg == SEC_OID_UNKNOWN) {
 	FatalError("Unknown key type");
     }
 
     rv = SECOID_SetAlgorithmID (cert->arena, &cert->signature, alg, 0);
@@ -435,17 +451,17 @@ sign_cert(CERTCertificate *cert, SECKEYP
 	     PROGRAM_NAME);
 	errorCount++;
 	exit (ERRX);
     }
 
     der2.len = 0;
     der2.data = NULL;
 
-    dummy = SEC_ASN1EncodeItem
+    (void)SEC_ASN1EncodeItem
         (cert->arena, &der2, cert, SEC_ASN1_GET(CERT_CertificateTemplate));
 
     if (rv != SECSuccess) {
 	PR_fprintf(errorFD, "%s: error encoding cert\n", PROGRAM_NAME);
 	errorCount++;
 	exit (ERRX);
     }
 
--- a/security/nss/cmd/signtool/util.c
+++ b/security/nss/cmd/signtool/util.c
@@ -11,19 +11,21 @@ static int	is_dir (char *filename);
 
 /***********************************************************
  * Nasty hackish function definitions
  */
 
 long	*mozilla_event_queue = 0;
 
 #ifndef XP_WIN
-char	*XP_GetString (int i)
+char *XP_GetString (int i)
 {
-    return SECU_Strerror (i);
+    /* nasty hackish cast to avoid changing the signature of
+     * JAR_init_callbacks() */
+    return (char *)SECU_Strerror (i);
 }
 #endif
 
 void	FE_SetPasswordEnabled()
 {
 }
 
 
--- a/security/nss/cmd/ssltap/ssltap.c
+++ b/security/nss/cmd/ssltap/ssltap.c
@@ -36,22 +36,22 @@
 #include "ocsp.h"
 #include "ocspti.h"     /* internals for pretty-printing routines *only