Bug 917571 - Add ChaCha20+Poly1305 cipher r=mt,wtc,ekr
☠☠ backed out by 74597951379c ☠ ☠
authorTim Taubert <ttaubert@mozilla.com>
Tue, 09 Feb 2016 11:22:45 +0100
changeset 11877 db4f87eed8ffedc9dbda440b54a817fc08054389
parent 11876 b32c1401102b4b4cc15fe399a2a4d045ee1f7419
child 11878 d60719dd22fdcc90af432d93866784a4b3e97386
push id982
push userttaubert@mozilla.com
push dateTue, 09 Feb 2016 12:45:21 +0000
reviewersmt, wtc, ekr
bugs917571
Bug 917571 - Add ChaCha20+Poly1305 cipher r=mt,wtc,ekr
circle.yml
cmd/bltest/blapitest.c
cmd/bltest/tests/chacha20_poly1305/aad0
cmd/bltest/tests/chacha20_poly1305/aad1
cmd/bltest/tests/chacha20_poly1305/ciphertext0
cmd/bltest/tests/chacha20_poly1305/ciphertext1
cmd/bltest/tests/chacha20_poly1305/iv0
cmd/bltest/tests/chacha20_poly1305/iv1
cmd/bltest/tests/chacha20_poly1305/key0
cmd/bltest/tests/chacha20_poly1305/key1
cmd/bltest/tests/chacha20_poly1305/numtests
cmd/bltest/tests/chacha20_poly1305/plaintext0
cmd/bltest/tests/chacha20_poly1305/plaintext1
coreconf/Werror.mk
external_tests/pk11_gtest/manifest.mn
external_tests/pk11_gtest/pk11_chacha20poly1305_unittest.cc
lib/freebl/Makefile
lib/freebl/blapi.h
lib/freebl/blapit.h
lib/freebl/chacha20.c
lib/freebl/chacha20.h
lib/freebl/chacha20_vec.c
lib/freebl/chacha20poly1305.c
lib/freebl/chacha20poly1305.h
lib/freebl/ldvector.c
lib/freebl/loader.c
lib/freebl/loader.h
lib/freebl/manifest.mn
lib/freebl/poly1305-donna-x64-sse2-incremental-source.c
lib/freebl/poly1305.c
lib/freebl/poly1305.h
lib/pk11wrap/pk11mech.c
lib/softoken/pkcs11.c
lib/softoken/pkcs11c.c
lib/softoken/pkcs11i.h
lib/util/pkcs11n.h
tests/cipher/cipher.txt
--- a/circle.yml
+++ b/circle.yml
@@ -1,18 +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
+        - cd tests; NSS_TESTS="ssl_gtests pk11_gtests der_gtests" NSS_CYCLES=standard ./all.sh
         - BUILD_OPT=1 make nss_build_all
-        - cd tests; BUILD_OPT=1 NSS_TESTS=ssl_gtests NSS_CYCLES=standard ./all.sh
+        - cd tests; BUILD_OPT=1 NSS_TESTS="ssl_gtests pk11_gtests der_gtests" NSS_CYCLES=standard ./all.sh
 
 machine:
     environment:
         { USE_64: 1,
           NSS_ENABLE_TLS_1_3: 1,
         }
     hosts:
 
--- a/cmd/bltest/blapitest.c
+++ b/cmd/bltest/blapitest.c
@@ -608,16 +608,27 @@ typedef struct
 
 typedef SECStatus (* bltestSymmCipherFn)(void *cx,
 					 unsigned char *output,
 					 unsigned int *outputLen,
 					 unsigned int maxOutputLen,
 					 const unsigned char *input,
 					 unsigned int inputLen);
 
+typedef SECStatus (* bltestAEADFn)(void *cx,
+                                   unsigned char *output,
+                                   unsigned int *outputLen,
+                                   unsigned int maxOutputLen,
+                                   const unsigned char *input,
+                                   unsigned int inputLen,
+                                   const unsigned char *nonce,
+                                   unsigned int nonceLen,
+                                   const unsigned char *ad,
+                                   unsigned int adLen);
+
 typedef SECStatus (* bltestPubKeyCipherFn)(void *key,
 					   SECItem *output,
 					   const SECItem *input);
 
 typedef SECStatus (* bltestHashCipherFn)(unsigned char *dest,
 					 const unsigned char *src,
 					 PRUint32 src_length);
 
@@ -641,16 +652,17 @@ typedef enum {
     bltestAES_CBC,        /* .                     */
     bltestAES_CTS,        /* .                     */
     bltestAES_CTR,        /* .                     */
     bltestAES_GCM,        /* .                     */
     bltestCAMELLIA_ECB,   /* .                     */
     bltestCAMELLIA_CBC,   /* .                     */
     bltestSEED_ECB,       /* SEED algorithm	   */
     bltestSEED_CBC,       /* SEED algorithm	   */
+    bltestCHACHA20,       /* ChaCha20 + Poly1305   */
     bltestRSA,            /* Public Key Ciphers    */
     bltestRSA_OAEP,       /* . (Public Key Enc.)   */
     bltestRSA_PSS,        /* . (Public Key Sig.)   */
 #ifndef NSS_DISABLE_ECC
     bltestECDSA,          /* . (Public Key Sig.)   */
 #endif
     bltestDSA,            /* . (Public Key Sig.)   */
     bltestMD2,		  /* Hash algorithms	   */
@@ -680,16 +692,17 @@ static char *mode_strings[] =
     "aes_cbc",
     "aes_cts",
     "aes_ctr",
     "aes_gcm",
     "camellia_ecb",
     "camellia_cbc",
     "seed_ecb",
     "seed_cbc",
+    "chacha20_poly1305",
     "rsa",
     "rsa_oaep",
     "rsa_pss",
 #ifndef NSS_DISABLE_ECC
     "ecdsa",
 #endif
     /*"pqg",*/
     "dsa",
@@ -800,16 +813,17 @@ struct  bltestCipherInfoStr {
     bltestIO output;
     /* Cipher-specific parameters */
     bltestParams params;
     /* Cipher mode */
     bltestCipherMode  mode;
     /* Cipher function (encrypt/decrypt/sign/verify/hash) */
     union {
 	bltestSymmCipherFn   symmkeyCipher;
+	bltestAEADFn         aeadCipher;
 	bltestPubKeyCipherFn pubkeyCipher;
 	bltestHashCipherFn   hashCipher;
     } cipher;
     /* performance testing */
     int   repetitionsToPerfom;
     int   seconds;
     int	  repetitions;
     int   cxreps;
@@ -822,34 +836,53 @@ is_symmkeyCipher(bltestCipherMode mode)
 {
     /* change as needed! */
     if (mode >= bltestDES_ECB && mode <= bltestSEED_CBC)
 	return PR_TRUE;
     return PR_FALSE;
 }
 
 PRBool
+is_aeadCipher(bltestCipherMode mode)
+{
+    /* change as needed! */
+    switch (mode) {
+	case bltestCHACHA20:
+	    return PR_TRUE;
+	default:
+	    return PR_FALSE;
+    }
+}
+
+PRBool
 is_authCipher(bltestCipherMode mode)
 {
     /* change as needed! */
-    if (mode == bltestAES_GCM)
-	return PR_TRUE;
-    return PR_FALSE;
+    switch (mode) {
+	case bltestAES_GCM:
+	case bltestCHACHA20:
+	    return PR_TRUE;
+	default:
+	    return PR_FALSE;
+    }
 }
 
 
 PRBool
 is_singleShotCipher(bltestCipherMode mode)
 {
     /* change as needed! */
-    if (mode == bltestAES_GCM)
-	return PR_TRUE;
-    if (mode == bltestAES_CTS)
-	return PR_TRUE;
-    return PR_FALSE;
+    switch (mode) {
+	case bltestAES_GCM:
+	case bltestAES_CTS:
+	case bltestCHACHA20:
+	    return PR_TRUE;
+	default:
+	    return PR_FALSE;
+    }
 }
 
 PRBool
 is_pubkeyCipher(bltestCipherMode mode)
 {
     /* change as needed! */
     if (mode >= bltestRSA && mode <= bltestDSA)
 	return PR_TRUE;
@@ -873,26 +906,34 @@ is_sigCipher(bltestCipherMode mode)
        return PR_TRUE;
     return PR_FALSE;
 }
 
 PRBool
 cipher_requires_IV(bltestCipherMode mode)
 {
     /* change as needed! */
-    if (mode == bltestDES_CBC || mode == bltestDES_EDE_CBC ||
-	mode == bltestRC2_CBC || 
+    switch (mode) {
+	case bltestDES_CBC:
+	case bltestDES_EDE_CBC:
+	case bltestRC2_CBC:
 #ifdef NSS_SOFTOKEN_DOES_RC5
-	mode == bltestRC5_CBC ||
+	case bltestRC5_CBC:
 #endif
-	mode == bltestAES_CBC || mode == bltestAES_CTS || 
-	mode == bltestAES_CTR || mode == bltestAES_GCM ||
-	mode == bltestCAMELLIA_CBC || mode == bltestSEED_CBC)
-	return PR_TRUE;
-    return PR_FALSE;
+	case bltestAES_CBC:
+	case bltestAES_CTS:
+	case bltestAES_CTR:
+	case bltestAES_GCM:
+	case bltestCAMELLIA_CBC:
+	case bltestSEED_CBC:
+	case bltestCHACHA20:
+	    return PR_TRUE;
+	default:
+	    return PR_FALSE;
+    }
 }
 
 SECStatus finishIO(bltestIO *output, PRFileDesc *file);
 
 SECStatus
 setupIO(PLArenaPool *arena, bltestIO *input, PRFileDesc *file,
 	char *str, int numBytes)
 {
@@ -1122,16 +1163,40 @@ aes_Decrypt(void *cx, unsigned char *out
             unsigned int maxOutputLen, const unsigned char *input,
             unsigned int inputLen)
 {
     return AES_Decrypt((AESContext *)cx, output, outputLen, maxOutputLen,
                        input, inputLen);
 }
 
 SECStatus
+chacha20_poly1305_Encrypt(void *cx, unsigned char *output,
+                         unsigned int *outputLen, unsigned int maxOutputLen,
+                         const unsigned char *input, unsigned int inputLen,
+                         const unsigned char *nonce, unsigned int nonceLen,
+                         const unsigned char *ad, unsigned int adLen)
+{
+    return ChaCha20Poly1305_Seal((ChaCha20Poly1305Context *)cx, output,
+                                 outputLen, maxOutputLen, input, inputLen,
+                                 nonce, nonceLen, ad, adLen);
+}
+
+SECStatus
+chacha20_poly1305_Decrypt(void *cx, unsigned char *output,
+                         unsigned int *outputLen, unsigned int maxOutputLen,
+                         const unsigned char *input, unsigned int inputLen,
+                         const unsigned char *nonce, unsigned int nonceLen,
+                         const unsigned char *ad, unsigned int adLen)
+{
+    return ChaCha20Poly1305_Open((ChaCha20Poly1305Context *)cx, output,
+                                 outputLen, maxOutputLen, input, inputLen,
+                                 nonce, nonceLen, ad, adLen);
+}
+
+SECStatus
 camellia_Encrypt(void *cx, unsigned char *output, unsigned int *outputLen,
 		 unsigned int maxOutputLen, const unsigned char *input,
 		 unsigned int inputLen)
 {
     return Camellia_Encrypt((CamelliaContext *)cx, output, outputLen,
 			    maxOutputLen,
 			    input, inputLen);
 }
@@ -1571,16 +1636,31 @@ bltest_seed_init(bltestCipherInfo *ciphe
 	cipherInfo->cipher.symmkeyCipher = seed_Encrypt;
     else
 	cipherInfo->cipher.symmkeyCipher = seed_Decrypt;
 	
 	return SECSuccess;
 }
 
 SECStatus
+bltest_chacha20_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
+{
+    const unsigned int tagLen = 16;
+    const bltestSymmKeyParams *sk = &cipherInfo->params.sk;
+    cipherInfo->cx = ChaCha20Poly1305_CreateContext(sk->key.buf.data,
+                                                    sk->key.buf.len, tagLen);
+
+    if (encrypt)
+	cipherInfo->cipher.aeadCipher = chacha20_poly1305_Encrypt;
+    else
+	cipherInfo->cipher.aeadCipher = chacha20_poly1305_Decrypt;
+    return SECSuccess;
+}
+
+SECStatus
 bltest_rsa_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     int i;
     RSAPrivateKey **dummyKey;
     RSAPrivateKey *privKey;
     RSAPublicKey *pubKey;
     PRIntervalTime time1, time2;
 
@@ -2221,16 +2301,21 @@ cipherInit(bltestCipherInfo *cipherInfo,
 	return bltest_camellia_init(cipherInfo, encrypt);
 	break;
     case bltestSEED_ECB:
     case bltestSEED_CBC:
 	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
 			  cipherInfo->input.pBuf.len);
 	return bltest_seed_init(cipherInfo, encrypt);
 	break;
+    case bltestCHACHA20:
+	outlen = cipherInfo->input.pBuf.len + (encrypt ? 16 : 0);
+	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, outlen);
+	return bltest_chacha20_init(cipherInfo, encrypt);
+	break;
     case bltestRSA:
     case bltestRSA_OAEP:
     case bltestRSA_PSS:
 	if (encrypt || cipherInfo->mode != bltestRSA_PSS) {
 		/* Don't allocate a buffer for PSS in verify mode, as no actual
 		 * output is produced. */
 		SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
 		                  RSA_MAX_MODULUS_BITS / 8);
@@ -2371,16 +2456,65 @@ cipherDoOp(bltestCipherInfo *cipherInfo)
                         cipherInfo->cx, dummyOut, &len, maxLen,
                         cipherInfo->input.pBuf.data,
                         cipherInfo->input.pBuf.len);
                 }
                 cipherInfo->repetitions += j;
             }
         }
         TIMEFINISH(cipherInfo->optime, 1.0);
+    } else if (is_aeadCipher(cipherInfo->mode)) {
+        const unsigned char *input = cipherInfo->input.pBuf.data;
+        unsigned int inputLen = cipherInfo->input.pBuf.len;
+        unsigned char *output = cipherInfo->output.pBuf.data;
+        unsigned int outputLen;
+        bltestSymmKeyParams *sk = &cipherInfo->params.sk;
+        bltestAuthSymmKeyParams *ask = &cipherInfo->params.ask;
+
+        TIMESTART();
+        rv = (*cipherInfo->cipher.aeadCipher)(
+                cipherInfo->cx,
+                output, &outputLen, maxLen,
+                input, inputLen,
+                sk->iv.buf.data, sk->iv.buf.len,
+                ask->aad.buf.data, ask->aad.buf.len);
+        CHECKERROR(rv, __LINE__);
+        cipherInfo->output.pBuf.len = outputLen;
+        TIMEFINISH(cipherInfo->optime, 1.0);
+
+        cipherInfo->repetitions = 0;
+        if (cipherInfo->repetitionsToPerfom != 0) {
+            TIMESTART();
+            for (i=0; i<cipherInfo->repetitionsToPerfom; i++,
+                     cipherInfo->repetitions++) {
+                rv = (*cipherInfo->cipher.aeadCipher)(
+                        cipherInfo->cx,
+                        output, &outputLen, maxLen,
+                        input, inputLen,
+                        sk->iv.buf.data, sk->iv.buf.len,
+                        ask->aad.buf.data, ask->aad.buf.len);
+                CHECKERROR(rv, __LINE__);
+            }
+        } else {
+            int opsBetweenChecks = 0;
+            TIMEMARK(cipherInfo->seconds);
+            while (! (TIMETOFINISH())) {
+                int j = 0;
+                for (;j < opsBetweenChecks;j++) {
+                    (*cipherInfo->cipher.aeadCipher)(
+                            cipherInfo->cx,
+                            output, &outputLen, maxLen,
+                            input, inputLen,
+                            sk->iv.buf.data, sk->iv.buf.len,
+                            ask->aad.buf.data, ask->aad.buf.len);
+                }
+                cipherInfo->repetitions += j;
+            }
+        }
+        TIMEFINISH(cipherInfo->optime, 1.0);
     } else if (is_pubkeyCipher(cipherInfo->mode)) {
         TIMESTART();
         rv = (*cipherInfo->cipher.pubkeyCipher)(cipherInfo->cx,
                                                 &cipherInfo->output.pBuf,
                                                 &cipherInfo->input.pBuf);
         TIMEFINISH(cipherInfo->optime, 1.0);
         CHECKERROR(rv, __LINE__);
         cipherInfo->repetitions = 0;
@@ -2472,16 +2606,20 @@ cipherFinish(bltestCipherInfo *cipherInf
     case bltestCAMELLIA_ECB:
     case bltestCAMELLIA_CBC:
 	Camellia_DestroyContext((CamelliaContext *)cipherInfo->cx, PR_TRUE);
 	break;
     case bltestSEED_ECB:
     case bltestSEED_CBC:
 	SEED_DestroyContext((SEEDContext *)cipherInfo->cx, PR_TRUE);
 	break;
+    case bltestCHACHA20:
+	ChaCha20Poly1305_DestroyContext((ChaCha20Poly1305Context *)
+                                        cipherInfo->cx, PR_TRUE);
+	break;
     case bltestRC2_ECB:
     case bltestRC2_CBC:
 	RC2_DestroyContext((RC2Context *)cipherInfo->cx, PR_TRUE);
 	break;
     case bltestRC4:
 	RC4_DestroyContext((RC4Context *)cipherInfo->cx, PR_TRUE);
 	break;
 #ifdef NSS_SOFTOKEN_DOES_RC5
@@ -2803,16 +2941,17 @@ get_params(PLArenaPool *arena, bltestPar
 
 #ifdef NSS_SOFTOKEN_DOES_RC5
     FILE *file;
     char *mark, *param, *val;
     int index = 0;
 #endif
     switch (mode) {
     case bltestAES_GCM:
+    case bltestCHACHA20:
 	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "aad", j);
 	load_file_data(arena, &params->ask.aad, filename, bltestBinary);
     case bltestDES_CBC:
     case bltestDES_EDE_CBC:
     case bltestRC2_CBC:
     case bltestAES_CBC:
     case bltestAES_CTS:
     case bltestAES_CTR:
@@ -3748,17 +3887,18 @@ print_usage:
             goto exit_point;
         }
         cipherInfo->arena = arena;
         params = &cipherInfo->params;
         
         /* Set up an encryption key. */
         keysize = 0;
         file = NULL;
-        if (is_symmkeyCipher(cipherInfo->mode)) {
+        if (is_symmkeyCipher(cipherInfo->mode) ||
+	    is_aeadCipher(cipherInfo->mode)) {
             char *keystr = NULL;  /* if key is on command line */
             if (bltest.options[opt_Key].activated) {
                 if (bltest.options[opt_CmdLine].activated) {
                     keystr = bltest.options[opt_Key].arg;
                 } else {
                     file = PR_Open(bltest.options[opt_Key].arg,
                                    PR_RDONLY, 00660);
                 }
new file mode 100644
--- /dev/null
+++ b/cmd/bltest/tests/chacha20_poly1305/aad0
@@ -0,0 +1,1 @@
+PQRSΐΑΒΓΔΕΖΗ
\ No newline at end of file
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..91287a1a2e38397b4bd5081fadab286c1fbd971a
GIT binary patch
literal 12
Pc%1ue+|kAW27VI(7}Nt4
new file mode 100644
--- /dev/null
+++ b/cmd/bltest/tests/chacha20_poly1305/ciphertext0
@@ -0,0 +1,1 @@
+0xqNNGSOYNt7hq+8U+9+wqSt7VEpbgj+qeK1pzbuYtY9vqRejKlnEoL6+2naknKLGnHeCp4GCykF1qW2fs07NpLdvX8td4uMmAOu4ygJG1j6syTk+tZ1lFWFgItIMde8P/Te8I5Lep3ldtJlhs7GS2EWGuELWU8J4mp+kC7L0GAGkQ==
new file mode 100644
--- /dev/null
+++ b/cmd/bltest/tests/chacha20_poly1305/ciphertext1
@@ -0,0 +1,1 @@
+ZKCGFXWGGvRg8GLHm+ZDvV6AXP00XPOJ8QhnCsdsjLJMbPwYdV1D7qCe6U44LSawvbe3PDIbAQDU8Dt/NViUzzMvgw5xC5fOmMioSr0LlIEUrRduAI0zvWD5grH/N8hVl5egbvTw72HBhjJOKzUGODYGkHtqfAKw+fYVe1PIZ+S5Fmx2e4BNRqWbUhbN56TpkEDFpAQzIl7igqGwoGxSPq9FNNf4P6EVWwBHcYy8VGoNBysEs1ZO6htCInP1SCcaC7IxYFP6dpkZVevWMVlDTs67TkZtrloQc6ZydicJehBJ5hfZHTYQlPpo8P93mHEwMFvqui7aBN+Ze3FNbG8sKaatXLQCKwJwm+6tnWeJDLsiOSM2/qGFHzg=
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..7e8a175046dde8a759e54a088eac41101ebd5782
GIT binary patch
literal 12
Tc${NrU|?`?baHlab#n&*3A6$v
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..7c8b98f50daf0ac0902bf4c98da4c5f6a91ca994
GIT binary patch
literal 12
Tc${NkU|?WmVrF4wW9I+>0E7S~
new file mode 100644
--- /dev/null
+++ b/cmd/bltest/tests/chacha20_poly1305/key0
@@ -0,0 +1,1 @@
+€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/cmd/bltest/tests/chacha20_poly1305/key1
@@ -0,0 +1,1 @@
+’@₯λUӊσ3ˆ†φ΅πG9Α@+€	Κ\Ό puΐ
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/cmd/bltest/tests/chacha20_poly1305/numtests
@@ -0,0 +1,1 @@
+2
new file mode 100644
--- /dev/null
+++ b/cmd/bltest/tests/chacha20_poly1305/plaintext0
@@ -0,0 +1,1 @@
+Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.
\ No newline at end of file
new file mode 100644
--- /dev/null
+++ b/cmd/bltest/tests/chacha20_poly1305/plaintext1
@@ -0,0 +1,1 @@
+Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as /β€œwork in progress./”
\ No newline at end of file
--- a/coreconf/Werror.mk
+++ b/coreconf/Werror.mk
@@ -2,28 +2,38 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
 # This sets WARNING_CFLAGS for gcc-like compilers.
 
 ifndef CC_IS_GCC
   CC_IS_GCC := $(shell $(CC) -x c -E -Wall -Werror /dev/null >/dev/null 2>&1 && echo 1)
+  # Export CC_IS_GCC to save a shell invocation when recursing.
   export CC_IS_GCC
 endif
 
 ifndef CC_NAME
   ifeq (1,$(CC_IS_GCC))
     CC_NAME := $(shell $(CC) -? 2>&1 >/dev/null | sed -e 's/:.*//;1q')
   else
     CC_NAME := $(notdir $(CC))
   endif
+  # Export CC_NAME to save a shell invocation when recursing.
   export CC_NAME
 endif
 
+ifndef GCC_VERSION
+  ifeq (1,$(CC_IS_GCC))
+    GCC_VERSION := $(subst ., ,$(shell $(CC) -dumpversion || echo x.x.x))
+    # Export GCC_VERSION to save a shell invocation when recursing.
+    export GCC_VERSION
+  endif
+endif
+
 ifndef WARNING_CFLAGS
   ifneq (1,$(CC_IS_GCC))
     WARNING_CFLAGS = $(NULL)
   else
     # This tests to see if enabling the warning is possible before
     # setting an option to disable it.
     disable_warning = $(shell $(CC) -x c -E -Werror -W$(1) /dev/null >/dev/null 2>&1 && echo -Wno-$(1))
 
@@ -50,28 +60,27 @@ ifndef WARNING_CFLAGS
         #   sprintf is often misused; please use snprintf [-Werror]
         # So, just suppress -Werror entirely on Android
         NSS_ENABLE_WERROR = 0
         $(warning OS_TARGET is Android, disabling -Werror)
       else
         ifeq ($(CC_NAME),clang)
           # Clang reports its version as an older gcc, but it's OK
           NSS_ENABLE_WERROR = 1
-        else
-          CC_VERSION := $(subst ., ,$(shell $(CC) -dumpversion))
-          ifneq (,$(filter 4.8 4.9,$(word 1,$(CC_VERSION)).$(word 2,$(CC_VERSION))))
+        else ifeq ($(CC_NAME),gcc)
+          ifneq (,$(filter 4.8 4.9,$(word 1,$(GCC_VERSION)).$(word 2,$(GCC_VERSION))))
             NSS_ENABLE_WERROR = 1
           endif
-          ifeq (,$(filter 0 1 2 3 4,$(word 1,$(CC_VERSION))))
+          ifeq (,$(filter 0 1 2 3 4,$(word 1,$(GCC_VERSION))))
             NSS_ENABLE_WERROR = 1
           endif
-          ifndef NSS_ENABLE_WERROR
-            $(warning Unable to find gcc 4.8 or greater, disabling -Werror)
-            NSS_ENABLE_WERROR = 0
-          endif
+        endif
+        ifndef NSS_ENABLE_WERROR
+          $(warning Unable to find gcc 4.8 or greater, disabling -Werror)
+          NSS_ENABLE_WERROR = 0
         endif
       endif
     endif #ndef NSS_ENABLE_WERROR
 
     ifeq ($(NSS_ENABLE_WERROR),1)
       WARNING_CFLAGS += -Werror
     else
       # Old versions of gcc (< 4.8) don't support #pragma diagnostic in functions.
--- a/external_tests/pk11_gtest/manifest.mn
+++ b/external_tests/pk11_gtest/manifest.mn
@@ -2,16 +2,17 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this
 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
 CORE_DEPTH = ../..
 DEPTH      = ../..
 MODULE = nss
 
 CPPSRCS = \
+      pk11_chacha20poly1305_unittest.cc \
       pk11_pbkdf2_unittest.cc \
       pk11_prf_unittest.cc \
       pk11_rsapss_unittest.cc \
       pk11_gtest.cc \
       $(NULL)
 
 INCLUDES += -I$(CORE_DEPTH)/external_tests/google_test/gtest/include \
             -I$(CORE_DEPTH)/external_tests/common
new file mode 100644
--- /dev/null
+++ b/external_tests/pk11_gtest/pk11_chacha20poly1305_unittest.cc
@@ -0,0 +1,277 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nss.h"
+#include "pk11pub.h"
+#include "sechash.h"
+#include <memory>
+
+#include "gtest/gtest.h"
+#include "scoped_ptrs.h"
+
+namespace nss_test {
+
+// ChaCha20/Poly1305 Test Vector 1, RFC 7539
+// <http://tools.ietf.org/html/rfc7539#section-2.8.2>
+const uint8_t kTestVector1Data[] = {
+  0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x47, 0x65,
+  0x6e, 0x74, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68,
+  0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39,
+  0x39, 0x3a, 0x20, 0x49, 0x66, 0x20, 0x49, 0x20, 0x63, 0x6f, 0x75, 0x6c, 0x64,
+  0x20, 0x6f, 0x66, 0x66, 0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f, 0x6e,
+  0x6c, 0x79, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x74, 0x69, 0x70, 0x20, 0x66, 0x6f,
+  0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x75, 0x74, 0x75, 0x72, 0x65, 0x2c,
+  0x20, 0x73, 0x75, 0x6e, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f,
+  0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69, 0x74, 0x2e
+};
+const uint8_t kTestVector1AAD[] = {
+  0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7
+};
+const uint8_t kTestVector1Key[] = {
+  0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c,
+  0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
+  0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f
+};
+const uint8_t kTestVector1IV[] = {
+  0x07, 0x00, 0x00, 0x00, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47
+};
+const uint8_t kTestVector1CT[] = {
+  0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb, 0x7b, 0x86, 0xaf, 0xbc, 0x53,
+  0xef, 0x7e, 0xc2, 0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x08, 0xfe, 0xa9, 0xe2,
+  0xb5, 0xa7, 0x36, 0xee, 0x62, 0xd6, 0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67,
+  0x12, 0x82, 0xfa, 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b, 0x1a, 0x71, 0xde, 0x0a,
+  0x9e, 0x06, 0x0b, 0x29, 0x05, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36, 0x92,
+  0xdd, 0xbd, 0x7f, 0x2d, 0x77, 0x8b, 0x8c, 0x98, 0x03, 0xae, 0xe3, 0x28, 0x09,
+  0x1b, 0x58, 0xfa, 0xb3, 0x24, 0xe4, 0xfa, 0xd6, 0x75, 0x94, 0x55, 0x85, 0x80,
+  0x8b, 0x48, 0x31, 0xd7, 0xbc, 0x3f, 0xf4, 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d,
+  0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b, 0x61, 0x16, 0x1a, 0xe1, 0x0b,
+  0x59, 0x4f, 0x09, 0xe2, 0x6a, 0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60, 0x06, 0x91
+};
+
+// ChaCha20/Poly1305 Test Vector 2, RFC 7539
+// <http://tools.ietf.org/html/rfc7539#appendix-A.5>
+const uint8_t kTestVector2Data[] = {
+  0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2d, 0x44, 0x72, 0x61, 0x66,
+  0x74, 0x73, 0x20, 0x61, 0x72, 0x65, 0x20, 0x64, 0x72, 0x61, 0x66, 0x74, 0x20,
+  0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x76, 0x61, 0x6c,
+  0x69, 0x64, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x61, 0x20, 0x6d, 0x61, 0x78, 0x69,
+  0x6d, 0x75, 0x6d, 0x20, 0x6f, 0x66, 0x20, 0x73, 0x69, 0x78, 0x20, 0x6d, 0x6f,
+  0x6e, 0x74, 0x68, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x6d, 0x61, 0x79, 0x20,
+  0x62, 0x65, 0x20, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x2c, 0x20, 0x72,
+  0x65, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x64, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x6f,
+  0x62, 0x73, 0x6f, 0x6c, 0x65, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x6f,
+  0x74, 0x68, 0x65, 0x72, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74,
+  0x73, 0x20, 0x61, 0x74, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x74, 0x69, 0x6d, 0x65,
+  0x2e, 0x20, 0x49, 0x74, 0x20, 0x69, 0x73, 0x20, 0x69, 0x6e, 0x61, 0x70, 0x70,
+  0x72, 0x6f, 0x70, 0x72, 0x69, 0x61, 0x74, 0x65, 0x20, 0x74, 0x6f, 0x20, 0x75,
+  0x73, 0x65, 0x20, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2d, 0x44,
+  0x72, 0x61, 0x66, 0x74, 0x73, 0x20, 0x61, 0x73, 0x20, 0x72, 0x65, 0x66, 0x65,
+  0x72, 0x65, 0x6e, 0x63, 0x65, 0x20, 0x6d, 0x61, 0x74, 0x65, 0x72, 0x69, 0x61,
+  0x6c, 0x20, 0x6f, 0x72, 0x20, 0x74, 0x6f, 0x20, 0x63, 0x69, 0x74, 0x65, 0x20,
+  0x74, 0x68, 0x65, 0x6d, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x20, 0x74, 0x68,
+  0x61, 0x6e, 0x20, 0x61, 0x73, 0x20, 0x2f, 0xe2, 0x80, 0x9c, 0x77, 0x6f, 0x72,
+  0x6b, 0x20, 0x69, 0x6e, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73,
+  0x2e, 0x2f, 0xe2, 0x80, 0x9d
+};
+const uint8_t kTestVector2AAD[] = {
+  0xf3, 0x33, 0x88, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4e, 0x91
+};
+const uint8_t kTestVector2Key[] = {
+  0x1c, 0x92, 0x40, 0xa5, 0xeb, 0x55, 0xd3, 0x8a, 0xf3, 0x33, 0x88, 0x86, 0x04,
+  0xf6, 0xb5, 0xf0, 0x47, 0x39, 0x17, 0xc1, 0x40, 0x2b, 0x80, 0x09, 0x9d, 0xca,
+  0x5c, 0xbc, 0x20, 0x70, 0x75, 0xc0
+};
+const uint8_t kTestVector2IV[] = {
+  0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
+};
+const uint8_t kTestVector2CT[] = {
+  0x64, 0xa0, 0x86, 0x15, 0x75, 0x86, 0x1a, 0xf4, 0x60, 0xf0, 0x62, 0xc7, 0x9b,
+  0xe6, 0x43, 0xbd, 0x5e, 0x80, 0x5c, 0xfd, 0x34, 0x5c, 0xf3, 0x89, 0xf1, 0x08,
+  0x67, 0x0a, 0xc7, 0x6c, 0x8c, 0xb2, 0x4c, 0x6c, 0xfc, 0x18, 0x75, 0x5d, 0x43,
+  0xee, 0xa0, 0x9e, 0xe9, 0x4e, 0x38, 0x2d, 0x26, 0xb0, 0xbd, 0xb7, 0xb7, 0x3c,
+  0x32, 0x1b, 0x01, 0x00, 0xd4, 0xf0, 0x3b, 0x7f, 0x35, 0x58, 0x94, 0xcf, 0x33,
+  0x2f, 0x83, 0x0e, 0x71, 0x0b, 0x97, 0xce, 0x98, 0xc8, 0xa8, 0x4a, 0xbd, 0x0b,
+  0x94, 0x81, 0x14, 0xad, 0x17, 0x6e, 0x00, 0x8d, 0x33, 0xbd, 0x60, 0xf9, 0x82,
+  0xb1, 0xff, 0x37, 0xc8, 0x55, 0x97, 0x97, 0xa0, 0x6e, 0xf4, 0xf0, 0xef, 0x61,
+  0xc1, 0x86, 0x32, 0x4e, 0x2b, 0x35, 0x06, 0x38, 0x36, 0x06, 0x90, 0x7b, 0x6a,
+  0x7c, 0x02, 0xb0, 0xf9, 0xf6, 0x15, 0x7b, 0x53, 0xc8, 0x67, 0xe4, 0xb9, 0x16,
+  0x6c, 0x76, 0x7b, 0x80, 0x4d, 0x46, 0xa5, 0x9b, 0x52, 0x16, 0xcd, 0xe7, 0xa4,
+  0xe9, 0x90, 0x40, 0xc5, 0xa4, 0x04, 0x33, 0x22, 0x5e, 0xe2, 0x82, 0xa1, 0xb0,
+  0xa0, 0x6c, 0x52, 0x3e, 0xaf, 0x45, 0x34, 0xd7, 0xf8, 0x3f, 0xa1, 0x15, 0x5b,
+  0x00, 0x47, 0x71, 0x8c, 0xbc, 0x54, 0x6a, 0x0d, 0x07, 0x2b, 0x04, 0xb3, 0x56,
+  0x4e, 0xea, 0x1b, 0x42, 0x22, 0x73, 0xf5, 0x48, 0x27, 0x1a, 0x0b, 0xb2, 0x31,
+  0x60, 0x53, 0xfa, 0x76, 0x99, 0x19, 0x55, 0xeb, 0xd6, 0x31, 0x59, 0x43, 0x4e,
+  0xce, 0xbb, 0x4e, 0x46, 0x6d, 0xae, 0x5a, 0x10, 0x73, 0xa6, 0x72, 0x76, 0x27,
+  0x09, 0x7a, 0x10, 0x49, 0xe6, 0x17, 0xd9, 0x1d, 0x36, 0x10, 0x94, 0xfa, 0x68,
+  0xf0, 0xff, 0x77, 0x98, 0x71, 0x30, 0x30, 0x5b, 0xea, 0xba, 0x2e, 0xda, 0x04,
+  0xdf, 0x99, 0x7b, 0x71, 0x4d, 0x6c, 0x6f, 0x2c, 0x29, 0xa6, 0xad, 0x5c, 0xb4,
+  0x02, 0x2b, 0x02, 0x70, 0x9b, 0xee, 0xad, 0x9d, 0x67, 0x89, 0x0c, 0xbb, 0x22,
+  0x39, 0x23, 0x36, 0xfe, 0xa1, 0x85, 0x1f, 0x38
+};
+
+class Pkcs11ChaCha20Poly1305Test : public ::testing::Test {
+ public:
+  void EncryptDecrypt(PK11SymKey* symKey,
+                      const uint8_t* data, size_t data_len,
+                      const uint8_t* aad, size_t aad_len,
+                      const uint8_t* iv, size_t iv_len,
+                      const uint8_t* ct = nullptr, size_t ct_len = 0)
+  {
+    // Prepare AEAD params.
+    CK_NSS_AEAD_PARAMS aead_params;
+    aead_params.pNonce = toUcharPtr(iv);
+    aead_params.ulNonceLen = iv_len;
+    aead_params.pAAD = toUcharPtr(aad);
+    aead_params.ulAADLen = aad_len;
+    aead_params.ulTagLen = 16;
+
+    SECItem params = { siBuffer, reinterpret_cast<unsigned char*>(&aead_params),
+                       sizeof(aead_params) };
+
+    // Encrypt.
+    unsigned int outputLen = 0;
+    std::vector<uint8_t> output(data_len + aead_params.ulTagLen);
+    SECStatus rv = PK11_Encrypt(symKey, mech, &params, &output[0], &outputLen,
+                                output.size(), data, data_len);
+    EXPECT_EQ(rv, SECSuccess);
+
+    // Check ciphertext and tag.
+    if (ct) {
+      EXPECT_TRUE(!memcmp(ct, &output[0], outputLen));
+    }
+
+    // Decrypt.
+    unsigned int decryptedLen = 0;
+    std::vector<uint8_t> decrypted(data_len);
+    rv = PK11_Decrypt(symKey, mech, &params, &decrypted[0], &decryptedLen,
+                      decrypted.size(), &output[0], outputLen);
+    EXPECT_EQ(rv, SECSuccess);
+
+    // Check the plaintext.
+    EXPECT_TRUE(!memcmp(data, &decrypted[0], decryptedLen));
+
+    // Decrypt with bogus data.
+    {
+      std::vector<uint8_t> bogusCiphertext(output);
+      bogusCiphertext[0] ^= 0xff;
+      rv = PK11_Decrypt(symKey, mech, &params, &decrypted[0], &decryptedLen,
+                        decrypted.size(), &bogusCiphertext[0], outputLen);
+      EXPECT_NE(rv, SECSuccess);
+    }
+
+    // Decrypt with bogus tag.
+    {
+      std::vector<uint8_t> bogusTag(output);
+      bogusTag[outputLen - 1] ^= 0xff;
+      rv = PK11_Decrypt(symKey, mech, &params, &decrypted[0], &decryptedLen,
+                        decrypted.size(), &bogusTag[0], outputLen);
+      EXPECT_NE(rv, SECSuccess);
+    }
+
+    // Decrypt with bogus IV.
+    {
+      SECItem bogusParams(params);
+      CK_NSS_AEAD_PARAMS bogusAeadParams(aead_params);
+      bogusParams.data = reinterpret_cast<unsigned char*>(&bogusAeadParams);
+
+      std::vector<uint8_t> bogusIV(iv, iv + iv_len);
+      bogusAeadParams.pNonce = toUcharPtr(&bogusIV[0]);
+      bogusIV[0] ^= 0xff;
+
+      rv = PK11_Decrypt(symKey, mech, &bogusParams, &decrypted[0],
+                        &decryptedLen, data_len, &output[0], outputLen);
+      EXPECT_NE(rv, SECSuccess);
+    }
+
+    // Decrypt with bogus additional data.
+    {
+      SECItem bogusParams(params);
+      CK_NSS_AEAD_PARAMS bogusAeadParams(aead_params);
+      bogusParams.data = reinterpret_cast<unsigned char*>(&bogusAeadParams);
+
+      std::vector<uint8_t> bogusAAD(aad, aad + aad_len);
+      bogusAeadParams.pAAD = toUcharPtr(&bogusAAD[0]);
+      bogusAAD[0] ^= 0xff;
+
+      rv = PK11_Decrypt(symKey, mech, &bogusParams, &decrypted[0],
+                        &decryptedLen, data_len, &output[0], outputLen);
+      EXPECT_NE(rv, SECSuccess);
+    }
+  }
+
+  void EncryptDecrypt(const uint8_t* key, size_t key_len,
+                      const uint8_t* data, size_t data_len,
+                      const uint8_t* aad, size_t aad_len,
+                      const uint8_t* iv, size_t iv_len,
+                      const uint8_t* ct, size_t ct_len)
+  {
+    ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
+    SECItem keyItem = { siBuffer, toUcharPtr(key),
+                        static_cast<unsigned int>(key_len) };
+
+    // Import key.
+    ScopedPK11SymKey symKey(PK11_ImportSymKey(slot.get(), mech,
+                                              PK11_OriginUnwrap, CKA_ENCRYPT,
+                                              &keyItem, nullptr));
+    EXPECT_TRUE(!!symKey);
+
+    // Check.
+    EncryptDecrypt(symKey.get(), data, data_len, aad, aad_len, iv, iv_len, ct,
+                   ct_len);
+  }
+
+ protected:
+  CK_MECHANISM_TYPE mech = CKM_NSS_CHACHA20_POLY1305;
+
+  unsigned char* toUcharPtr(const uint8_t* v) {
+    return const_cast<unsigned char*>(
+      static_cast<const unsigned char*>(v));
+  }
+};
+
+#define ENCRYPT_DECRYPT(v) \
+  EncryptDecrypt(v ## Key, sizeof(v ## Key), \
+                 v ## Data, sizeof(v ## Data), \
+                 v ## AAD, sizeof(v ## AAD), \
+                 v ## IV, sizeof(v ## IV), \
+                 v ## CT, sizeof(v ## CT));
+
+TEST_F(Pkcs11ChaCha20Poly1305Test, GenerateEncryptDecrypt) {
+  // Generate a random key.
+  ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
+  ScopedPK11SymKey symKey(PK11_KeyGen(slot.get(), mech, nullptr, 32, nullptr));
+  EXPECT_TRUE(!!symKey);
+
+  // Generate random data.
+  std::vector<uint8_t> data(512);
+  SECStatus rv = PK11_GenerateRandomOnSlot(slot.get(), &data[0], data.size());
+  EXPECT_EQ(rv, SECSuccess);
+
+  // Generate random AAD.
+  std::vector<uint8_t> aad(16);
+  rv = PK11_GenerateRandomOnSlot(slot.get(), &aad[0], aad.size());
+  EXPECT_EQ(rv, SECSuccess);
+
+  // Generate random IV.
+  std::vector<uint8_t> iv(12);
+  rv = PK11_GenerateRandomOnSlot(slot.get(), &iv[0], iv.size());
+  EXPECT_EQ(rv, SECSuccess);
+
+  // Check.
+  EncryptDecrypt(symKey.get(), &data[0], data.size(), &aad[0], aad.size(),
+                 &iv[0], iv.size());
+}
+
+TEST_F(Pkcs11ChaCha20Poly1305Test, CheckTestVector1) {
+  ENCRYPT_DECRYPT(kTestVector1);
+}
+
+TEST_F(Pkcs11ChaCha20Poly1305Test, CheckTestVector2) {
+  ENCRYPT_DECRYPT(kTestVector2);
+}
+
+}  // namespace nss_test
+
--- a/lib/freebl/Makefile
+++ b/lib/freebl/Makefile
@@ -477,16 +477,41 @@ ifndef NSS_DISABLE_ECC
     ifdef ECL_USE_FP
 	#enable floating point ECC code	
 	DEFINES  += -DECL_USE_FP
 	ECL_SRCS += ecp_fp160.c ecp_fp192.c ecp_fp224.c ecp_fp.c
 	ECL_HDRS += ecp_fp.h
     endif
 endif
 
+# poly1305-donna-x64-sse2-incremental-source.c requires __int128 support
+# in GCC 4.6.0.
+ifeq ($(CC_NAME),clang)
+    HAVE_INT128_SUPPORT = 1
+else ifeq (1,$(CC_IS_GCC))
+    ifneq (,$(filter 4.6 4.7 4.8 4.9,$(word 1,$(GCC_VERSION)).$(word 2,$(GCC_VERSION))))
+        HAVE_INT128_SUPPORT = 1
+    endif
+    ifeq (,$(filter 0 1 2 3 4,$(word 1,$(GCC_VERSION))))
+        HAVE_INT128_SUPPORT = 1
+    endif
+endif
+
+ifeq ($(CPU_ARCH),x86_64)
+    ifdef HAVE_INT128_SUPPORT
+        EXTRA_SRCS += poly1305-donna-x64-sse2-incremental-source.c
+    else
+        EXTRA_SRCS += poly1305.c
+    endif
+    EXTRA_SRCS += chacha20_vec.c
+else
+    EXTRA_SRCS += poly1305.c
+    EXTRA_SRCS += chacha20.c
+endif # x86_64
+
 #######################################################################
 # (5) Execute "global" rules. (OPTIONAL)                              #
 #######################################################################
 
 include $(CORE_DEPTH)/coreconf/rules.mk
 
 #######################################################################
 # (6) Execute "component" rules. (OPTIONAL)                           #
--- a/lib/freebl/blapi.h
+++ b/lib/freebl/blapi.h
@@ -981,16 +981,45 @@ Camellia_Encrypt(CamelliaContext *cx, un
 **	"input" the input data
 **	"inputLen" the amount of input data
 */
 extern SECStatus 
 Camellia_Decrypt(CamelliaContext *cx, unsigned char *output,
 		 unsigned int *outputLen, unsigned int maxOutputLen,
 		 const unsigned char *input, unsigned int inputLen);
 
+/******************************************/
+/*
+** ChaCha20+Poly1305 AEAD
+*/
+
+extern SECStatus ChaCha20Poly1305_InitContext(ChaCha20Poly1305Context *ctx,
+                                              const unsigned char *key,
+                                              unsigned int keyLen,
+                                              unsigned int tagLen);
+
+extern ChaCha20Poly1305Context *ChaCha20Poly1305_CreateContext(
+    const unsigned char *key, unsigned int keyLen, unsigned int tagLen);
+
+extern void ChaCha20Poly1305_DestroyContext(ChaCha20Poly1305Context *ctx,
+                                            PRBool freeit);
+
+extern SECStatus ChaCha20Poly1305_Seal(
+    const ChaCha20Poly1305Context *ctx, unsigned char *output,
+    unsigned int *outputLen, unsigned int maxOutputLen,
+    const unsigned char *input, unsigned int inputLen,
+    const unsigned char *nonce, unsigned int nonceLen,
+    const unsigned char *ad, unsigned int adLen);
+
+extern SECStatus ChaCha20Poly1305_Open(
+    const ChaCha20Poly1305Context *ctx, unsigned char *output,
+    unsigned int *outputLen, unsigned int maxOutputLen,
+    const unsigned char *input, unsigned int inputLen,
+    const unsigned char *nonce, unsigned int nonceLen,
+    const unsigned char *ad, unsigned int adLen);
 
 /******************************************/
 /*
 ** MD5 secure hash function
 */
 
 /*
 ** Hash a null terminated string "src" into "dest" using MD5
--- a/lib/freebl/blapit.h
+++ b/lib/freebl/blapit.h
@@ -217,16 +217,17 @@ struct AESContextStr        ;
 struct CamelliaContextStr   ;
 struct MD2ContextStr        ;
 struct MD5ContextStr        ;
 struct SHA1ContextStr       ;
 struct SHA256ContextStr     ;
 struct SHA512ContextStr     ;
 struct AESKeyWrapContextStr ;
 struct SEEDContextStr       ;	
+struct ChaCha20Poly1305ContextStr;
 
 typedef struct DESContextStr        DESContext;
 typedef struct RC2ContextStr        RC2Context;
 typedef struct RC4ContextStr        RC4Context;
 typedef struct RC5ContextStr        RC5Context;
 typedef struct AESContextStr        AESContext;
 typedef struct CamelliaContextStr   CamelliaContext;
 typedef struct MD2ContextStr        MD2Context;
@@ -235,16 +236,17 @@ typedef struct SHA1ContextStr       SHA1
 typedef struct SHA256ContextStr     SHA256Context;
 /* SHA224Context is really a SHA256ContextStr.  This is not a mistake. */
 typedef struct SHA256ContextStr     SHA224Context;
 typedef struct SHA512ContextStr     SHA512Context;
 /* SHA384Context is really a SHA512ContextStr.  This is not a mistake. */
 typedef struct SHA512ContextStr     SHA384Context;
 typedef struct AESKeyWrapContextStr AESKeyWrapContext;
 typedef struct SEEDContextStr	    SEEDContext;	
+typedef struct ChaCha20Poly1305ContextStr ChaCha20Poly1305Context;
 
 /***************************************************************************
 ** RSA Public and Private Key structures
 */
 
 /* member names from PKCS#1, section 7.1 */
 struct RSAPublicKeyStr {
     PLArenaPool * arena;
new file mode 100644
--- /dev/null
+++ b/lib/freebl/chacha20.c
@@ -0,0 +1,111 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Adopted from the public domain code in NaCl by djb. */
+
+#include <string.h>
+#include <stdio.h>
+
+#include "prtypes.h"
+#include "secport.h"
+#include "chacha20.h"
+
+#if defined(_MSC_VER)
+#pragma intrinsic(_lrotl)
+#define ROTL32(x, n) _lrotl(x, n)
+#else
+#define ROTL32(x, n) ((x << n) | (x >> ((8 * sizeof x) - n)))
+#endif
+
+#define ROTATE(v, c) ROTL32((v), (c))
+
+#define U32TO8_LITTLE(p, v)                                                    \
+    { (p)[0] = ((v)      ) & 0xff; (p)[1] = ((v) >>  8) & 0xff;                \
+      (p)[2] = ((v) >> 16) & 0xff; (p)[3] = ((v) >> 24) & 0xff; }
+#define U8TO32_LITTLE(p)                                                       \
+    (((PRUint32)((p)[0])      ) | ((PRUint32)((p)[1]) <<  8) |                 \
+     ((PRUint32)((p)[2]) << 16) | ((PRUint32)((p)[3]) << 24))
+
+#define QUARTERROUND(x, a, b, c, d)                                            \
+    x[a] = x[a] + x[b]; x[d] = ROTATE(x[d] ^ x[a], 16);                        \
+    x[c] = x[c] + x[d]; x[b] = ROTATE(x[b] ^ x[c], 12);                        \
+    x[a] = x[a] + x[b]; x[d] = ROTATE(x[d] ^ x[a],  8);                        \
+    x[c] = x[c] + x[d]; x[b] = ROTATE(x[b] ^ x[c],  7);
+
+static void
+ChaChaCore(unsigned char output[64], const PRUint32 input[16], int num_rounds)
+{
+    PRUint32 x[16];
+    int i;
+
+    PORT_Memcpy(x, input, sizeof(PRUint32) * 16);
+    for (i = num_rounds; i > 0; i -= 2) {
+        QUARTERROUND(x, 0, 4, 8, 12)
+        QUARTERROUND(x, 1, 5, 9, 13)
+        QUARTERROUND(x, 2, 6, 10, 14)
+        QUARTERROUND(x, 3, 7, 11, 15)
+        QUARTERROUND(x, 0, 5, 10, 15)
+        QUARTERROUND(x, 1, 6, 11, 12)
+        QUARTERROUND(x, 2, 7, 8, 13)
+        QUARTERROUND(x, 3, 4, 9, 14)
+    }
+
+    for (i = 0; i < 16; ++i) {
+        x[i] = x[i] + input[i];
+    }
+    for (i = 0; i < 16; ++i) {
+        U32TO8_LITTLE(output + 4 * i, x[i]);
+    }
+}
+
+static const unsigned char sigma[16] = "expand 32-byte k";
+
+void
+ChaCha20XOR(unsigned char *out, const unsigned char *in, unsigned int inLen,
+            const unsigned char key[32], const unsigned char nonce[12],
+            uint32_t counter)
+{
+    unsigned char block[64];
+    PRUint32 input[16];
+    unsigned int i;
+
+    input[4] = U8TO32_LITTLE(key + 0);
+    input[5] = U8TO32_LITTLE(key + 4);
+    input[6] = U8TO32_LITTLE(key + 8);
+    input[7] = U8TO32_LITTLE(key + 12);
+
+    input[8] = U8TO32_LITTLE(key + 16);
+    input[9] = U8TO32_LITTLE(key + 20);
+    input[10] = U8TO32_LITTLE(key + 24);
+    input[11] = U8TO32_LITTLE(key + 28);
+
+    input[0] = U8TO32_LITTLE(sigma + 0);
+    input[1] = U8TO32_LITTLE(sigma + 4);
+    input[2] = U8TO32_LITTLE(sigma + 8);
+    input[3] = U8TO32_LITTLE(sigma + 12);
+
+    input[12] = counter;
+    input[13] = U8TO32_LITTLE(nonce + 0);
+    input[14] = U8TO32_LITTLE(nonce + 4);
+    input[15] = U8TO32_LITTLE(nonce + 8);
+
+    while (inLen >= 64) {
+        ChaChaCore(block, input, 20);
+        for (i = 0; i < 64; i++) {
+            out[i] = in[i] ^ block[i];
+        }
+
+        input[12]++;
+        inLen -= 64;
+        in += 64;
+        out += 64;
+    }
+
+    if (inLen > 0) {
+        ChaChaCore(block, input, 20);
+        for (i = 0; i < inLen; i++) {
+            out[i] = in[i] ^ block[i];
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/lib/freebl/chacha20.h
@@ -0,0 +1,20 @@
+/*
+ * chacha20.h - header file for ChaCha20 implementation.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef FREEBL_CHACHA20_H_
+#define FREEBL_CHACHA20_H_
+
+#include <stdint.h>
+
+/* ChaCha20XOR encrypts |inLen| bytes from |in| with the given key and
+ * nonce and writes the result to |out|, which may be equal to |in|. The
+ * initial block counter is specified by |counter|. */
+extern void ChaCha20XOR(unsigned char *out, const unsigned char *in,
+                        unsigned int inLen, const unsigned char key[32],
+                        const unsigned char nonce[12], uint32_t counter);
+
+#endif /* FREEBL_CHACHA20_H_ */
new file mode 100644
--- /dev/null
+++ b/lib/freebl/chacha20_vec.c
@@ -0,0 +1,278 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* This implementation is by Ted Krovetz and was submitted to SUPERCOP and
+ * marked as public domain. It was been altered to allow for non-aligned inputs
+ * and to allow the block counter to be passed in specifically. */
+
+#include <string.h>
+
+#include "chacha20.h"
+
+#ifndef CHACHA_RNDS
+#define CHACHA_RNDS 20    /* 8 (high speed), 20 (conservative), 12 (middle) */
+#endif
+
+/* Architecture-neutral way to specify 16-byte vector of ints              */
+typedef unsigned vec __attribute__ ((vector_size (16)));
+
+/* This implementation is designed for Neon, SSE and AltiVec machines. The
+ * following specify how to do certain vector operations efficiently on
+ * each architecture, using intrinsics.
+ * This implementation supports parallel processing of multiple blocks,
+ * including potentially using general-purpose registers.
+ */
+#if __ARM_NEON__
+#include <arm_neon.h>
+#define GPR_TOO   1
+#define VBPI      2
+#define ONE       (vec)vsetq_lane_u32(1,vdupq_n_u32(0),0)
+#define LOAD(m)   (vec)(*((vec*)(m)))
+#define STORE(m,r) (*((vec*)(m))) = (r)
+#define ROTV1(x)  (vec)vextq_u32((uint32x4_t)x,(uint32x4_t)x,1)
+#define ROTV2(x)  (vec)vextq_u32((uint32x4_t)x,(uint32x4_t)x,2)
+#define ROTV3(x)  (vec)vextq_u32((uint32x4_t)x,(uint32x4_t)x,3)
+#define ROTW16(x) (vec)vrev32q_u16((uint16x8_t)x)
+#if __clang__
+#define ROTW7(x)  (x << ((vec){ 7, 7, 7, 7})) ^ (x >> ((vec){25,25,25,25}))
+#define ROTW8(x)  (x << ((vec){ 8, 8, 8, 8})) ^ (x >> ((vec){24,24,24,24}))
+#define ROTW12(x) (x << ((vec){12,12,12,12})) ^ (x >> ((vec){20,20,20,20}))
+#else
+#define ROTW7(x)  (vec)vsriq_n_u32(vshlq_n_u32((uint32x4_t)x,7),(uint32x4_t)x,25)
+#define ROTW8(x)  (vec)vsriq_n_u32(vshlq_n_u32((uint32x4_t)x,8),(uint32x4_t)x,24)
+#define ROTW12(x) (vec)vsriq_n_u32(vshlq_n_u32((uint32x4_t)x,12),(uint32x4_t)x,20)
+#endif
+#elif __SSE2__
+#include <emmintrin.h>
+#define GPR_TOO   0
+#if __clang__
+#define VBPI      4
+#else
+#define VBPI      3
+#endif
+#define ONE       (vec)_mm_set_epi32(0,0,0,1)
+#define LOAD(m)   (vec)_mm_loadu_si128((__m128i*)(m))
+#define STORE(m,r) _mm_storeu_si128((__m128i*)(m), (__m128i) (r))
+#define ROTV1(x)  (vec)_mm_shuffle_epi32((__m128i)x,_MM_SHUFFLE(0,3,2,1))
+#define ROTV2(x)  (vec)_mm_shuffle_epi32((__m128i)x,_MM_SHUFFLE(1,0,3,2))
+#define ROTV3(x)  (vec)_mm_shuffle_epi32((__m128i)x,_MM_SHUFFLE(2,1,0,3))
+#define ROTW7(x)  (vec)(_mm_slli_epi32((__m128i)x, 7) ^ _mm_srli_epi32((__m128i)x,25))
+#define ROTW12(x) (vec)(_mm_slli_epi32((__m128i)x,12) ^ _mm_srli_epi32((__m128i)x,20))
+#if __SSSE3__
+#include <tmmintrin.h>
+#define ROTW8(x)  (vec)_mm_shuffle_epi8((__m128i)x,_mm_set_epi8(14,13,12,15,10,9,8,11,6,5,4,7,2,1,0,3))
+#define ROTW16(x) (vec)_mm_shuffle_epi8((__m128i)x,_mm_set_epi8(13,12,15,14,9,8,11,10,5,4,7,6,1,0,3,2))
+#else
+#define ROTW8(x)  (vec)(_mm_slli_epi32((__m128i)x, 8) ^ _mm_srli_epi32((__m128i)x,24))
+#define ROTW16(x) (vec)(_mm_slli_epi32((__m128i)x,16) ^ _mm_srli_epi32((__m128i)x,16))
+#endif
+#else
+#error -- Implementation supports only machines with neon or SSE2
+#endif
+
+#ifndef REVV_BE
+#define REVV_BE(x)  (x)
+#endif
+
+#ifndef REVW_BE
+#define REVW_BE(x)  (x)
+#endif
+
+#define BPI      (VBPI + GPR_TOO)  /* Blocks computed per loop iteration   */
+
+#define DQROUND_VECTORS(a,b,c,d)                \
+    a += b; d ^= a; d = ROTW16(d);              \
+    c += d; b ^= c; b = ROTW12(b);              \
+    a += b; d ^= a; d = ROTW8(d);               \
+    c += d; b ^= c; b = ROTW7(b);               \
+    b = ROTV1(b); c = ROTV2(c);  d = ROTV3(d);  \
+    a += b; d ^= a; d = ROTW16(d);              \
+    c += d; b ^= c; b = ROTW12(b);              \
+    a += b; d ^= a; d = ROTW8(d);               \
+    c += d; b ^= c; b = ROTW7(b);               \
+    b = ROTV3(b); c = ROTV2(c); d = ROTV1(d);
+
+#define QROUND_WORDS(a,b,c,d) \
+  a = a+b; d ^= a; d = d<<16 | d>>16; \
+  c = c+d; b ^= c; b = b<<12 | b>>20; \
+  a = a+b; d ^= a; d = d<< 8 | d>>24; \
+  c = c+d; b ^= c; b = b<< 7 | b>>25;
+
+#define WRITE_XOR(in, op, d, v0, v1, v2, v3)                \
+    STORE(op + d + 0, LOAD(in + d + 0) ^ REVV_BE(v0));      \
+    STORE(op + d + 4, LOAD(in + d + 4) ^ REVV_BE(v1));      \
+    STORE(op + d + 8, LOAD(in + d + 8) ^ REVV_BE(v2));      \
+    STORE(op + d +12, LOAD(in + d +12) ^ REVV_BE(v3));
+
+void
+ChaCha20XOR(unsigned char *out, const unsigned char *in, unsigned int inlen,
+            const unsigned char key[32], const unsigned char nonce[12],
+            uint32_t counter)
+{
+    unsigned iters, i, *op=(unsigned *)out, *ip=(unsigned *)in, *kp;
+#if defined(__ARM_NEON__)
+    unsigned *np;
+#endif
+    vec s0, s1, s2, s3;
+#if !defined(__ARM_NEON__) && !defined(__SSE2__)
+    __attribute__ ((aligned (16))) unsigned key[8], nonce[4];
+#endif
+    __attribute__ ((aligned (16))) unsigned chacha_const[] =
+        {0x61707865,0x3320646E,0x79622D32,0x6B206574};
+#if defined(__ARM_NEON__) || defined(__SSE2__)
+    kp = (unsigned *)key;
+#else
+    ((vec *)key)[0] = REVV_BE(((vec *)key)[0]);
+    ((vec *)key)[1] = REVV_BE(((vec *)key)[1]);
+    ((unsigned *)nonce)[0] = REVW_BE(((unsigned *)nonce)[0]);
+    ((unsigned *)nonce)[1] = REVW_BE(((unsigned *)nonce)[1]);
+    ((unsigned *)nonce)[2] = REVW_BE(((unsigned *)nonce)[2]);
+    ((unsigned *)nonce)[3] = REVW_BE(((unsigned *)nonce)[3]);
+    kp = (unsigned *)key;
+    np = (unsigned *)nonce;
+#endif
+#if defined(__ARM_NEON__)
+    np = (unsigned*) nonce;
+#endif
+    s0 = LOAD(chacha_const);
+    s1 = LOAD(&((vec*)kp)[0]);
+    s2 = LOAD(&((vec*)kp)[1]);
+    s3 = (vec) {
+        counter,
+        ((uint32_t*)nonce)[0],
+        ((uint32_t*)nonce)[1],
+        ((uint32_t*)nonce)[2]
+    };
+
+    for (iters = 0; iters < inlen/(BPI*64); iters++) {
+#if GPR_TOO
+        register unsigned x0, x1, x2, x3, x4, x5, x6, x7, x8,
+                  x9, x10, x11, x12, x13, x14, x15;
+#endif
+#if VBPI > 2
+        vec v8,v9,v10,v11;
+#endif
+#if VBPI > 3
+        vec v12,v13,v14,v15;
+#endif
+
+        vec v0,v1,v2,v3,v4,v5,v6,v7;
+        v4 = v0 = s0; v5 = v1 = s1; v6 = v2 = s2; v3 = s3;
+        v7 = v3 + ONE;
+#if VBPI > 2
+        v8 = v4; v9 = v5; v10 = v6;
+        v11 =  v7 + ONE;
+#endif
+#if VBPI > 3
+        v12 = v8; v13 = v9; v14 = v10;
+        v15 = v11 + ONE;
+#endif
+#if GPR_TOO
+        x0 = chacha_const[0]; x1 = chacha_const[1];
+        x2 = chacha_const[2]; x3 = chacha_const[3];
+        x4 = kp[0]; x5 = kp[1]; x6  = kp[2]; x7  = kp[3];
+        x8 = kp[4]; x9 = kp[5]; x10 = kp[6]; x11 = kp[7];
+        x12 = counter+BPI*iters+(BPI-1); x13 = np[0];
+        x14 = np[1]; x15 = np[2];
+#endif
+        for (i = CHACHA_RNDS/2; i; i--) {
+            DQROUND_VECTORS(v0,v1,v2,v3)
+            DQROUND_VECTORS(v4,v5,v6,v7)
+#if VBPI > 2
+            DQROUND_VECTORS(v8,v9,v10,v11)
+#endif
+#if VBPI > 3
+            DQROUND_VECTORS(v12,v13,v14,v15)
+#endif
+#if GPR_TOO
+            QROUND_WORDS( x0, x4, x8,x12)
+            QROUND_WORDS( x1, x5, x9,x13)
+            QROUND_WORDS( x2, x6,x10,x14)
+            QROUND_WORDS( x3, x7,x11,x15)
+            QROUND_WORDS( x0, x5,x10,x15)
+            QROUND_WORDS( x1, x6,x11,x12)
+            QROUND_WORDS( x2, x7, x8,x13)
+            QROUND_WORDS( x3, x4, x9,x14)
+#endif
+        }
+
+        WRITE_XOR(ip, op, 0, v0+s0, v1+s1, v2+s2, v3+s3)
+        s3 += ONE;
+        WRITE_XOR(ip, op, 16, v4+s0, v5+s1, v6+s2, v7+s3)
+        s3 += ONE;
+#if VBPI > 2
+        WRITE_XOR(ip, op, 32, v8+s0, v9+s1, v10+s2, v11+s3)
+        s3 += ONE;
+#endif
+#if VBPI > 3
+        WRITE_XOR(ip, op, 48, v12+s0, v13+s1, v14+s2, v15+s3)
+        s3 += ONE;
+#endif
+        ip += VBPI*16;
+        op += VBPI*16;
+#if GPR_TOO
+        op[0]  = REVW_BE(REVW_BE(ip[0])  ^ (x0  + chacha_const[0]));
+        op[1]  = REVW_BE(REVW_BE(ip[1])  ^ (x1  + chacha_const[1]));
+        op[2]  = REVW_BE(REVW_BE(ip[2])  ^ (x2  + chacha_const[2]));
+        op[3]  = REVW_BE(REVW_BE(ip[3])  ^ (x3  + chacha_const[3]));
+        op[4]  = REVW_BE(REVW_BE(ip[4])  ^ (x4  + kp[0]));
+        op[5]  = REVW_BE(REVW_BE(ip[5])  ^ (x5  + kp[1]));
+        op[6]  = REVW_BE(REVW_BE(ip[6])  ^ (x6  + kp[2]));
+        op[7]  = REVW_BE(REVW_BE(ip[7])  ^ (x7  + kp[3]));
+        op[8]  = REVW_BE(REVW_BE(ip[8])  ^ (x8  + kp[4]));
+        op[9]  = REVW_BE(REVW_BE(ip[9])  ^ (x9  + kp[5]));
+        op[10] = REVW_BE(REVW_BE(ip[10]) ^ (x10 + kp[6]));
+        op[11] = REVW_BE(REVW_BE(ip[11]) ^ (x11 + kp[7]));
+        op[12] = REVW_BE(REVW_BE(ip[12]) ^ (x12 + counter+BPI*iters+(BPI-1)));
+        op[13] = REVW_BE(REVW_BE(ip[13]) ^ (x13 + np[0]));
+        op[14] = REVW_BE(REVW_BE(ip[14]) ^ (x14 + np[1]));
+        op[15] = REVW_BE(REVW_BE(ip[15]) ^ (x15 + np[2]));
+        s3 += ONE;
+        ip += 16;
+        op += 16;
+#endif
+    }
+
+    for (iters = inlen%(BPI*64)/64; iters != 0; iters--) {
+        vec v0 = s0, v1 = s1, v2 = s2, v3 = s3;
+        for (i = CHACHA_RNDS/2; i; i--) {
+            DQROUND_VECTORS(v0,v1,v2,v3);
+        }
+        WRITE_XOR(ip, op, 0, v0+s0, v1+s1, v2+s2, v3+s3)
+        s3 += ONE;
+        ip += 16;
+        op += 16;
+    }
+
+    inlen = inlen % 64;
+    if (inlen) {
+        __attribute__ ((aligned (16))) vec buf[4];
+        vec v0,v1,v2,v3;
+        v0 = s0; v1 = s1; v2 = s2; v3 = s3;
+        for (i = CHACHA_RNDS/2; i; i--) {
+            DQROUND_VECTORS(v0,v1,v2,v3);
+        }
+
+        if (inlen >= 16) {
+            STORE(op + 0, LOAD(ip + 0) ^ REVV_BE(v0 + s0));
+            if (inlen >= 32) {
+                STORE(op + 4, LOAD(ip + 4) ^ REVV_BE(v1 + s1));
+                if (inlen >= 48) {
+                    STORE(op + 8, LOAD(ip + 8) ^ REVV_BE(v2 + s2));
+                    buf[3] = REVV_BE(v3 + s3);
+                } else {
+                    buf[2] = REVV_BE(v2 + s2);
+                }
+            } else {
+                buf[1] = REVV_BE(v1 + s1);
+            }
+        } else {
+            buf[0] = REVV_BE(v0 + s0);
+        }
+
+        for (i=inlen & ~15; i<inlen; i++) {
+            ((char *)op)[i] = ((char *)ip)[i] ^ ((char *)buf)[i];
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/lib/freebl/chacha20poly1305.c
@@ -0,0 +1,174 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifdef FREEBL_NO_DEPEND
+#include "stubs.h"
+#endif
+
+#include <string.h>
+#include <stdio.h>
+
+#include "seccomon.h"
+#include "secerr.h"
+#include "blapit.h"
+#include "poly1305.h"
+#include "chacha20.h"
+#include "chacha20poly1305.h"
+
+/* Poly1305Do writes the Poly1305 authenticator of the given additional data
+ * and ciphertext to |out|. */
+static void
+Poly1305Do(unsigned char *out, const unsigned char *ad, unsigned int adLen,
+           const unsigned char *ciphertext, unsigned int ciphertextLen,
+           const unsigned char key[32])
+{
+    poly1305_state state;
+    unsigned int j;
+    unsigned char lengthBytes[8];
+    static const unsigned char zeros[15];
+    unsigned int i;
+
+    Poly1305Init(&state, key);
+    Poly1305Update(&state, ad, adLen);
+    if (adLen % 16 > 0) {
+        Poly1305Update(&state, zeros, 16 - adLen % 16);
+    }
+    Poly1305Update(&state, ciphertext, ciphertextLen);
+    if (ciphertextLen % 16 > 0) {
+        Poly1305Update(&state, zeros, 16 - ciphertextLen % 16);
+    }
+    j = adLen;
+    for (i = 0; i < sizeof(lengthBytes); i++) {
+        lengthBytes[i] = j;
+        j >>= 8;
+    }
+    Poly1305Update(&state, lengthBytes, sizeof(lengthBytes));
+    j = ciphertextLen;
+    for (i = 0; i < sizeof(lengthBytes); i++) {
+        lengthBytes[i] = j;
+        j >>= 8;
+    }
+    Poly1305Update(&state, lengthBytes, sizeof(lengthBytes));
+    Poly1305Finish(&state, out);
+}
+
+SECStatus
+ChaCha20Poly1305_InitContext(ChaCha20Poly1305Context *ctx,
+                             const unsigned char *key, unsigned int keyLen,
+                             unsigned int tagLen)
+{
+    if (keyLen != 32) {
+        PORT_SetError(SEC_ERROR_BAD_KEY);
+        return SECFailure;
+    }
+    if (tagLen == 0 || tagLen > 16) {
+        PORT_SetError(SEC_ERROR_INPUT_LEN);
+        return SECFailure;
+    }
+
+    PORT_Memcpy(ctx->key, key, sizeof(ctx->key));
+    ctx->tagLen = tagLen;
+
+    return SECSuccess;
+}
+
+ChaCha20Poly1305Context *
+ChaCha20Poly1305_CreateContext(const unsigned char *key, unsigned int keyLen,
+                               unsigned int tagLen)
+{
+    ChaCha20Poly1305Context *ctx;
+
+    ctx = PORT_New(ChaCha20Poly1305Context);
+    if (ctx == NULL) {
+        return NULL;
+    }
+
+    if (ChaCha20Poly1305_InitContext(ctx, key, keyLen, tagLen) != SECSuccess) {
+        PORT_Free(ctx);
+        ctx = NULL;
+    }
+
+    return ctx;
+}
+
+void
+ChaCha20Poly1305_DestroyContext(ChaCha20Poly1305Context *ctx, PRBool freeit)
+{
+    PORT_Memset(ctx, 0, sizeof(*ctx));
+    if (freeit) {
+        PORT_Free(ctx);
+    }
+}
+
+SECStatus
+ChaCha20Poly1305_Seal(const ChaCha20Poly1305Context *ctx, unsigned char *output,
+                      unsigned int *outputLen, unsigned int maxOutputLen,
+                      const unsigned char *input, unsigned int inputLen,
+                      const unsigned char *nonce, unsigned int nonceLen,
+                      const unsigned char *ad, unsigned int adLen)
+{
+    unsigned char block[64];
+    unsigned char tag[16];
+
+    if (nonceLen != 12) {
+        PORT_SetError(SEC_ERROR_INPUT_LEN);
+        return SECFailure;
+    }
+    *outputLen = inputLen + ctx->tagLen;
+    if (maxOutputLen < *outputLen) {
+        PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+        return SECFailure;
+    }
+
+    PORT_Memset(block, 0, sizeof(block));
+    // Generate a block of keystream. The first 32 bytes will be the poly1305
+    // key. The remainder of the block is discarded.
+    ChaCha20XOR(block, block, sizeof(block), ctx->key, nonce, 0);
+    ChaCha20XOR(output, input, inputLen, ctx->key, nonce, 1);
+
+    Poly1305Do(tag, ad, adLen, output, inputLen, block);
+    PORT_Memcpy(output + inputLen, tag, ctx->tagLen);
+
+    return SECSuccess;
+}
+
+SECStatus
+ChaCha20Poly1305_Open(const ChaCha20Poly1305Context *ctx, unsigned char *output,
+                      unsigned int *outputLen, unsigned int maxOutputLen,
+                      const unsigned char *input, unsigned int inputLen,
+                      const unsigned char *nonce, unsigned int nonceLen,
+                      const unsigned char *ad, unsigned int adLen)
+{
+    unsigned char block[64];
+    unsigned char tag[16];
+
+    if (nonceLen != 12) {
+        PORT_SetError(SEC_ERROR_INPUT_LEN);
+        return SECFailure;
+    }
+    if (inputLen < ctx->tagLen) {
+        PORT_SetError(SEC_ERROR_INPUT_LEN);
+        return SECFailure;
+    }
+    unsigned int ciphertextLen = inputLen - ctx->tagLen;
+    *outputLen = ciphertextLen;
+    if (maxOutputLen < *outputLen) {
+        PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+        return SECFailure;
+    }
+
+    PORT_Memset(block, 0, sizeof(block));
+    // Generate a block of keystream. The first 32 bytes will be the poly1305
+    // key. The remainder of the block is discarded.
+    ChaCha20XOR(block, block, sizeof(block), ctx->key, nonce, 0);
+    Poly1305Do(tag, ad, adLen, input, ciphertextLen, block);
+    if (NSS_SecureMemcmp(tag, &input[ciphertextLen], ctx->tagLen) != 0) {
+        PORT_SetError(SEC_ERROR_BAD_DATA);
+        return SECFailure;
+    }
+
+    ChaCha20XOR(output, input, ciphertextLen, ctx->key, nonce, 1);
+
+    return SECSuccess;
+}
new file mode 100644
--- /dev/null
+++ b/lib/freebl/chacha20poly1305.h
@@ -0,0 +1,15 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef _CHACHA20_POLY1305_H_
+#define _CHACHA20_POLY1305_H_ 1
+
+/* ChaCha20Poly1305ContextStr saves the key and tag length for a
+ * ChaCha20+Poly1305 AEAD operation. */
+struct ChaCha20Poly1305ContextStr {
+    unsigned char key[32];
+    unsigned char tagLen;
+};
+
+#endif /* _CHACHA20_POLY1305_H_ */
--- a/lib/freebl/ldvector.c
+++ b/lib/freebl/ldvector.c
@@ -281,19 +281,27 @@ static const struct FREEBLVectorStr vect
     RSA_Sign,
     RSA_CheckSign,
     RSA_CheckSignRecover,
 
     /* End of Version 3.016 */
 
     EC_FillParams,
     EC_DecodeParams,
-    EC_CopyParams
+    EC_CopyParams,
 
     /* End of Version 3.017 */
+
+    ChaCha20Poly1305_InitContext,
+    ChaCha20Poly1305_CreateContext,
+    ChaCha20Poly1305_DestroyContext,
+    ChaCha20Poly1305_Seal,
+    ChaCha20Poly1305_Open
+
+    /* End of Version 3.018 */
 };
 
 const FREEBLVector *
 FREEBL_GetVector(void)
 {
 #define NSS_VERSION_VARIABLE __nss_freebl_version
 #include "verref.h"
 
--- a/lib/freebl/loader.c
+++ b/lib/freebl/loader.c
@@ -2123,8 +2123,64 @@ SECStatus EC_DecodeParams(const SECItem 
 SECStatus EC_CopyParams(PLArenaPool *arena, ECParams *dstParams,
                         const ECParams *srcParams)
 {
   if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
       return SECFailure;
   return (vector->p_EC_CopyParams)(arena, dstParams,  srcParams);
 }
 
+SECStatus
+ChaCha20Poly1305_InitContext(ChaCha20Poly1305Context *ctx,
+                             const unsigned char *key, unsigned int keyLen,
+                             unsigned int tagLen)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return SECFailure;
+  return (vector->p_ChaCha20Poly1305_InitContext)(ctx, key, keyLen, tagLen);
+}
+
+ChaCha20Poly1305Context *
+ChaCha20Poly1305_CreateContext(const unsigned char *key, unsigned int keyLen,
+                               unsigned int tagLen)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return NULL;
+  return (vector->p_ChaCha20Poly1305_CreateContext)(key, keyLen, tagLen);
+}
+
+void
+ChaCha20Poly1305_DestroyContext(ChaCha20Poly1305Context *ctx, PRBool freeit)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return;
+  (vector->p_ChaCha20Poly1305_DestroyContext)(ctx, freeit);
+}
+
+SECStatus
+ChaCha20Poly1305_Seal(const ChaCha20Poly1305Context *ctx,
+                      unsigned char *output, unsigned int *outputLen,
+                      unsigned int maxOutputLen,
+                      const unsigned char *input, unsigned int inputLen,
+                      const unsigned char *nonce, unsigned int nonceLen,
+                      const unsigned char *ad, unsigned int adLen)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return SECFailure;
+  return (vector->p_ChaCha20Poly1305_Seal)(
+      ctx, output, outputLen, maxOutputLen, input, inputLen,
+      nonce, nonceLen, ad, adLen);
+}
+
+SECStatus
+ChaCha20Poly1305_Open(const ChaCha20Poly1305Context *ctx,
+                      unsigned char *output, unsigned int *outputLen,
+                      unsigned int maxOutputLen,
+                      const unsigned char *input, unsigned int inputLen,
+                      const unsigned char *nonce, unsigned int nonceLen,
+                      const unsigned char *ad, unsigned int adLen)
+{
+  if (!vector && PR_SUCCESS != freebl_RunLoaderOnce())
+      return SECFailure;
+  return (vector->p_ChaCha20Poly1305_Open)(
+      ctx, output, outputLen, maxOutputLen, input, inputLen,
+      nonce, nonceLen, ad, adLen);
+}
--- a/lib/freebl/loader.h
+++ b/lib/freebl/loader.h
@@ -5,17 +5,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef _LOADER_H_
 #define _LOADER_H_ 1
 
 #include "blapi.h"
 
-#define FREEBL_VERSION 0x0311
+#define FREEBL_VERSION 0x0312
 
 struct FREEBLVectorStr {
 
   unsigned short length;  /* of this struct in bytes */
   unsigned short version; /* of this struct. */
 
   RSAPrivateKey * (* p_RSA_NewKey)(int         keySizeInBits,
 				 SECItem *   publicExponent);
@@ -702,16 +702,43 @@ struct FREEBLVectorStr {
                                const SECItem *encodedParams, ECParams *params);
  SECStatus (* p_EC_DecodeParams)(const SECItem *encodedParams,
                                ECParams **ecparams);
  SECStatus (* p_EC_CopyParams)(PLArenaPool *arena, ECParams *dstParams,
                                const ECParams *srcParams);
 
   /* Version 3.017 came to here */
 
+ SECStatus (* p_ChaCha20Poly1305_InitContext)(ChaCha20Poly1305Context *ctx,
+                                              const unsigned char *key,
+                                              unsigned int keyLen,
+                                              unsigned int tagLen);
+
+ ChaCha20Poly1305Context *(* p_ChaCha20Poly1305_CreateContext)(
+     const unsigned char *key, unsigned int keyLen, unsigned int tagLen);
+
+ void (* p_ChaCha20Poly1305_DestroyContext)(ChaCha20Poly1305Context *ctx,
+                                            PRBool freeit);
+
+ SECStatus (* p_ChaCha20Poly1305_Seal)(
+     const ChaCha20Poly1305Context *ctx, unsigned char *output,
+     unsigned int *outputLen, unsigned int maxOutputLen,
+     const unsigned char *input, unsigned int inputLen,
+     const unsigned char *nonce, unsigned int nonceLen,
+     const unsigned char *ad, unsigned int adLen);
+
+ SECStatus (* p_ChaCha20Poly1305_Open)(
+     const ChaCha20Poly1305Context *ctx, unsigned char *output,
+     unsigned int *outputLen, unsigned int maxOutputLen,
+     const unsigned char *input, unsigned int inputLen,
+     const unsigned char *nonce, unsigned int nonceLen,
+     const unsigned char *ad, unsigned int adLen);
+
+  /* Version 3.018 came to here */
+
   /* Add new function pointers at the end of this struct and bump
    * FREEBL_VERSION at the beginning of this file. */
  };
 
 typedef struct FREEBLVectorStr FREEBLVector;
 
 SEC_BEGIN_PROTOS
 
--- a/lib/freebl/manifest.mn
+++ b/lib/freebl/manifest.mn
@@ -51,16 +51,17 @@ EXPORTS = \
 	shsign.h \
 	ecl-exp.h \
 	$(LOWHASH_EXPORTS) \
 	$(NULL)
 
 PRIVATE_EXPORTS = \
 	alghmac.h \
 	blapi.h \
+	chacha20poly1305.h \
 	hmacct.h \
 	secmpi.h \
 	secrng.h \
 	ec.h \
 	ecl.h \
 	ecl-curve.h \
 	$(NULL)
 
@@ -96,16 +97,17 @@ CSRCS = \
 	alghmac.c \
 	rawhash.c \
 	alg2268.c \
 	arcfour.c \
 	arcfive.c \
 	desblapi.c \
 	des.c \
 	drbg.c \
+	chacha20poly1305.c \
 	cts.c \
 	ctr.c \
 	gcm.c \
 	hmacct.c \
 	rijndael.c \
 	aeskeywrap.c \
 	camellia.c \
 	dh.c \
new file mode 100644
--- /dev/null
+++ b/lib/freebl/poly1305-donna-x64-sse2-incremental-source.c
@@ -0,0 +1,623 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* This implementation of poly1305 is by Andrew Moon
+ * (https://github.com/floodyberry/poly1305-donna) and released as public
+ * domain. It implements SIMD vectorization based on the algorithm described in
+ * http://cr.yp.to/papers.html#neoncrypto. Unrolled to 2 powers, i.e. 64 byte
+ * block size. */
+
+#include <emmintrin.h>
+#include <stdint.h>
+
+#include "poly1305.h"
+
+#define ALIGN(x) __attribute__((aligned(x)))
+#define INLINE inline
+#define U8TO64_LE(m) (*(uint64_t*)(m))
+#define U8TO32_LE(m) (*(uint32_t*)(m))
+#define U64TO8_LE(m,v) (*(uint64_t*)(m)) = v
+
+typedef __m128i xmmi;
+typedef unsigned __int128 uint128_t;
+
+static const uint32_t ALIGN(16) poly1305_x64_sse2_message_mask[4] = {(1 << 26) - 1, 0, (1 << 26) - 1, 0};
+static const uint32_t ALIGN(16) poly1305_x64_sse2_5[4] = {5, 0, 5, 0};
+static const uint32_t ALIGN(16) poly1305_x64_sse2_1shl128[4] = {(1 << 24), 0, (1 << 24), 0};
+
+static uint128_t INLINE
+add128(uint128_t a, uint128_t b) {
+	return a + b;
+}
+
+static uint128_t INLINE
+add128_64(uint128_t a, uint64_t b) {
+	return a + b;
+}
+
+static uint128_t INLINE
+mul64x64_128(uint64_t a, uint64_t b) {
+	return (uint128_t)a * b;
+}
+
+static uint64_t INLINE
+lo128(uint128_t a) {
+	return (uint64_t)a;
+}
+
+static uint64_t INLINE
+shr128(uint128_t v, const int shift) {
+	return (uint64_t)(v >> shift);
+}
+
+static uint64_t INLINE
+shr128_pair(uint64_t hi, uint64_t lo, const int shift) {
+	return (uint64_t)((((uint128_t)hi << 64) | lo) >> shift);
+}
+
+typedef struct poly1305_power_t {
+	union {
+		xmmi v;
+		uint64_t u[2];
+		uint32_t d[4];
+	} R20,R21,R22,R23,R24,S21,S22,S23,S24;
+} poly1305_power;
+
+typedef struct poly1305_state_internal_t {
+	poly1305_power P[2];     /* 288 bytes, top 32 bit halves unused = 144 bytes of free storage */
+	union {
+		xmmi H[5];           /*  80 bytes  */
+		uint64_t HH[10];
+	};
+	/* uint64_t r0,r1,r2;       [24 bytes] */
+	/* uint64_t pad0,pad1;      [16 bytes] */
+	uint64_t started;        /*   8 bytes  */
+	uint64_t leftover;       /*   8 bytes  */
+	uint8_t buffer[64];      /*  64 bytes  */
+} poly1305_state_internal;   /* 448 bytes total + 63 bytes for alignment = 511 bytes raw */
+
+static poly1305_state_internal INLINE
+*poly1305_aligned_state(poly1305_state *state) {
+	return (poly1305_state_internal *)(((uint64_t)state + 63) & ~63);
+}
+
+/* copy 0-63 bytes */
+static void INLINE
+poly1305_block_copy(uint8_t *dst, const uint8_t *src, size_t bytes) {
+	size_t offset = src - dst;
+	if (bytes & 32) {
+		_mm_storeu_si128((xmmi *)(dst + 0), _mm_loadu_si128((xmmi *)(dst + offset + 0)));
+		_mm_storeu_si128((xmmi *)(dst + 16), _mm_loadu_si128((xmmi *)(dst + offset + 16)));
+		dst += 32;
+	}
+	if (bytes & 16) { _mm_storeu_si128((xmmi *)dst, _mm_loadu_si128((xmmi *)(dst + offset))); dst += 16; }
+	if (bytes &  8) { *(uint64_t *)dst = *(uint64_t *)(dst + offset); dst += 8; }
+	if (bytes &  4) { *(uint32_t *)dst = *(uint32_t *)(dst + offset); dst += 4; }
+	if (bytes &  2) { *(uint16_t *)dst = *(uint16_t *)(dst + offset); dst += 2; }
+	if (bytes &  1) { *( uint8_t *)dst = *( uint8_t *)(dst + offset);           }
+}
+
+/* zero 0-15 bytes */
+static void INLINE
+poly1305_block_zero(uint8_t *dst, size_t bytes) {
+	if (bytes &  8) { *(uint64_t *)dst = 0; dst += 8; }
+	if (bytes &  4) { *(uint32_t *)dst = 0; dst += 4; }
+	if (bytes &  2) { *(uint16_t *)dst = 0; dst += 2; }
+	if (bytes &  1) { *( uint8_t *)dst = 0; }
+}
+
+static size_t INLINE
+poly1305_min(size_t a, size_t b) {
+	return (a < b) ? a : b;
+}
+
+void
+Poly1305Init(poly1305_state *state, const unsigned char key[32]) {
+	poly1305_state_internal *st = poly1305_aligned_state(state);
+	poly1305_power *p;
+	uint64_t r0,r1,r2;
+	uint64_t t0,t1;
+
+	/* clamp key */
+	t0 = U8TO64_LE(key + 0);
+	t1 = U8TO64_LE(key + 8);
+	r0 = t0 & 0xffc0fffffff; t0 >>= 44; t0 |= t1 << 20;
+	r1 = t0 & 0xfffffc0ffff; t1 >>= 24;
+	r2 = t1 & 0x00ffffffc0f;
+
+	/* store r in un-used space of st->P[1] */
+	p = &st->P[1];
+	p->R20.d[1] = (uint32_t)(r0      );
+	p->R20.d[3] = (uint32_t)(r0 >> 32);
+	p->R21.d[1] = (uint32_t)(r1      );
+	p->R21.d[3] = (uint32_t)(r1 >> 32);
+	p->R22.d[1] = (uint32_t)(r2      );
+	p->R22.d[3] = (uint32_t)(r2 >> 32);
+
+	/* store pad */
+	p->R23.d[1] = U8TO32_LE(key + 16);
+	p->R23.d[3] = U8TO32_LE(key + 20);
+	p->R24.d[1] = U8TO32_LE(key + 24);
+	p->R24.d[3] = U8TO32_LE(key + 28);
+
+	/* H = 0 */
+	st->H[0] = _mm_setzero_si128();
+	st->H[1] = _mm_setzero_si128();
+	st->H[2] = _mm_setzero_si128();
+	st->H[3] = _mm_setzero_si128();
+	st->H[4] = _mm_setzero_si128();
+
+	st->started = 0;
+	st->leftover = 0;
+}
+
+static void
+poly1305_first_block(poly1305_state_internal *st, const uint8_t *m) {
+	const xmmi MMASK = _mm_load_si128((xmmi *)poly1305_x64_sse2_message_mask);
+	const xmmi FIVE = _mm_load_si128((xmmi*)poly1305_x64_sse2_5);
+	const xmmi HIBIT = _mm_load_si128((xmmi*)poly1305_x64_sse2_1shl128);
+	xmmi T5,T6;
+	poly1305_power *p;
+	uint128_t d[3];
+	uint64_t r0,r1,r2;
+	uint64_t r20,r21,r22,s22;
+	uint64_t pad0,pad1;
+	uint64_t c;
+	uint64_t i;
+
+	/* pull out stored info */
+	p = &st->P[1];
+
+	r0   = ((uint64_t)p->R20.d[3] << 32) | (uint64_t)p->R20.d[1];
+	r1   = ((uint64_t)p->R21.d[3] << 32) | (uint64_t)p->R21.d[1];
+	r2   = ((uint64_t)p->R22.d[3] << 32) | (uint64_t)p->R22.d[1];
+	pad0 = ((uint64_t)p->R23.d[3] << 32) | (uint64_t)p->R23.d[1];
+	pad1 = ((uint64_t)p->R24.d[3] << 32) | (uint64_t)p->R24.d[1];
+
+	/* compute powers r^2,r^4 */
+	r20 = r0;
+	r21 = r1;
+	r22 = r2;
+	for (i = 0; i < 2; i++) {
+		s22 = r22 * (5 << 2);
+
+		d[0] = add128(mul64x64_128(r20, r20), mul64x64_128(r21 * 2, s22));
+		d[1] = add128(mul64x64_128(r22, s22), mul64x64_128(r20 * 2, r21));
+		d[2] = add128(mul64x64_128(r21, r21), mul64x64_128(r22 * 2, r20));
+
+		                           r20 = lo128(d[0]) & 0xfffffffffff; c = shr128(d[0], 44);
+		d[1] = add128_64(d[1], c); r21 = lo128(d[1]) & 0xfffffffffff; c = shr128(d[1], 44);
+		d[2] = add128_64(d[2], c); r22 = lo128(d[2]) & 0x3ffffffffff; c = shr128(d[2], 42);
+		r20 += c * 5; c = (r20 >> 44); r20 = r20 & 0xfffffffffff;
+		r21 += c;
+
+		p->R20.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)( r20                     ) & 0x3ffffff), _MM_SHUFFLE(1,0,1,0));
+		p->R21.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)((r20 >> 26) | (r21 << 18)) & 0x3ffffff), _MM_SHUFFLE(1,0,1,0));
+		p->R22.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)((r21 >> 8)               ) & 0x3ffffff), _MM_SHUFFLE(1,0,1,0));
+		p->R23.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)((r21 >> 34) | (r22 << 10)) & 0x3ffffff), _MM_SHUFFLE(1,0,1,0));
+		p->R24.v = _mm_shuffle_epi32(_mm_cvtsi32_si128((uint32_t)((r22 >> 16)              )            ), _MM_SHUFFLE(1,0,1,0));
+		p->S21.v = _mm_mul_epu32(p->R21.v, FIVE);
+		p->S22.v = _mm_mul_epu32(p->R22.v, FIVE);
+		p->S23.v = _mm_mul_epu32(p->R23.v, FIVE);
+		p->S24.v = _mm_mul_epu32(p->R24.v, FIVE);
+		p--;
+	}
+
+	/* put saved info back */
+	p = &st->P[1];
+	p->R20.d[1] = (uint32_t)(r0        );
+	p->R20.d[3] = (uint32_t)(r0   >> 32);
+	p->R21.d[1] = (uint32_t)(r1        );
+	p->R21.d[3] = (uint32_t)(r1   >> 32);
+	p->R22.d[1] = (uint32_t)(r2        );
+	p->R22.d[3] = (uint32_t)(r2   >> 32);
+	p->R23.d[1] = (uint32_t)(pad0      );
+	p->R23.d[3] = (uint32_t)(pad0 >> 32);
+	p->R24.d[1] = (uint32_t)(pad1      );
+	p->R24.d[3] = (uint32_t)(pad1 >> 32);
+
+	/* H = [Mx,My] */
+	T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 0)), _mm_loadl_epi64((xmmi *)(m + 16)));
+	T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 8)), _mm_loadl_epi64((xmmi *)(m + 24)));
+	st->H[0] = _mm_and_si128(MMASK, T5);
+	st->H[1] = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+	T5 = _mm_or_si128(_mm_srli_epi64(T5, 52), _mm_slli_epi64(T6, 12));
+	st->H[2] = _mm_and_si128(MMASK, T5);
+	st->H[3] = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+	st->H[4] = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT);
+}
+
+static void
+poly1305_blocks(poly1305_state_internal *st, const uint8_t *m, size_t bytes) {
+	const xmmi MMASK = _mm_load_si128((xmmi *)poly1305_x64_sse2_message_mask);
+	const xmmi FIVE = _mm_load_si128((xmmi*)poly1305_x64_sse2_5);
+	const xmmi HIBIT = _mm_load_si128((xmmi*)poly1305_x64_sse2_1shl128);
+
+	poly1305_power *p;
+	xmmi H0,H1,H2,H3,H4;
+	xmmi T0,T1,T2,T3,T4,T5,T6;
+	xmmi M0,M1,M2,M3,M4;
+	xmmi C1,C2;
+
+	H0 = st->H[0];
+	H1 = st->H[1];
+	H2 = st->H[2];
+	H3 = st->H[3];
+	H4 = st->H[4];
+
+	while (bytes >= 64) {
+		/* H *= [r^4,r^4] */
+		p = &st->P[0];
+		T0 = _mm_mul_epu32(H0, p->R20.v);
+		T1 = _mm_mul_epu32(H0, p->R21.v);
+		T2 = _mm_mul_epu32(H0, p->R22.v);
+		T3 = _mm_mul_epu32(H0, p->R23.v);
+		T4 = _mm_mul_epu32(H0, p->R24.v);
+		T5 = _mm_mul_epu32(H1, p->S24.v); T6 = _mm_mul_epu32(H1, p->R20.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H2, p->S23.v); T6 = _mm_mul_epu32(H2, p->S24.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H3, p->S22.v); T6 = _mm_mul_epu32(H3, p->S23.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H4, p->S21.v); T6 = _mm_mul_epu32(H4, p->S22.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H1, p->R21.v); T6 = _mm_mul_epu32(H1, p->R22.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H2, p->R20.v); T6 = _mm_mul_epu32(H2, p->R21.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H3, p->S24.v); T6 = _mm_mul_epu32(H3, p->R20.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H4, p->S23.v); T6 = _mm_mul_epu32(H4, p->S24.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H1, p->R23.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(H2, p->R22.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(H3, p->R21.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(H4, p->R20.v);                                   T4 = _mm_add_epi64(T4, T5);
+
+		/* H += [Mx,My]*[r^2,r^2] */
+		T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 0)), _mm_loadl_epi64((xmmi *)(m + 16)));
+		T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 8)), _mm_loadl_epi64((xmmi *)(m + 24)));
+		M0 = _mm_and_si128(MMASK, T5);
+		M1 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+		T5 = _mm_or_si128(_mm_srli_epi64(T5, 52), _mm_slli_epi64(T6, 12));
+		M2 = _mm_and_si128(MMASK, T5);
+		M3 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+		M4 = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT);
+
+		p = &st->P[1];
+		T5 = _mm_mul_epu32(M0, p->R20.v); T6 = _mm_mul_epu32(M0, p->R21.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(M1, p->S24.v); T6 = _mm_mul_epu32(M1, p->R20.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(M2, p->S23.v); T6 = _mm_mul_epu32(M2, p->S24.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(M3, p->S22.v); T6 = _mm_mul_epu32(M3, p->S23.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(M4, p->S21.v); T6 = _mm_mul_epu32(M4, p->S22.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(M0, p->R22.v); T6 = _mm_mul_epu32(M0, p->R23.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(M1, p->R21.v); T6 = _mm_mul_epu32(M1, p->R22.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(M2, p->R20.v); T6 = _mm_mul_epu32(M2, p->R21.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(M3, p->S24.v); T6 = _mm_mul_epu32(M3, p->R20.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(M4, p->S23.v); T6 = _mm_mul_epu32(M4, p->S24.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(M0, p->R24.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(M1, p->R23.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(M2, p->R22.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(M3, p->R21.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(M4, p->R20.v);                                   T4 = _mm_add_epi64(T4, T5);
+
+		/* H += [Mx,My] */
+		T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 32)), _mm_loadl_epi64((xmmi *)(m + 48)));
+		T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 40)), _mm_loadl_epi64((xmmi *)(m + 56)));
+		M0 = _mm_and_si128(MMASK, T5);
+		M1 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+		T5 = _mm_or_si128(_mm_srli_epi64(T5, 52), _mm_slli_epi64(T6, 12));
+		M2 = _mm_and_si128(MMASK, T5);
+		M3 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+		M4 = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT);
+
+		T0 = _mm_add_epi64(T0, M0);
+		T1 = _mm_add_epi64(T1, M1);
+		T2 = _mm_add_epi64(T2, M2);
+		T3 = _mm_add_epi64(T3, M3);
+		T4 = _mm_add_epi64(T4, M4);
+
+		/* reduce */
+		C1 = _mm_srli_epi64(T0, 26); C2 = _mm_srli_epi64(T3, 26); T0 = _mm_and_si128(T0, MMASK); T3 = _mm_and_si128(T3, MMASK); T1 = _mm_add_epi64(T1, C1); T4 = _mm_add_epi64(T4, C2);
+		C1 = _mm_srli_epi64(T1, 26); C2 = _mm_srli_epi64(T4, 26); T1 = _mm_and_si128(T1, MMASK); T4 = _mm_and_si128(T4, MMASK); T2 = _mm_add_epi64(T2, C1); T0 = _mm_add_epi64(T0, _mm_mul_epu32(C2, FIVE));
+		C1 = _mm_srli_epi64(T2, 26); C2 = _mm_srli_epi64(T0, 26); T2 = _mm_and_si128(T2, MMASK); T0 = _mm_and_si128(T0, MMASK); T3 = _mm_add_epi64(T3, C1); T1 = _mm_add_epi64(T1, C2);
+		C1 = _mm_srli_epi64(T3, 26);                              T3 = _mm_and_si128(T3, MMASK);                                T4 = _mm_add_epi64(T4, C1);
+
+		/* H = (H*[r^4,r^4] + [Mx,My]*[r^2,r^2] + [Mx,My]) */
+		H0 = T0;
+		H1 = T1;
+		H2 = T2;
+		H3 = T3;
+		H4 = T4;
+
+		m += 64;
+		bytes -= 64;
+	}
+
+	st->H[0] = H0;
+	st->H[1] = H1;
+	st->H[2] = H2;
+	st->H[3] = H3;
+	st->H[4] = H4;
+}
+
+static size_t
+poly1305_combine(poly1305_state_internal *st, const uint8_t *m, size_t bytes) {
+	const xmmi MMASK = _mm_load_si128((xmmi *)poly1305_x64_sse2_message_mask);
+	const xmmi HIBIT = _mm_load_si128((xmmi*)poly1305_x64_sse2_1shl128);
+	const xmmi FIVE = _mm_load_si128((xmmi*)poly1305_x64_sse2_5);
+
+	poly1305_power *p;
+	xmmi H0,H1,H2,H3,H4;
+	xmmi M0,M1,M2,M3,M4;
+	xmmi T0,T1,T2,T3,T4,T5,T6;
+	xmmi C1,C2;
+
+	uint64_t r0,r1,r2;
+	uint64_t t0,t1,t2,t3,t4;
+	uint64_t c;
+	size_t consumed = 0;
+
+	H0 = st->H[0];
+	H1 = st->H[1];
+	H2 = st->H[2];
+	H3 = st->H[3];
+	H4 = st->H[4];
+
+	/* p = [r^2,r^2] */
+	p = &st->P[1];
+
+	if (bytes >= 32) {
+		/* H *= [r^2,r^2] */
+		T0 = _mm_mul_epu32(H0, p->R20.v);
+		T1 = _mm_mul_epu32(H0, p->R21.v);
+		T2 = _mm_mul_epu32(H0, p->R22.v);
+		T3 = _mm_mul_epu32(H0, p->R23.v);
+		T4 = _mm_mul_epu32(H0, p->R24.v);
+		T5 = _mm_mul_epu32(H1, p->S24.v); T6 = _mm_mul_epu32(H1, p->R20.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H2, p->S23.v); T6 = _mm_mul_epu32(H2, p->S24.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H3, p->S22.v); T6 = _mm_mul_epu32(H3, p->S23.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H4, p->S21.v); T6 = _mm_mul_epu32(H4, p->S22.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+		T5 = _mm_mul_epu32(H1, p->R21.v); T6 = _mm_mul_epu32(H1, p->R22.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H2, p->R20.v); T6 = _mm_mul_epu32(H2, p->R21.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H3, p->S24.v); T6 = _mm_mul_epu32(H3, p->R20.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H4, p->S23.v); T6 = _mm_mul_epu32(H4, p->S24.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+		T5 = _mm_mul_epu32(H1, p->R23.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(H2, p->R22.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(H3, p->R21.v);                                   T4 = _mm_add_epi64(T4, T5);
+		T5 = _mm_mul_epu32(H4, p->R20.v);                                   T4 = _mm_add_epi64(T4, T5);
+
+		/* H += [Mx,My] */
+		T5 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 0)), _mm_loadl_epi64((xmmi *)(m + 16)));
+		T6 = _mm_unpacklo_epi64(_mm_loadl_epi64((xmmi *)(m + 8)), _mm_loadl_epi64((xmmi *)(m + 24)));
+		M0 = _mm_and_si128(MMASK, T5);
+		M1 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+		T5 = _mm_or_si128(_mm_srli_epi64(T5, 52), _mm_slli_epi64(T6, 12));
+		M2 = _mm_and_si128(MMASK, T5);
+		M3 = _mm_and_si128(MMASK, _mm_srli_epi64(T5, 26));
+		M4 = _mm_or_si128(_mm_srli_epi64(T6, 40), HIBIT);
+
+		T0 = _mm_add_epi64(T0, M0);
+		T1 = _mm_add_epi64(T1, M1);
+		T2 = _mm_add_epi64(T2, M2);
+		T3 = _mm_add_epi64(T3, M3);
+		T4 = _mm_add_epi64(T4, M4);
+
+		/* reduce */
+		C1 = _mm_srli_epi64(T0, 26); C2 = _mm_srli_epi64(T3, 26); T0 = _mm_and_si128(T0, MMASK); T3 = _mm_and_si128(T3, MMASK); T1 = _mm_add_epi64(T1, C1); T4 = _mm_add_epi64(T4, C2);
+		C1 = _mm_srli_epi64(T1, 26); C2 = _mm_srli_epi64(T4, 26); T1 = _mm_and_si128(T1, MMASK); T4 = _mm_and_si128(T4, MMASK); T2 = _mm_add_epi64(T2, C1); T0 = _mm_add_epi64(T0, _mm_mul_epu32(C2, FIVE));
+		C1 = _mm_srli_epi64(T2, 26); C2 = _mm_srli_epi64(T0, 26); T2 = _mm_and_si128(T2, MMASK); T0 = _mm_and_si128(T0, MMASK); T3 = _mm_add_epi64(T3, C1); T1 = _mm_add_epi64(T1, C2);
+		C1 = _mm_srli_epi64(T3, 26);                              T3 = _mm_and_si128(T3, MMASK);                                T4 = _mm_add_epi64(T4, C1);
+
+		/* H = (H*[r^2,r^2] + [Mx,My]) */
+		H0 = T0;
+		H1 = T1;
+		H2 = T2;
+		H3 = T3;
+		H4 = T4;
+
+		consumed = 32;
+	}
+
+	/* finalize, H *= [r^2,r] */
+	r0 = ((uint64_t)p->R20.d[3] << 32) | (uint64_t)p->R20.d[1];
+	r1 = ((uint64_t)p->R21.d[3] << 32) | (uint64_t)p->R21.d[1];
+	r2 = ((uint64_t)p->R22.d[3] << 32) | (uint64_t)p->R22.d[1];
+
+	p->R20.d[2] = (uint32_t)( r0                    ) & 0x3ffffff;
+	p->R21.d[2] = (uint32_t)((r0 >> 26) | (r1 << 18)) & 0x3ffffff;
+	p->R22.d[2] = (uint32_t)((r1 >> 8)              ) & 0x3ffffff;
+	p->R23.d[2] = (uint32_t)((r1 >> 34) | (r2 << 10)) & 0x3ffffff;
+	p->R24.d[2] = (uint32_t)((r2 >> 16)             )            ;
+	p->S21.d[2] = p->R21.d[2] * 5;
+	p->S22.d[2] = p->R22.d[2] * 5;
+	p->S23.d[2] = p->R23.d[2] * 5;
+	p->S24.d[2] = p->R24.d[2] * 5;
+
+	/* H *= [r^2,r] */
+	T0 = _mm_mul_epu32(H0, p->R20.v);
+	T1 = _mm_mul_epu32(H0, p->R21.v);
+	T2 = _mm_mul_epu32(H0, p->R22.v);
+	T3 = _mm_mul_epu32(H0, p->R23.v);
+	T4 = _mm_mul_epu32(H0, p->R24.v);
+	T5 = _mm_mul_epu32(H1, p->S24.v); T6 = _mm_mul_epu32(H1, p->R20.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+	T5 = _mm_mul_epu32(H2, p->S23.v); T6 = _mm_mul_epu32(H2, p->S24.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+	T5 = _mm_mul_epu32(H3, p->S22.v); T6 = _mm_mul_epu32(H3, p->S23.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+	T5 = _mm_mul_epu32(H4, p->S21.v); T6 = _mm_mul_epu32(H4, p->S22.v); T0 = _mm_add_epi64(T0, T5); T1 = _mm_add_epi64(T1, T6);
+	T5 = _mm_mul_epu32(H1, p->R21.v); T6 = _mm_mul_epu32(H1, p->R22.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+	T5 = _mm_mul_epu32(H2, p->R20.v); T6 = _mm_mul_epu32(H2, p->R21.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+	T5 = _mm_mul_epu32(H3, p->S24.v); T6 = _mm_mul_epu32(H3, p->R20.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+	T5 = _mm_mul_epu32(H4, p->S23.v); T6 = _mm_mul_epu32(H4, p->S24.v); T2 = _mm_add_epi64(T2, T5); T3 = _mm_add_epi64(T3, T6);
+	T5 = _mm_mul_epu32(H1, p->R23.v);                                   T4 = _mm_add_epi64(T4, T5);
+	T5 = _mm_mul_epu32(H2, p->R22.v);                                   T4 = _mm_add_epi64(T4, T5);
+	T5 = _mm_mul_epu32(H3, p->R21.v);                                   T4 = _mm_add_epi64(T4, T5);
+	T5 = _mm_mul_epu32(H4, p->R20.v);                                   T4 = _mm_add_epi64(T4, T5);
+
+	C1 = _mm_srli_epi64(T0, 26); C2 = _mm_srli_epi64(T3, 26); T0 = _mm_and_si128(T0, MMASK); T3 = _mm_and_si128(T3, MMASK); T1 = _mm_add_epi64(T1, C1); T4 = _mm_add_epi64(T4, C2);
+	C1 = _mm_srli_epi64(T1, 26); C2 = _mm_srli_epi64(T4, 26); T1 = _mm_and_si128(T1, MMASK); T4 = _mm_and_si128(T4, MMASK); T2 = _mm_add_epi64(T2, C1); T0 = _mm_add_epi64(T0, _mm_mul_epu32(C2, FIVE));
+	C1 = _mm_srli_epi64(T2, 26); C2 = _mm_srli_epi64(T0, 26); T2 = _mm_and_si128(T2, MMASK); T0 = _mm_and_si128(T0, MMASK); T3 = _mm_add_epi64(T3, C1); T1 = _mm_add_epi64(T1, C2);
+	C1 = _mm_srli_epi64(T3, 26);                              T3 = _mm_and_si128(T3, MMASK);                                T4 = _mm_add_epi64(T4, C1);
+
+	/* H = H[0]+H[1] */
+	H0 = _mm_add_epi64(T0, _mm_srli_si128(T0, 8));
+	H1 = _mm_add_epi64(T1, _mm_srli_si128(T1, 8));
+	H2 = _mm_add_epi64(T2, _mm_srli_si128(T2, 8));
+	H3 = _mm_add_epi64(T3, _mm_srli_si128(T3, 8));
+	H4 = _mm_add_epi64(T4, _mm_srli_si128(T4, 8));
+
+	t0 = _mm_cvtsi128_si32(H0)    ; c = (t0 >> 26); t0 &= 0x3ffffff;
+	t1 = _mm_cvtsi128_si32(H1) + c; c = (t1 >> 26); t1 &= 0x3ffffff;
+	t2 = _mm_cvtsi128_si32(H2) + c; c = (t2 >> 26); t2 &= 0x3ffffff;
+	t3 = _mm_cvtsi128_si32(H3) + c; c = (t3 >> 26); t3 &= 0x3ffffff;
+	t4 = _mm_cvtsi128_si32(H4) + c; c = (t4 >> 26); t4 &= 0x3ffffff;
+	t0 =              t0 + (c * 5); c = (t0 >> 26); t0 &= 0x3ffffff;
+	t1 =              t1 + c;
+
+	st->HH[0] =  ((t0      ) | (t1 << 26)             ) & 0xfffffffffffull;
+	st->HH[1] =  ((t1 >> 18) | (t2 <<  8) | (t3 << 34)) & 0xfffffffffffull;
+	st->HH[2] =  ((t3 >> 10) | (t4 << 16)             ) & 0x3ffffffffffull;
+
+	return consumed;
+}
+
+void
+Poly1305Update(poly1305_state *state, const unsigned char *m, size_t bytes) {
+	poly1305_state_internal *st = poly1305_aligned_state(state);
+	size_t want;
+
+	/* need at least 32 initial bytes to start the accelerated branch */
+	if (!st->started) {
+		if ((st->leftover == 0) && (bytes > 32)) {
+			poly1305_first_block(st, m);
+			m += 32;
+			bytes -= 32;
+		} else {
+			want = poly1305_min(32 - st->leftover, bytes);
+			poly1305_block_copy(st->buffer + st->leftover, m, want);
+			bytes -= want;
+			m += want;
+			st->leftover += want;
+			if ((st->leftover < 32) || (bytes == 0))
+				return;
+			poly1305_first_block(st, st->buffer);
+			st->leftover = 0;
+		}
+		st->started = 1;
+	}
+
+	/* handle leftover */
+	if (st->leftover) {
+		want = poly1305_min(64 - st->leftover, bytes);
+		poly1305_block_copy(st->buffer + st->leftover, m, want);
+		bytes -= want;
+		m += want;
+		st->leftover += want;
+		if (st->leftover < 64)
+			return;
+		poly1305_blocks(st, st->buffer, 64);
+		st->leftover = 0;
+	}
+
+	/* process 64 byte blocks */
+	if (bytes >= 64) {
+		want = (bytes & ~63);
+		poly1305_blocks(st, m, want);
+		m += want;
+		bytes -= want;
+	}
+
+	if (bytes) {
+		poly1305_block_copy(st->buffer + st->leftover, m, bytes);
+		st->leftover += bytes;
+	}
+}
+
+void
+Poly1305Finish(poly1305_state *state, unsigned char mac[16]) {
+	poly1305_state_internal *st = poly1305_aligned_state(state);
+	size_t leftover = st->leftover;
+	uint8_t *m = st->buffer;
+	uint128_t d[3];
+	uint64_t h0,h1,h2;
+	uint64_t t0,t1;
+	uint64_t g0,g1,g2,c,nc;
+	uint64_t r0,r1,r2,s1,s2;
+	poly1305_power *p;
+
+	if (st->started) {
+		size_t consumed = poly1305_combine(st, m, leftover);
+		leftover -= consumed;
+		m += consumed;
+	}
+
+	/* st->HH will either be 0 or have the combined result */
+	h0 = st->HH[0];
+	h1 = st->HH[1];
+	h2 = st->HH[2];
+
+	p = &st->P[1];
+	r0 = ((uint64_t)p->R20.d[3] << 32) | (uint64_t)p->R20.d[1];
+	r1 = ((uint64_t)p->R21.d[3] << 32) | (uint64_t)p->R21.d[1];
+	r2 = ((uint64_t)p->R22.d[3] << 32) | (uint64_t)p->R22.d[1];
+	s1 = r1 * (5 << 2);
+	s2 = r2 * (5 << 2);
+
+	if (leftover < 16)
+		goto poly1305_donna_atmost15bytes;
+
+poly1305_donna_atleast16bytes:
+	t0 = U8TO64_LE(m + 0);
+	t1 = U8TO64_LE(m + 8);
+	h0 += t0 & 0xfffffffffff;
+	t0 = shr128_pair(t1, t0, 44);
+	h1 += t0 & 0xfffffffffff;
+	h2 += (t1 >> 24) | ((uint64_t)1 << 40);
+
+poly1305_donna_mul:
+	d[0] = add128(add128(mul64x64_128(h0, r0), mul64x64_128(h1, s2)), mul64x64_128(h2, s1));
+	d[1] = add128(add128(mul64x64_128(h0, r1), mul64x64_128(h1, r0)), mul64x64_128(h2, s2));
+	d[2] = add128(add128(mul64x64_128(h0, r2), mul64x64_128(h1, r1)), mul64x64_128(h2, r0));
+	                           h0 = lo128(d[0]) & 0xfffffffffff; c = shr128(d[0], 44);
+	d[1] = add128_64(d[1], c); h1 = lo128(d[1]) & 0xfffffffffff; c = shr128(d[1], 44);
+	d[2] = add128_64(d[2], c); h2 = lo128(d[2]) & 0x3ffffffffff; c = shr128(d[2], 42);
+	h0   += c * 5;
+
+	m += 16;
+	leftover -= 16;
+	if (leftover >= 16) goto poly1305_donna_atleast16bytes;
+
+	/* final bytes */
+poly1305_donna_atmost15bytes:
+	if (!leftover) goto poly1305_donna_finish;
+
+	m[leftover++] = 1;
+	poly1305_block_zero(m + leftover, 16 - leftover);
+	leftover = 16;
+
+	t0 = U8TO64_LE(m+0);
+	t1 = U8TO64_LE(m+8);
+	h0 += t0 & 0xfffffffffff; t0 = shr128_pair(t1, t0, 44);
+	h1 += t0 & 0xfffffffffff;
+	h2 += (t1 >> 24);
+
+	goto poly1305_donna_mul;
+
+poly1305_donna_finish:
+	             c = (h0 >> 44); h0 &= 0xfffffffffff;
+	h1 += c;     c = (h1 >> 44); h1 &= 0xfffffffffff;
+	h2 += c;     c = (h2 >> 42); h2 &= 0x3ffffffffff;
+	h0 += c * 5;
+
+	g0 = h0 + 5; c = (g0 >> 44); g0 &= 0xfffffffffff;
+	g1 = h1 + c; c = (g1 >> 44); g1 &= 0xfffffffffff;
+	g2 = h2 + c - ((uint64_t)1 << 42);
+
+	c = (g2 >> 63) - 1;
+	nc = ~c;
+	h0 = (h0 & nc) | (g0 & c);
+	h1 = (h1 & nc) | (g1 & c);
+	h2 = (h2 & nc) | (g2 & c);
+
+	/* pad */
+	t0 = ((uint64_t)p->R23.d[3] << 32) | (uint64_t)p->R23.d[1];
+	t1 = ((uint64_t)p->R24.d[3] << 32) | (uint64_t)p->R24.d[1];
+	h0 += (t0 & 0xfffffffffff)    ; c = (h0 >> 44); h0 &= 0xfffffffffff; t0 = shr128_pair(t1, t0, 44);
+	h1 += (t0 & 0xfffffffffff) + c; c = (h1 >> 44); h1 &= 0xfffffffffff; t1 = (t1 >> 24);
+	h2 += (t1                ) + c;
+
+	U64TO8_LE(mac + 0, ((h0      ) | (h1 << 44)));
+	U64TO8_LE(mac + 8, ((h1 >> 20) | (h2 << 24)));
+}
new file mode 100644
--- /dev/null
+++ b/lib/freebl/poly1305.c
@@ -0,0 +1,254 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* This implementation of poly1305 is by Andrew Moon
+ * (https://github.com/floodyberry/poly1305-donna) and released as public
+ * domain. */
+
+#include <string.h>
+#include <stdint.h>
+
+#include "poly1305.h"
+
+#if defined(NSS_X86) || defined(NSS_X64)
+/* We can assume little-endian. */
+static uint32_t U8TO32_LE(const unsigned char *m) {
+	uint32_t r;
+	memcpy(&r, m, sizeof(r));
+	return r;
+}
+
+static void U32TO8_LE(unsigned char *m, uint32_t v) {
+	memcpy(m, &v, sizeof(v));
+}
+#else
+static uint32_t U8TO32_LE(const unsigned char *m) {
+	return (uint32_t)m[0] |
+	       (uint32_t)m[1] << 8 |
+	       (uint32_t)m[2] << 16 |
+	       (uint32_t)m[3] << 24;
+}
+
+static void U32TO8_LE(unsigned char *m, uint32_t v) {
+	m[0] = v;
+	m[1] = v >> 8;
+	m[2] = v >> 16;
+	m[3] = v >> 24;
+}
+#endif
+
+static uint64_t
+mul32x32_64(uint32_t a, uint32_t b) {
+	return (uint64_t)a * b;
+}
+
+struct poly1305_state_st {
+	uint32_t r0,r1,r2,r3,r4;
+	uint32_t s1,s2,s3,s4;
+	uint32_t h0,h1,h2,h3,h4;
+	unsigned char buf[16];
+	unsigned int buf_used;
+	unsigned char key[16];
+};
+
+/* update updates |state| given some amount of input data. This function may
+ * only be called with a |len| that is not a multiple of 16 at the end of the
+ * data. Otherwise the input must be buffered into 16 byte blocks. */
+static void update(struct poly1305_state_st *state, const unsigned char *in,
+		   size_t len) {
+	uint32_t t0,t1,t2,t3;
+	uint64_t t[5];
+	uint32_t b;
+	uint64_t c;
+	size_t j;
+	unsigned char mp[16];
+
+	if (len < 16)
+		goto poly1305_donna_atmost15bytes;
+
+poly1305_donna_16bytes:
+	t0 = U8TO32_LE(in);
+	t1 = U8TO32_LE(in+4);
+	t2 = U8TO32_LE(in+8);
+	t3 = U8TO32_LE(in+12);
+
+	in += 16;
+	len -= 16;
+
+	state->h0 += t0 & 0x3ffffff;
+	state->h1 += ((((uint64_t)t1 << 32) | t0) >> 26) & 0x3ffffff;
+	state->h2 += ((((uint64_t)t2 << 32) | t1) >> 20) & 0x3ffffff;
+	state->h3 += ((((uint64_t)t3 << 32) | t2) >> 14) & 0x3ffffff;
+	state->h4 += (t3 >> 8) | (1 << 24);
+
+poly1305_donna_mul:
+	t[0] = mul32x32_64(state->h0,state->r0) +
+	       mul32x32_64(state->h1,state->s4) +
+	       mul32x32_64(state->h2,state->s3) +
+	       mul32x32_64(state->h3,state->s2) +
+	       mul32x32_64(state->h4,state->s1);
+	t[1] = mul32x32_64(state->h0,state->r1) +
+	       mul32x32_64(state->h1,state->r0) +
+	       mul32x32_64(state->h2,state->s4) +
+	       mul32x32_64(state->h3,state->s3) +
+	       mul32x32_64(state->h4,state->s2);
+	t[2] = mul32x32_64(state->h0,state->r2) +
+	       mul32x32_64(state->h1,state->r1) +
+	       mul32x32_64(state->h2,state->r0) +
+	       mul32x32_64(state->h3,state->s4) +
+	       mul32x32_64(state->h4,state->s3);
+	t[3] = mul32x32_64(state->h0,state->r3) +
+	       mul32x32_64(state->h1,state->r2) +
+	       mul32x32_64(state->h2,state->r1) +
+	       mul32x32_64(state->h3,state->r0) +
+	       mul32x32_64(state->h4,state->s4);
+	t[4] = mul32x32_64(state->h0,state->r4) +
+	       mul32x32_64(state->h1,state->r3) +
+	       mul32x32_64(state->h2,state->r2) +
+	       mul32x32_64(state->h3,state->r1) +
+	       mul32x32_64(state->h4,state->r0);
+
+	           state->h0 = (uint32_t)t[0] & 0x3ffffff; c =           (t[0] >> 26);
+	t[1] += c; state->h1 = (uint32_t)t[1] & 0x3ffffff; b = (uint32_t)(t[1] >> 26);
+	t[2] += b; state->h2 = (uint32_t)t[2] & 0x3ffffff; b = (uint32_t)(t[2] >> 26);
+	t[3] += b; state->h3 = (uint32_t)t[3] & 0x3ffffff; b = (uint32_t)(t[3] >> 26);
+	t[4] += b; state->h4 = (uint32_t)t[4] & 0x3ffffff; b = (uint32_t)(t[4] >> 26);
+	state->h0 += b * 5;
+
+	if (len >= 16)
+		goto poly1305_donna_16bytes;
+
+	/* final bytes */
+poly1305_donna_atmost15bytes:
+	if (!len)
+		return;
+
+	for (j = 0; j < len; j++)
+		mp[j] = in[j];
+	mp[j++] = 1;
+	for (; j < 16; j++)
+		mp[j] = 0;
+	len = 0;
+
+	t0 = U8TO32_LE(mp+0);
+	t1 = U8TO32_LE(mp+4);
+	t2 = U8TO32_LE(mp+8);
+	t3 = U8TO32_LE(mp+12);
+
+	state->h0 += t0 & 0x3ffffff;
+	state->h1 += ((((uint64_t)t1 << 32) | t0) >> 26) & 0x3ffffff;
+	state->h2 += ((((uint64_t)t2 << 32) | t1) >> 20) & 0x3ffffff;
+	state->h3 += ((((uint64_t)t3 << 32) | t2) >> 14) & 0x3ffffff;
+	state->h4 += (t3 >> 8);
+
+	goto poly1305_donna_mul;
+}
+
+void Poly1305Init(poly1305_state *statep, const unsigned char key[32]) {
+	struct poly1305_state_st *state = (struct poly1305_state_st*) statep;
+	uint32_t t0,t1,t2,t3;
+
+	t0 = U8TO32_LE(key+0);
+	t1 = U8TO32_LE(key+4);
+	t2 = U8TO32_LE(key+8);
+	t3 = U8TO32_LE(key+12);
+
+	/* precompute multipliers */
+	state->r0 = t0 & 0x3ffffff; t0 >>= 26; t0 |= t1 << 6;
+	state->r1 = t0 & 0x3ffff03; t1 >>= 20; t1 |= t2 << 12;
+	state->r2 = t1 & 0x3ffc0ff; t2 >>= 14; t2 |= t3 << 18;
+	state->r3 = t2 & 0x3f03fff; t3 >>= 8;
+	state->r4 = t3 & 0x00fffff;
+
+	state->s1 = state->r1 * 5;
+	state->s2 = state->r2 * 5;
+	state->s3 = state->r3 * 5;
+	state->s4 = state->r4 * 5;
+
+	/* init state */
+	state->h0 = 0;
+	state->h1 = 0;
+	state->h2 = 0;
+	state->h3 = 0;
+	state->h4 = 0;
+
+	state->buf_used = 0;
+	memcpy(state->key, key + 16, sizeof(state->key));
+}
+
+void Poly1305Update(poly1305_state *statep, const unsigned char *in,
+		     size_t in_len) {
+	unsigned int i;
+	struct poly1305_state_st *state = (struct poly1305_state_st*) statep;
+
+	if (state->buf_used) {
+		unsigned int todo = 16 - state->buf_used;
+		if (todo > in_len)
+			todo = in_len;
+		for (i = 0; i < todo; i++)
+			state->buf[state->buf_used + i] = in[i];
+		state->buf_used += todo;
+		in_len -= todo;
+		in += todo;
+
+		if (state->buf_used == 16) {
+			update(state, state->buf, 16);
+			state->buf_used = 0;
+		}
+	}
+
+	if (in_len >= 16) {
+		size_t todo = in_len & ~0xf;
+		update(state, in, todo);
+		in += todo;
+		in_len &= 0xf;
+	}
+
+	if (in_len) {
+		for (i = 0; i < in_len; i++)
+			state->buf[i] = in[i];
+		state->buf_used = in_len;
+	}
+}
+
+void Poly1305Finish(poly1305_state *statep, unsigned char mac[16]) {
+	struct poly1305_state_st *state = (struct poly1305_state_st*) statep;
+	uint64_t f0,f1,f2,f3;
+	uint32_t g0,g1,g2,g3,g4;
+	uint32_t b, nb;
+
+	if (state->buf_used)
+		update(state, state->buf, state->buf_used);
+
+	                    b = state->h0 >> 26; state->h0 = state->h0 & 0x3ffffff;
+	state->h1 +=     b; b = state->h1 >> 26; state->h1 = state->h1 & 0x3ffffff;
+	state->h2 +=     b; b = state->h2 >> 26; state->h2 = state->h2 & 0x3ffffff;
+	state->h3 +=     b; b = state->h3 >> 26; state->h3 = state->h3 & 0x3ffffff;
+	state->h4 +=     b; b = state->h4 >> 26; state->h4 = state->h4 & 0x3ffffff;
+	state->h0 += b * 5;
+
+	g0 = state->h0 + 5; b = g0 >> 26; g0 &= 0x3ffffff;
+	g1 = state->h1 + b; b = g1 >> 26; g1 &= 0x3ffffff;
+	g2 = state->h2 + b; b = g2 >> 26; g2 &= 0x3ffffff;
+	g3 = state->h3 + b; b = g3 >> 26; g3 &= 0x3ffffff;
+	g4 = state->h4 + b - (1 << 26);
+
+	b = (g4 >> 31) - 1;
+	nb = ~b;
+	state->h0 = (state->h0 & nb) | (g0 & b);
+	state->h1 = (state->h1 & nb) | (g1 & b);
+	state->h2 = (state->h2 & nb) | (g2 & b);
+	state->h3 = (state->h3 & nb) | (g3 & b);
+	state->h4 = (state->h4 & nb) | (g4 & b);
+
+	f0 = ((state->h0      ) | (state->h1 << 26)) + (uint64_t)U8TO32_LE(&state->key[0]);
+	f1 = ((state->h1 >>  6) | (state->h2 << 20)) + (uint64_t)U8TO32_LE(&state->key[4]);
+	f2 = ((state->h2 >> 12) | (state->h3 << 14)) + (uint64_t)U8TO32_LE(&state->key[8]);
+	f3 = ((state->h3 >> 18) | (state->h4 <<  8)) + (uint64_t)U8TO32_LE(&state->key[12]);
+
+	U32TO8_LE(&mac[ 0], (uint32_t)f0); f1 += (f0 >> 32);
+	U32TO8_LE(&mac[ 4], (uint32_t)f1); f2 += (f1 >> 32);
+	U32TO8_LE(&mac[ 8], (uint32_t)f2); f3 += (f2 >> 32);
+	U32TO8_LE(&mac[12], (uint32_t)f3);
+}
new file mode 100644
--- /dev/null
+++ b/lib/freebl/poly1305.h
@@ -0,0 +1,28 @@
+/*
+ * poly1305.h - header file for Poly1305 implementation.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef FREEBL_POLY1305_H_
+#define FREEBL_POLY1305_H_
+
+typedef unsigned char poly1305_state[512];
+
+/* Poly1305Init sets up |state| so that it can be used to calculate an
+ * authentication tag with the one-time key |key|. Note that |key| is a
+ * one-time key and therefore there is no `reset' method because that would
+ * enable several messages to be authenticated with the same key. */
+extern void Poly1305Init(poly1305_state* state, const unsigned char key[32]);
+
+/* Poly1305Update processes |in_len| bytes from |in|. It can be called zero or
+ * more times after poly1305_init. */
+extern void Poly1305Update(poly1305_state* state, const unsigned char* in,
+                           size_t inLen);
+
+/* Poly1305Finish completes the poly1305 calculation and writes a 16 byte
+ * authentication tag to |mac|. */
+extern void Poly1305Finish(poly1305_state* state, unsigned char mac[16]);
+
+#endif /* FREEBL_POLY1305_H_ */
--- a/lib/pk11wrap/pk11mech.c
+++ b/lib/pk11wrap/pk11mech.c
@@ -147,16 +147,18 @@ PK11_AddMechanismEntry(CK_MECHANISM_TYPE
 CK_MECHANISM_TYPE
 PK11_GetKeyMechanism(CK_KEY_TYPE type)
 {
     switch (type) {
     case CKK_SEED:
 	return CKM_SEED_CBC;
     case CKK_CAMELLIA:
 	return CKM_CAMELLIA_CBC;
+    case CKK_NSS_CHACHA20:
+	return CKM_NSS_CHACHA20_POLY1305;
     case CKK_AES:
 	return CKM_AES_CBC;
     case CKK_DES:
 	return CKM_DES_CBC;
     case CKK_DES3:
 	return CKM_DES3_KEY_GEN;
     case CKK_DES2:
 	return CKM_DES2_KEY_GEN;
@@ -214,16 +216,19 @@ PK11_GetKeyType(CK_MECHANISM_TYPE type,u
 	return CKK_SEED;
     case CKM_CAMELLIA_ECB:
     case CKM_CAMELLIA_CBC:
     case CKM_CAMELLIA_MAC:
     case CKM_CAMELLIA_MAC_GENERAL:
     case CKM_CAMELLIA_CBC_PAD:
     case CKM_CAMELLIA_KEY_GEN:
 	return CKK_CAMELLIA;
+    case CKM_NSS_CHACHA20_POLY1305:
+    case CKM_NSS_CHACHA20_KEY_GEN:
+	return CKK_NSS_CHACHA20;
     case CKM_AES_ECB:
     case CKM_AES_CBC:
     case CKM_AES_CCM:
     case CKM_AES_CTR:
     case CKM_AES_CTS:
     case CKM_AES_GCM:
     case CKM_AES_MAC:
     case CKM_AES_MAC_GENERAL:
@@ -426,16 +431,18 @@ PK11_GetKeyGenWithSize(CK_MECHANISM_TYPE
 	return CKM_SEED_KEY_GEN;
     case CKM_CAMELLIA_ECB:
     case CKM_CAMELLIA_CBC:
     case CKM_CAMELLIA_MAC:
     case CKM_CAMELLIA_MAC_GENERAL:
     case CKM_CAMELLIA_CBC_PAD:
     case CKM_CAMELLIA_KEY_GEN:
 	return CKM_CAMELLIA_KEY_GEN;
+    case CKM_NSS_CHACHA20_POLY1305:
+	return CKM_NSS_CHACHA20_KEY_GEN;
     case CKM_AES_ECB:
     case CKM_AES_CBC:
     case CKM_AES_CCM:
     case CKM_AES_CTR:
     case CKM_AES_CTS:
     case CKM_AES_GCM:
     case CKM_AES_MAC:
     case CKM_AES_MAC_GENERAL:
--- a/lib/softoken/pkcs11.c
+++ b/lib/softoken/pkcs11.c
@@ -365,16 +365,19 @@ static const struct mechanismList mechan
      {CKM_CAMELLIA_CBC_PAD,	{16, 32, CKF_EN_DE_WR_UN},      PR_TRUE},
      /* ------------------------- SEED Operations --------------------------- */
      {CKM_SEED_KEY_GEN,		{16, 16, CKF_GENERATE},		PR_TRUE},
      {CKM_SEED_ECB,		{16, 16, CKF_EN_DE_WR_UN},	PR_TRUE},
      {CKM_SEED_CBC,		{16, 16, CKF_EN_DE_WR_UN},	PR_TRUE},
      {CKM_SEED_MAC,		{16, 16, CKF_SN_VR},		PR_TRUE},
      {CKM_SEED_MAC_GENERAL,	{16, 16, CKF_SN_VR},		PR_TRUE},
      {CKM_SEED_CBC_PAD,		{16, 16, CKF_EN_DE_WR_UN},	PR_TRUE},
+     /* ------------------------- ChaCha20 Operations ---------------------- */
+     {CKM_NSS_CHACHA20_KEY_GEN,	{32, 32, CKF_GENERATE},		PR_TRUE},
+     {CKM_NSS_CHACHA20_POLY1305,{32, 32, CKF_EN_DE},		PR_TRUE},
      /* ------------------------- Hashing Operations ----------------------- */
      {CKM_MD2,			{0,   0, CKF_DIGEST},		PR_FALSE},
      {CKM_MD2_HMAC,		{1, 128, CKF_SN_VR},		PR_TRUE},
      {CKM_MD2_HMAC_GENERAL,	{1, 128, CKF_SN_VR},		PR_TRUE},
      {CKM_MD5,			{0,   0, CKF_DIGEST},		PR_FALSE},
      {CKM_MD5_HMAC,		{1, 128, CKF_SN_VR},		PR_TRUE},
      {CKM_MD5_HMAC_GENERAL,	{1, 128, CKF_SN_VR},		PR_TRUE},
      {CKM_SHA_1,		{0,   0, CKF_DIGEST},		PR_FALSE},
--- a/lib/softoken/pkcs11c.c
+++ b/lib/softoken/pkcs11c.c
@@ -660,16 +660,107 @@ sftk_RSADecryptOAEP(SFTKOAEPDecryptInfo 
                          info->params->ulSourceDataLen,
                          output, outputLen, maxLen, input, inputLen);
      if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) {
         sftk_fatalError = PR_TRUE;
     }
     return rv;
 }
 
+static SFTKChaCha20Poly1305Info *
+sftk_ChaCha20Poly1305_CreateContext(const unsigned char *key,
+                                    unsigned int keyLen,
+                                    const CK_NSS_AEAD_PARAMS *params)
+{
+    SFTKChaCha20Poly1305Info *ctx;
+
+    if (params->ulNonceLen != sizeof(ctx->nonce)) {
+        PORT_SetError(SEC_ERROR_INPUT_LEN);
+        return NULL;
+    }
+
+    ctx = PORT_New(SFTKChaCha20Poly1305Info);
+    if (ctx == NULL) {
+        return NULL;
+    }
+
+    if (ChaCha20Poly1305_InitContext(&ctx->freeblCtx, key, keyLen,
+                                     params->ulTagLen) != SECSuccess) {
+        PORT_Free(ctx);
+        return NULL;
+    }
+
+    PORT_Memcpy(ctx->nonce, params->pNonce, sizeof(ctx->nonce));
+
+    if (params->ulAADLen > sizeof(ctx->ad)) {
+        /* Need to allocate an overflow buffer for the additional data. */
+        ctx->adOverflow = (unsigned char *)PORT_Alloc(params->ulAADLen);
+        if (!ctx->adOverflow) {
+            PORT_Free(ctx);
+            return NULL;
+        }
+        PORT_Memcpy(ctx->adOverflow, params->pAAD, params->ulAADLen);
+    } else {
+        ctx->adOverflow = NULL;
+        PORT_Memcpy(ctx->ad, params->pAAD, params->ulAADLen);
+    }
+    ctx->adLen = params->ulAADLen;
+
+    return ctx;
+}
+
+static void
+sftk_ChaCha20Poly1305_DestroyContext(SFTKChaCha20Poly1305Info *ctx,
+                                     PRBool freeit)
+{
+    ChaCha20Poly1305_DestroyContext(&ctx->freeblCtx, PR_FALSE);
+    if (ctx->adOverflow != NULL) {
+        PORT_Free(ctx->adOverflow);
+        ctx->adOverflow = NULL;
+    }
+    ctx->adLen = 0;
+    if (freeit) {
+        PORT_Free(ctx);
+    }
+}
+
+static SECStatus
+sftk_ChaCha20Poly1305_Encrypt(const SFTKChaCha20Poly1305Info *ctx,
+                              unsigned char *output, unsigned int *outputLen,
+                              unsigned int maxOutputLen,
+                              const unsigned char *input, unsigned int inputLen)
+{
+    const unsigned char *ad = ctx->adOverflow;
+
+    if (ad == NULL) {
+        ad = ctx->ad;
+    }
+
+    return ChaCha20Poly1305_Seal(&ctx->freeblCtx, output, outputLen,
+                                 maxOutputLen, input, inputLen, ctx->nonce,
+                                 sizeof(ctx->nonce), ad, ctx->adLen);
+}
+
+static SECStatus
+sftk_ChaCha20Poly1305_Decrypt(const SFTKChaCha20Poly1305Info *ctx,
+                              unsigned char *output, unsigned int *outputLen,
+                              unsigned int maxOutputLen,
+                              const unsigned char *input, unsigned int inputLen)
+{
+    const unsigned char *ad = ctx->adOverflow;
+
+    if (ad == NULL) {
+        ad = ctx->ad;
+    }
+
+    return ChaCha20Poly1305_Open(&ctx->freeblCtx, output, outputLen,
+                                 maxOutputLen, input, inputLen, ctx->nonce,
+                                 sizeof(ctx->nonce), ad, ctx->adLen);
+}
+
 /** NSC_CryptInit initializes an encryption/Decryption operation.
  *
  * Always called by NSC_EncryptInit, NSC_DecryptInit, NSC_WrapKey,NSC_UnwrapKey.
  * Called by NSC_SignInit, NSC_VerifyInit (via sftk_InitCBCMac) only for block
  *  ciphers MAC'ing.
  */
 static CK_RV
 sftk_CryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism,
@@ -1053,16 +1144,44 @@ finish_des:
 	if (context->cipherInfo == NULL) {
 	    crv = CKR_HOST_MEMORY;
 	    break;
 	}
 	context->update = (SFTKCipher) (isEncrypt ? AES_Encrypt : AES_Decrypt);
 	context->destroy = (SFTKDestroy) AES_DestroyContext;
 	break;
 
+    case CKM_NSS_CHACHA20_POLY1305:
+	if (pMechanism->ulParameterLen != sizeof(CK_NSS_AEAD_PARAMS)) {
+	    crv = CKR_MECHANISM_PARAM_INVALID;
+	    break;
+	}
+	context->multi = PR_FALSE;
+	if (key_type != CKK_NSS_CHACHA20) {
+	    crv = CKR_KEY_TYPE_INCONSISTENT;
+	    break;
+	}
+	att = sftk_FindAttribute(key,CKA_VALUE);
+	if (att == NULL) {
+	    crv = CKR_KEY_HANDLE_INVALID;
+	    break;
+	}
+	context->cipherInfo = sftk_ChaCha20Poly1305_CreateContext(
+		(unsigned char*) att->attrib.pValue, att->attrib.ulValueLen,
+		(CK_NSS_AEAD_PARAMS*) pMechanism->pParameter);
+	sftk_FreeAttribute(att);
+	if (context->cipherInfo == NULL) {
+	    crv = sftk_MapCryptError(PORT_GetError());
+	    break;
+	}
+	context->update = (SFTKCipher) (isEncrypt ? sftk_ChaCha20Poly1305_Encrypt :
+					sftk_ChaCha20Poly1305_Decrypt);
+	context->destroy = (SFTKDestroy) sftk_ChaCha20Poly1305_DestroyContext;
+	break;
+
     case CKM_NETSCAPE_AES_KEY_WRAP_PAD:
     	context->doPad = PR_TRUE;
 	/* fall thru */
     case CKM_NETSCAPE_AES_KEY_WRAP:
 	context->multi = PR_FALSE;
 	context->blockSize = 8;
 	if (key_type != CKK_AES) {
 	    crv = CKR_KEY_TYPE_INCONSISTENT;
@@ -3650,16 +3769,20 @@ nsc_SetupBulkKeyGen(CK_MECHANISM_TYPE me
     case CKM_CAMELLIA_KEY_GEN:
 	*key_type = CKK_CAMELLIA;
 	if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE;
 	break;
     case CKM_AES_KEY_GEN:
 	*key_type = CKK_AES;
 	if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE;
 	break;
+    case CKM_NSS_CHACHA20_KEY_GEN:
+	*key_type = CKK_NSS_CHACHA20;
+	if (*key_length == 0) crv = CKR_TEMPLATE_INCOMPLETE;
+	break;
     default:
 	PORT_Assert(0);
 	crv = CKR_MECHANISM_INVALID;
 	break;
     }
 
     return crv;
 }
@@ -3911,16 +4034,17 @@ CK_RV NSC_GenerateKey(CK_SESSION_HANDLE 
 	checkWeak = PR_TRUE;
         /* fall through */
     case CKM_RC2_KEY_GEN:
     case CKM_RC4_KEY_GEN:
     case CKM_GENERIC_SECRET_KEY_GEN:
     case CKM_SEED_KEY_GEN:
     case CKM_CAMELLIA_KEY_GEN:
     case CKM_AES_KEY_GEN:
+    case CKM_NSS_CHACHA20_KEY_GEN:
 #if NSS_SOFTOKEN_DOES_RC5
     case CKM_RC5_KEY_GEN:
 #endif
 	crv = nsc_SetupBulkKeyGen(pMechanism->mechanism,&key_type,&key_length);
 	break;
     case CKM_SSL3_PRE_MASTER_KEY_GEN:
 	key_type = CKK_GENERIC_SECRET;
 	key_length = 48;
--- a/lib/softoken/pkcs11i.h
+++ b/lib/softoken/pkcs11i.h
@@ -9,16 +9,17 @@
 
 #include "nssilock.h"
 #include "seccomon.h"
 #include "secoidt.h"
 #include "lowkeyti.h" 
 #include "pkcs11t.h"
 
 #include "sftkdbt.h" 
+#include "chacha20poly1305.h"
 #include "hasht.h"
 
 /* 
  * Configuration Defines 
  *
  * The following defines affect the space verse speed trade offs of
  * the PKCS #11 module. For the most part the current settings are optimized
  * for web servers, where we want faster speed and lower lock contention at
@@ -99,16 +100,17 @@ typedef struct SFTKSessionStr SFTKSessio
 typedef struct SFTKSlotStr SFTKSlot;
 typedef struct SFTKSessionContextStr SFTKSessionContext;
 typedef struct SFTKSearchResultsStr SFTKSearchResults;
 typedef struct SFTKHashVerifyInfoStr SFTKHashVerifyInfo;
 typedef struct SFTKHashSignInfoStr SFTKHashSignInfo;
 typedef struct SFTKOAEPEncryptInfoStr SFTKOAEPEncryptInfo;
 typedef struct SFTKOAEPDecryptInfoStr SFTKOAEPDecryptInfo;
 typedef struct SFTKSSLMACInfoStr SFTKSSLMACInfo;
+typedef struct SFTKChaCha20Poly1305InfoStr SFTKChaCha20Poly1305Info;
 typedef struct SFTKItemTemplateStr SFTKItemTemplate;
 
 /* define function pointer typdefs for pointer tables */
 typedef void (*SFTKDestroy)(void *, PRBool);
 typedef void (*SFTKBegin)(void *);
 typedef SECStatus (*SFTKCipher)(void *,void *,unsigned int *,unsigned int,
 					void *, unsigned int);
 typedef SECStatus (*SFTKVerify)(void *,void *,unsigned int,void *,unsigned int);
@@ -394,16 +396,26 @@ struct SFTKSSLMACInfoStr {
     SFTKHash		update;
     SFTKEnd		end;
     CK_ULONG		macSize;
     int			padSize;
     unsigned char	key[MAX_KEY_LEN];
     unsigned int	keySize;
 };
 
+/* SFTKChaCha20Poly1305Info saves the key, tag length, nonce,
+ * and additional data for a ChaCha20+Poly1305 AEAD operation. */
+struct SFTKChaCha20Poly1305InfoStr {
+    ChaCha20Poly1305Context freeblCtx;
+    unsigned char nonce[12];
+    unsigned char ad[16];
+    unsigned char *adOverflow;
+    unsigned int adLen;
+};
+
 /*
  * Template based on SECItems, suitable for passing as arrays
  */
 struct SFTKItemTemplateStr {
     CK_ATTRIBUTE_TYPE	type;
     SECItem		*item;
 };
 
--- a/lib/util/pkcs11n.h
+++ b/lib/util/pkcs11n.h
@@ -46,16 +46,18 @@
  */
 #define CKK_NSS (CKK_VENDOR_DEFINED|NSSCK_VENDOR_NSS)
 
 #define CKK_NSS_PKCS8              (CKK_NSS + 1)
 
 #define CKK_NSS_JPAKE_ROUND1       (CKK_NSS + 2)
 #define CKK_NSS_JPAKE_ROUND2       (CKK_NSS + 3)
 
+#define CKK_NSS_CHACHA20           (CKK_NSS + 4)
+
 /*
  * NSS-defined certificate types
  *
  */
 #define CKC_NSS (CKC_VENDOR_DEFINED|NSSCK_VENDOR_NSS)
 
 /* FAKE PKCS #11 defines */
 #define CKA_DIGEST            0x81000000L
@@ -213,16 +215,19 @@
 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256    (CKM_NSS + 22)
 #define CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256   (CKM_NSS + 23)
 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
 
 /* TLS extended master secret derivation */
 #define CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE    (CKM_NSS + 25)
 #define CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH (CKM_NSS + 26)
 
+#define CKM_NSS_CHACHA20_KEY_GEN                (CKM_NSS + 27)
+#define CKM_NSS_CHACHA20_POLY1305               (CKM_NSS + 28)
+
 /*
  * HISTORICAL:
  * Do not attempt to use these. They are only used by NETSCAPE's internal
  * PKCS #11 interface. Most of these are place holders for other mechanism
  * and will change in the future.
  */
 #define CKM_NETSCAPE_PBE_SHA1_DES_CBC           0x80000002UL
 #define CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC    0x80000003UL
@@ -280,16 +285,24 @@ typedef struct CK_NSS_JPAKEFinalParams {
  */
 typedef struct CK_NSS_MAC_CONSTANT_TIME_PARAMS {
     CK_MECHANISM_TYPE macAlg;   /* in */
     CK_ULONG ulBodyTotalLen;    /* in */
     CK_BYTE * pHeader;          /* in */
     CK_ULONG ulHeaderLen;       /* in */
 } CK_NSS_MAC_CONSTANT_TIME_PARAMS;
 
+typedef struct CK_NSS_AEAD_PARAMS {
+    CK_BYTE_PTR  pNonce;
+    CK_ULONG     ulNonceLen;
+    CK_BYTE_PTR  pAAD;
+    CK_ULONG     ulAADLen;
+    CK_ULONG     ulTagLen;
+} CK_NSS_AEAD_PARAMS;
+
 /*
  * NSS-defined return values
  *
  */
 #define CKR_NSS (CKM_VENDOR_DEFINED|NSSCK_VENDOR_NSS)
 
 #define CKR_NSS_CERTDB_FAILED      (CKR_NSS + 1)
 #define CKR_NSS_KEYDB_FAILED       (CKR_NSS + 2)
--- a/tests/cipher/cipher.txt
+++ b/tests/cipher/cipher.txt
@@ -26,16 +26,18 @@
 	0	camellia_ecb_-E	Camellia_ECB_Encrypt
 	0	camellia_ecb_-D	Camellia_ECB_Decrypt
 	0	camellia_cbc_-E	Camellia_CBC_Encrypt
 	0	camellia_cbc_-D	Camellia_CBC_Decrypt
 	0	seed_ecb_-E	SEED_ECB_Encrypt
 	0	seed_ecb_-D	SEED_ECB_Decrypt
 	0	seed_cbc_-E	SEED_CBC_Encrypt
 	0	seed_cbc_-D	SEED_CBC_Decrypt
+	0	chacha20_poly1305_-E ChaCha20_Poly1305_Encrypt
+	0	chacha20_poly1305_-D ChaCha20_Poly1305_Decrypt
 	0	rc2_ecb_-E	RC2_ECB_Encrypt
 	0	rc2_ecb_-D	RC2_ECB_Decrypt
 	0	rc2_cbc_-E	RC2_CBC_Encrypt
 	0	rc2_cbc_-D	RC2_CBC_Decrypt
 	0	rc4_-E		RC4_Encrypt
 	0	rc4_-D		RC4_Decrypt
 	0	rsa_-E		RSA_Encrypt
 	0	rsa_-D		RSA_Decrypt