Switch to BoringSSL.

This is a reland of r284079 which was reverted in r284248 for components build
issues. That, in turn, was a reland of r283813 which was reverted in r283845
because it broke WebRTC tests on Android. That, in turn, was a reland of
r283542 which was reverted in r283591 because it broke the WebView build.

This is a much larger change than its diff suggests. If it breaks
something, please revert first and ask questions later.

BUG=393317
[email protected], [email protected]

Review URL: https://codereview.chromium.org/401153002

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284729 0039d316-1c4b-4281-b951-d872f2087c98
diff --git a/DEPS b/DEPS
index 1a511e9..579cae5 100644
--- a/DEPS
+++ b/DEPS
@@ -55,7 +55,7 @@
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling WebRTC
   # and V8 without interference from each other.
-  "webrtc_revision": "6680",
+  "webrtc_revision": "6683",
   "jsoncpp_revision": "248",
   "nss_revision": "277057",
   # Three lines of non-changing comments so that
@@ -65,7 +65,7 @@
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling openssl
   # and whatever else without interference from each other.
-  "openssl_revision": "275836",
+  "openssl_revision": "284247",
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling ANGLE
   # and whatever else without interference from each other.
@@ -85,7 +85,7 @@
   # Three lines of non-changing comments so that
   # the commit queue can handle CLs rolling BoringSSL
   # and whatever else without interference from each other.
-  "boringssl_revision": "09020c2f08df11179b93e6548117806a4c0d0d45",
+  "boringssl_revision": "de620d9c87293fd0ed3b0a348550833565a0b61a",
 }
 
 deps = {
diff --git a/android_webview/buildbot/deps_whitelist.py b/android_webview/buildbot/deps_whitelist.py
index 69bb2d7..9a317f5 100755
--- a/android_webview/buildbot/deps_whitelist.py
+++ b/android_webview/buildbot/deps_whitelist.py
@@ -32,6 +32,7 @@
     # in the Android tree.
     self._compile_but_not_snapshot_dependencies = [
       'third_party/libaddressinput/src/cpp',
+      'third_party/boringssl/src',
     ]
 
     # Dependencies that need to be merged into the Android tree.
diff --git a/android_webview/native/webview_native.gyp b/android_webview/native/webview_native.gyp
index 56972c7..2e965e6 100644
--- a/android_webview/native/webview_native.gyp
+++ b/android_webview/native/webview_native.gyp
@@ -23,7 +23,7 @@
         '../../ui/gfx/gfx.gyp:gfx_geometry',
         '../../webkit/storage_browser.gyp:webkit_storage_browser',
         '../../webkit/storage_common.gyp:webkit_storage_common',
-        '../../third_party/openssl/openssl.gyp:openssl',
+        '../../third_party/boringssl/boringssl.gyp:boringssl',
         'android_webview_native_jni',
       ],
       'include_dirs': [
diff --git a/build/linux/system.gyp b/build/linux/system.gyp
index 59c31a6..d81b8d4 100644
--- a/build/linux/system.gyp
+++ b/build/linux/system.gyp
@@ -985,7 +985,7 @@
           'conditions': [
             ['use_openssl==1', {
               'dependencies': [
-                '../../third_party/openssl/openssl.gyp:openssl',
+                '../../third_party/boringssl/boringssl.gyp:boringssl',
               ],
             }],
             ['use_openssl==0', {
diff --git a/build/linux/unbundle/replace_gyp_files.py b/build/linux/unbundle/replace_gyp_files.py
index 28ab14f8..fc7646f 100755
--- a/build/linux/unbundle/replace_gyp_files.py
+++ b/build/linux/unbundle/replace_gyp_files.py
@@ -31,7 +31,7 @@
   'use_system_libxml': 'third_party/libxml/libxml.gyp',
   'use_system_libxnvctrl' : 'third_party/libXNVCtrl/libXNVCtrl.gyp',
   'use_system_libxslt': 'third_party/libxslt/libxslt.gyp',
-  'use_system_openssl': 'third_party/openssl/openssl.gyp',
+  'use_system_openssl': 'third_party/boringssl/boringssl.gyp',
   'use_system_opus': 'third_party/opus/opus.gyp',
   'use_system_re2': 'third_party/re2/re2.gyp',
   'use_system_snappy': 'third_party/snappy/snappy.gyp',
diff --git a/chrome/chrome_browser_ui.gypi b/chrome/chrome_browser_ui.gypi
index 341bbd6..5012b71 100644
--- a/chrome/chrome_browser_ui.gypi
+++ b/chrome/chrome_browser_ui.gypi
@@ -2781,7 +2781,7 @@
         ['OS=="android"', {
           'dependencies': [
             '../components/components.gyp:web_contents_delegate_android',
-            '../third_party/openssl/openssl.gyp:openssl',
+            '../third_party/boringssl/boringssl.gyp:boringssl',
             'chrome_browser_jni_headers',
           ],
           'dependencies!': [
diff --git a/chrome/chrome_common.gypi b/chrome/chrome_common.gypi
index 5368c96b..b24fd2a 100644
--- a/chrome/chrome_common.gypi
+++ b/chrome/chrome_common.gypi
@@ -653,7 +653,7 @@
         ],
         ['OS == "android"', {
             'dependencies': [
-              '../third_party/openssl/openssl.gyp:openssl',
+              '../third_party/boringssl/boringssl.gyp:boringssl',
             ],
             'sources!': [
               'common/net/x509_certificate_model.cc',
diff --git a/chrome/common/net/BUILD.gn b/chrome/common/net/BUILD.gn
index 30d46113..dd3502a 100644
--- a/chrome/common/net/BUILD.gn
+++ b/chrome/common/net/BUILD.gn
@@ -51,7 +51,7 @@
       "x509_certificate_model.cc",
       "x509_certificate_model_openssl.cc",
     ]
-    deps += [ "//third_party/openssl" ]
+    deps += [ "//third_party/boringssl" ]
   }
 
   if (use_openssl) {
diff --git a/content/child/webcrypto/openssl/aes_gcm_openssl.cc b/content/child/webcrypto/openssl/aes_gcm_openssl.cc
index de47dd80..0bc927ba 100644
--- a/content/child/webcrypto/openssl/aes_gcm_openssl.cc
+++ b/content/child/webcrypto/openssl/aes_gcm_openssl.cc
@@ -71,7 +71,8 @@
   crypto::ScopedOpenSSL<EVP_AEAD_CTX, EVP_AEAD_CTX_cleanup>::Type ctx_cleanup(
       &ctx);
 
-  ssize_t len;
+  size_t len;
+  int ok;
 
   if (mode == DECRYPT) {
     if (data.byte_length() < tag_length_bytes)
@@ -79,32 +80,34 @@
 
     buffer->resize(data.byte_length() - tag_length_bytes);
 
-    len = EVP_AEAD_CTX_open(&ctx,
-                            Uint8VectorStart(buffer),
-                            buffer->size(),
-                            iv.bytes(),
-                            iv.byte_length(),
-                            data.bytes(),
-                            data.byte_length(),
-                            additional_data.bytes(),
-                            additional_data.byte_length());
+    ok = EVP_AEAD_CTX_open(&ctx,
+                           Uint8VectorStart(buffer),
+                           &len,
+                           buffer->size(),
+                           iv.bytes(),
+                           iv.byte_length(),
+                           data.bytes(),
+                           data.byte_length(),
+                           additional_data.bytes(),
+                           additional_data.byte_length());
   } else {
     // No need to check for unsigned integer overflow here (seal fails if
     // the output buffer is too small).
     buffer->resize(data.byte_length() + tag_length_bytes);
 
-    len = EVP_AEAD_CTX_seal(&ctx,
-                            Uint8VectorStart(buffer),
-                            buffer->size(),
-                            iv.bytes(),
-                            iv.byte_length(),
-                            data.bytes(),
-                            data.byte_length(),
-                            additional_data.bytes(),
-                            additional_data.byte_length());
+    ok = EVP_AEAD_CTX_seal(&ctx,
+                           Uint8VectorStart(buffer),
+                           &len,
+                           buffer->size(),
+                           iv.bytes(),
+                           iv.byte_length(),
+                           data.bytes(),
+                           data.byte_length(),
+                           additional_data.bytes(),
+                           additional_data.byte_length());
   }
 
-  if (len < 0)
+  if (!ok)
     return Status::OperationError();
   buffer->resize(len);
   return Status::Success();
diff --git a/content/child/webcrypto/openssl/rsa_key_openssl.cc b/content/child/webcrypto/openssl/rsa_key_openssl.cc
index 8ba329a0..42098eba8 100644
--- a/content/child/webcrypto/openssl/rsa_key_openssl.cc
+++ b/content/child/webcrypto/openssl/rsa_key_openssl.cc
@@ -79,7 +79,7 @@
   std::vector<uint8_t> e(BN_num_bytes(rsa.get()->e));
   if (e.size() == 0)
     return Status::ErrorUnexpected();
-  if (static_cast<int>(e.size()) != BN_bn2bin(rsa.get()->e, &e[0]))
+  if (e.size() != BN_bn2bin(rsa.get()->e, &e[0]))
     return Status::ErrorUnexpected();
 
   *key_algorithm = blink::WebCryptoKeyAlgorithm::createRsaHashed(
diff --git a/content/content_child.gypi b/content/content_child.gypi
index 560e4a6..6080d0e 100644
--- a/content/content_child.gypi
+++ b/content/content_child.gypi
@@ -334,7 +334,7 @@
         '<@(webcrypto_openssl_sources)',
       ],
       'dependencies': [
-        '../third_party/openssl/openssl.gyp:openssl',
+        '../third_party/boringssl/boringssl.gyp:boringssl',
       ],
     }, {
       'sources': [
diff --git a/content/zygote/zygote_main_linux.cc b/content/zygote/zygote_main_linux.cc
index 60f08b6..5e3746b 100644
--- a/content/zygote/zygote_main_linux.cc
+++ b/content/zygote/zygote_main_linux.cc
@@ -47,6 +47,10 @@
 #include <sys/prctl.h>
 #endif
 
+#if defined(USE_OPENSSL)
+#include <openssl/rand.h>
+#endif
+
 #if defined(ENABLE_WEBRTC)
 #include "third_party/libjingle/overrides/init_webrtc.h"
 #endif
@@ -312,9 +316,10 @@
   // successful initialization of NSS which tries to load extra library files.
   crypto::LoadNSSLibraries();
 #elif defined(USE_OPENSSL)
-  // OpenSSL is intentionally not supported in the sandboxed processes, see
-  // http://crbug.com/99163. If that ever changes we'll likely need to init
-  // OpenSSL here (at least, load the library and error strings).
+  // Read a random byte in order to cause BoringSSL to open a file descriptor
+  // for /dev/urandom.
+  uint8_t scratch;
+  RAND_bytes(&scratch, 1);
 #else
   // It's possible that another hypothetical crypto stack would not require
   // pre-sandbox init, but more likely this is just a build configuration error.
diff --git a/crypto/BUILD.gn b/crypto/BUILD.gn
index 30784208..bd7f06d 100644
--- a/crypto/BUILD.gn
+++ b/crypto/BUILD.gn
@@ -242,7 +242,7 @@
 # on the current SSL library should just depend on this.
 group("platform") {
   if (use_openssl) {
-    deps = [ "//third_party/openssl" ]
+    deps = [ "//third_party/boringssl" ]
   } else {
     deps = [ "//net/third_party/nss/ssl:libssl" ]
     if (is_linux) {
diff --git a/crypto/crypto.gyp b/crypto/crypto.gyp
index 0c472ff..42f3cad 100644
--- a/crypto/crypto.gyp
+++ b/crypto/crypto.gyp
@@ -100,7 +100,7 @@
         }],
         [ 'use_openssl==1', {
             'dependencies': [
-              '../third_party/openssl/openssl.gyp:openssl',
+              '../third_party/boringssl/boringssl.gyp:boringssl',
             ],
             # TODO(joth): Use a glob to match exclude patterns once the
             #             OpenSSL file set is complete.
@@ -209,7 +209,7 @@
         }],
         [ 'use_openssl==1', {
           'dependencies': [
-            '../third_party/openssl/openssl.gyp:openssl',
+            '../third_party/boringssl/boringssl.gyp:boringssl',
           ],
           'sources!': [
             'nss_util_unittest.cc',
diff --git a/crypto/crypto_nacl.gyp b/crypto/crypto_nacl.gyp
index 6ec5e83..4451610 100644
--- a/crypto/crypto_nacl.gyp
+++ b/crypto/crypto_nacl.gyp
@@ -22,7 +22,7 @@
         'build_pnacl_newlib': 1,
       },
       'dependencies': [
-        '../third_party/openssl/openssl_nacl.gyp:openssl_nacl',
+        '../third_party/boringssl/boringssl_nacl.gyp:boringssl_nacl',
         '../native_client/tools.gyp:prep_toolchain',
         '../native_client_sdk/native_client_sdk_untrusted.gyp:nacl_io_untrusted',
       ],
diff --git a/crypto/encryptor_openssl.cc b/crypto/encryptor_openssl.cc
index 0bf96b7..0504adb 100644
--- a/crypto/encryptor_openssl.cc
+++ b/crypto/encryptor_openssl.cc
@@ -19,7 +19,6 @@
 const EVP_CIPHER* GetCipherForKey(SymmetricKey* key) {
   switch (key->key().length()) {
     case 16: return EVP_aes_128_cbc();
-    case 24: return EVP_aes_192_cbc();
     case 32: return EVP_aes_256_cbc();
     default: return NULL;
   }
@@ -100,8 +99,8 @@
   DCHECK(cipher);  // Already handled in Init();
 
   const std::string& key = key_->key();
-  DCHECK_EQ(EVP_CIPHER_iv_length(cipher), static_cast<int>(iv_.length()));
-  DCHECK_EQ(EVP_CIPHER_key_length(cipher), static_cast<int>(key.length()));
+  DCHECK_EQ(EVP_CIPHER_iv_length(cipher), iv_.length());
+  DCHECK_EQ(EVP_CIPHER_key_length(cipher), key.length());
 
   ScopedCipherCTX ctx;
   if (!EVP_CipherInit_ex(ctx.get(), cipher, NULL,
diff --git a/crypto/openssl_bio_string_unittest.cc b/crypto/openssl_bio_string_unittest.cc
index 2467215..9dfa0e70 100644
--- a/crypto/openssl_bio_string_unittest.cc
+++ b/crypto/openssl_bio_string_unittest.cc
@@ -23,24 +23,17 @@
     EXPECT_EQ(static_cast<int>(expected1.size()),
               BIO_printf(bio.get(), "a %s\nb %i\n", "one", 2));
     EXPECT_EQ(expected1, s);
-    EXPECT_EQ(static_cast<int>(expected1.size()), BIO_tell(bio.get()));
 
     EXPECT_EQ(1, BIO_flush(bio.get()));
-    EXPECT_EQ(-1, BIO_seek(bio.get(), 0));
     EXPECT_EQ(expected1, s);
 
     EXPECT_EQ(static_cast<int>(expected2.size()),
               BIO_write(bio.get(), expected2.data(), expected2.size()));
     EXPECT_EQ(expected1 + expected2, s);
-    EXPECT_EQ(static_cast<int>(expected1.size() + expected2.size()),
-              BIO_tell(bio.get()));
 
     EXPECT_EQ(static_cast<int>(expected3.size()),
               BIO_puts(bio.get(), expected3.c_str()));
     EXPECT_EQ(expected1 + expected2 + expected3, s);
-    EXPECT_EQ(static_cast<int>(expected1.size() + expected2.size() +
-                               expected3.size()),
-              BIO_tell(bio.get()));
   }
   EXPECT_EQ(expected1 + expected2 + expected3, s);
 }
diff --git a/crypto/openssl_util.cc b/crypto/openssl_util.cc
index 34af810c..94bf246a 100644
--- a/crypto/openssl_util.cc
+++ b/crypto/openssl_util.cc
@@ -6,6 +6,7 @@
 
 #include <openssl/err.h>
 #include <openssl/ssl.h>
+#include <openssl/cpu.h>
 
 #include "base/logging.h"
 #include "base/memory/scoped_vector.h"
@@ -22,8 +23,9 @@
 
 namespace {
 
-unsigned long CurrentThreadId() {
-  return static_cast<unsigned long>(base::PlatformThread::CurrentId());
+void CurrentThreadId(CRYPTO_THREADID* id) {
+  CRYPTO_THREADID_set_numeric(
+      id, static_cast<unsigned long>(base::PlatformThread::CurrentId()));
 }
 
 // Singleton for initializing and cleaning up the OpenSSL library.
@@ -53,7 +55,7 @@
     for (int i = 0; i < num_locks; ++i)
       locks_.push_back(new base::Lock());
     CRYPTO_set_locking_callback(LockingCallback);
-    CRYPTO_set_id_callback(CurrentThreadId);
+    CRYPTO_THREADID_set_callback(CurrentThreadId);
 
 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
     const bool has_neon =
diff --git a/crypto/rsa_private_key_openssl.cc b/crypto/rsa_private_key_openssl.cc
index e3cf04c..8dcde61 100644
--- a/crypto/rsa_private_key_openssl.cc
+++ b/crypto/rsa_private_key_openssl.cc
@@ -4,6 +4,8 @@
 
 #include "crypto/rsa_private_key.h"
 
+#include <openssl/bio.h>
+#include <openssl/bn.h>
 #include <openssl/evp.h>
 #include <openssl/pkcs12.h>
 #include <openssl/rsa.h>
diff --git a/crypto/scoped_openssl_types.h b/crypto/scoped_openssl_types.h
index a949233..19953a2b 100644
--- a/crypto/scoped_openssl_types.h
+++ b/crypto/scoped_openssl_types.h
@@ -5,6 +5,7 @@
 #ifndef CRYPTO_SCOPED_OPENSSL_TYPES_H_
 #define CRYPTO_SCOPED_OPENSSL_TYPES_H_
 
+#include <openssl/bio.h>
 #include <openssl/bn.h>
 #include <openssl/dsa.h>
 #include <openssl/ec.h>
diff --git a/crypto/signature_verifier_openssl.cc b/crypto/signature_verifier_openssl.cc
index 155a2cf3..a855120e 100644
--- a/crypto/signature_verifier_openssl.cc
+++ b/crypto/signature_verifier_openssl.cc
@@ -26,7 +26,7 @@
     case SignatureVerifier::SHA256:
       return EVP_sha256();
   }
-  return EVP_md_null();
+  return NULL;
 }
 
 }  // namespace
@@ -80,8 +80,11 @@
                                          const uint8* public_key_info,
                                          int public_key_info_len) {
   OpenSSLErrStackTracer err_tracer(FROM_HERE);
-  const EVP_MD* digest = ToOpenSSLDigest(hash_alg);
+  const EVP_MD* const digest = ToOpenSSLDigest(hash_alg);
   DCHECK(digest);
+  if (!digest) {
+    return false;
+  }
 
   EVP_PKEY_CTX* pkey_ctx;
   if (!CommonInit(digest, signature, signature_len, public_key_info,
@@ -92,8 +95,12 @@
   int rv = EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING);
   if (rv != 1)
     return false;
-  rv = EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx,
-                                    ToOpenSSLDigest(mask_hash_alg));
+  const EVP_MD* const mgf_digest = ToOpenSSLDigest(mask_hash_alg);
+  DCHECK(mgf_digest);
+  if (!mgf_digest) {
+    return false;
+  }
+  rv = EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, mgf_digest);
   if (rv != 1)
     return false;
   rv = EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, salt_len);
diff --git a/google_apis/google_apis.gyp b/google_apis/google_apis.gyp
index ecc56097..73b2d11 100644
--- a/google_apis/google_apis.gyp
+++ b/google_apis/google_apis.gyp
@@ -45,7 +45,7 @@
         }],
         ['OS=="android"', {
           'dependencies': [
-            '../third_party/openssl/openssl.gyp:openssl',
+            '../third_party/boringssl/boringssl.gyp:boringssl',
           ],
           'sources/': [
             ['exclude', 'cup/client_update_protocol_nss\.cc$'],
diff --git a/net/BUILD.gn b/net/BUILD.gn
index fd00467..07828b95 100644
--- a/net/BUILD.gn
+++ b/net/BUILD.gn
@@ -523,10 +523,6 @@
 
     if (!is_android_webview_build) {
       deps += [ ":net_jni_headers" ]
-
-      # The net/android/keystore_openssl.cc source file needs to access an
-      # OpenSSL-internal header.
-      include_dirs = [ "//third_party/openssl" ]
     }
   }
 
@@ -924,7 +920,7 @@
       ":epoll_server",
       ":net",
       "//base",
-      "//third_party/openssl",
+      "//third_party/boringssl",
     ]
   }
 
@@ -943,7 +939,7 @@
       ":test_support",
       "//testing/gtest",
       "//testing/gmock",
-      "//third_party/openssl",
+      "//third_party/boringssl",
     ]
   }
 
@@ -994,7 +990,7 @@
       "//base",
       "//base/third_party/dynamic_annotations",
       "//crypto",
-      "//third_party/openssl",
+      "//third_party/boringssl",
       "//url",
     ]
   }
@@ -1005,7 +1001,7 @@
       ":quic_base",
       ":net",
       "//base",
-      "//third_party/openssl",
+      "//third_party/boringssl",
     ]
   }
 }
@@ -1334,7 +1330,7 @@
     ":quic_tools",
     ":net",
     "//base",
-    "//third_party/openssl",
+    "//third_party/boringssl",
   ]
 }
 
diff --git a/net/android/keystore_openssl.cc b/net/android/keystore_openssl.cc
index dbb3b1c..09ecaf3c 100644
--- a/net/android/keystore_openssl.cc
+++ b/net/android/keystore_openssl.cc
@@ -6,16 +6,10 @@
 
 #include <jni.h>
 #include <openssl/bn.h>
-// This include is required to get the ECDSA_METHOD structure definition
-// which isn't currently part of the OpenSSL official ABI. This should
-// not be a concern for Chromium which always links against its own
-// version of the library on Android.
-#include <openssl/crypto/ecdsa/ecs_locl.h>
-// And this one is needed for the EC_GROUP definition.
-#include <openssl/crypto/ec/ec_lcl.h>
 #include <openssl/dsa.h>
 #include <openssl/ec.h>
 #include <openssl/engine.h>
+#include <openssl/err.h>
 #include <openssl/evp.h>
 #include <openssl/rsa.h>
 
@@ -60,41 +54,10 @@
 // fields point to static methods used to implement the corresponding
 // RSA operation using platform Android APIs.
 //
-// However, the platform APIs require a jobject JNI reference to work.
-// It must be stored in the RSA instance, or made accessible when the
-// custom RSA methods are called. This is done by using RSA_set_app_data()
-// and RSA_get_app_data().
-//
-// One can thus _directly_ create a new EVP_PKEY that uses a custom RSA
-// object with the following:
-//
-//    RSA* rsa = RSA_new()
-//    RSA_set_method(&custom_rsa_method);
-//    RSA_set_app_data(rsa, jni_private_key);
-//
-//    EVP_PKEY* pkey = EVP_PKEY_new();
-//    EVP_PKEY_assign_RSA(pkey, rsa);
-//
-// Note that because EVP_PKEY_assign_RSA() is used, instead of
-// EVP_PKEY_set1_RSA(), the new EVP_PKEY now owns the RSA object, and
-// will destroy it when it is itself destroyed.
-//
-// Unfortunately, such objects cannot be used with RSA_size(), which
-// totally ignores the RSA_METHOD pointers. Instead, it is necessary
-// to manually setup the modulus field (n) in the RSA object, with a
-// value that matches the wrapped PrivateKey object. See GetRsaPkeyWrapper
-// for full details.
-//
-// Similarly, custom DSA_METHOD and ECDSA_METHOD are defined by this source
-// file, and appropriate field setups are performed to ensure that
-// DSA_size() and ECDSA_size() work properly with the wrapper EVP_PKEY.
-//
-// Note that there is no need to define an OpenSSL ENGINE here. These
-// are objects that can be used to expose custom methods (i.e. either
-// RSA_METHOD, DSA_METHOD, ECDSA_METHOD, and a large number of other ones
-// for types not related to this source file), and make them used by
-// default for a lot of operations. Very fortunately, this is not needed
-// here, which saves a lot of complexity.
+// However, the platform APIs require a jobject JNI reference to work. It must
+// be stored in the RSA instance, or made accessible when the custom RSA
+// methods are called. This is done by storing it in a |KeyExData| structure
+// that's referenced by the key using |EX_DATA|.
 
 using base::android::ScopedJavaGlobalRef;
 using base::android::ScopedJavaLocalRef;
@@ -104,45 +67,127 @@
 
 namespace {
 
-typedef crypto::ScopedOpenSSL<EC_GROUP, EC_GROUP_free>::Type ScopedEC_GROUP;
+extern const RSA_METHOD android_rsa_method;
+extern const ECDSA_METHOD android_ecdsa_method;
 
-// Custom RSA_METHOD that uses the platform APIs.
-// Note that for now, only signing through RSA_sign() is really supported.
-// all other method pointers are either stubs returning errors, or no-ops.
-// See <openssl/rsa.h> for exact declaration of RSA_METHOD.
-
-struct RsaAppData {
+// KeyExData contains the data that is contained in the EX_DATA of the RSA, DSA
+// and ECDSA objects that are created to wrap Android system keys.
+struct KeyExData {
+  // private_key contains a reference to a Java, private-key object.
   jobject private_key;
+  // legacy_rsa, if not NULL, points to an RSA* in the system's OpenSSL (which
+  // might not be ABI compatible with Chromium).
   AndroidRSA* legacy_rsa;
+  // cached_size contains the "size" of the key. This is the size of the
+  // modulus (in bytes) for RSA, or the group order size for (EC)DSA. This
+  // avoids calling into Java to calculate the size.
+  size_t cached_size;
 };
 
-int RsaMethodPubEnc(int flen,
-                    const unsigned char* from,
-                    unsigned char* to,
-                    RSA* rsa,
-                    int padding) {
-  NOTIMPLEMENTED();
-  RSAerr(RSA_F_RSA_PUBLIC_ENCRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
-  return -1;
+// ExDataDup is called when one of the RSA, DSA or EC_KEY objects is
+// duplicated. We don't support this and it should never happen.
+int ExDataDup(CRYPTO_EX_DATA* to,
+              const CRYPTO_EX_DATA* from,
+              void** from_d,
+              int index,
+              long argl,
+              void* argp) {
+  CHECK(false);
+  return 0;
 }
 
-int RsaMethodPubDec(int flen,
-                    const unsigned char* from,
-                    unsigned char* to,
-                    RSA* rsa,
-                    int padding) {
-  NOTIMPLEMENTED();
-  RSAerr(RSA_F_RSA_PUBLIC_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
-  return -1;
+// ExDataFree is called when one of the RSA, DSA or EC_KEY object is freed.
+void ExDataFree(void* parent,
+                void* ptr,
+                CRYPTO_EX_DATA* ad,
+                int index,
+                long argl,
+                void* argp) {
+  // Ensure the global JNI reference created with this wrapper is
+  // properly destroyed with it.
+  KeyExData *ex_data = reinterpret_cast<KeyExData*>(ptr);
+  if (ex_data != NULL) {
+    ReleaseKey(ex_data->private_key);
+    delete ex_data;
+  }
 }
 
-// See RSA_eay_private_encrypt in
-// third_party/openssl/openssl/crypto/rsa/rsa_eay.c for the default
-// implementation of this function.
-int RsaMethodPrivEnc(int flen,
-                     const unsigned char *from,
-                     unsigned char *to,
-                     RSA *rsa,
+// BoringSSLEngine is a BoringSSL ENGINE that implements RSA, DSA and ECDSA by
+// forwarding the requested operations to the Java libraries.
+class BoringSSLEngine {
+ public:
+  BoringSSLEngine()
+      : rsa_index_(RSA_get_ex_new_index(0 /* argl */,
+                                        NULL /* argp */,
+                                        NULL /* new_func */,
+                                        ExDataDup,
+                                        ExDataFree)),
+        ec_key_index_(EC_KEY_get_ex_new_index(0 /* argl */,
+                                              NULL /* argp */,
+                                              NULL /* new_func */,
+                                              ExDataDup,
+                                              ExDataFree)),
+        engine_(ENGINE_new()) {
+    ENGINE_set_RSA_method(
+        engine_, &android_rsa_method, sizeof(android_rsa_method));
+    ENGINE_set_ECDSA_method(
+        engine_, &android_ecdsa_method, sizeof(android_ecdsa_method));
+  }
+
+  int rsa_ex_index() const { return rsa_index_; }
+  int ec_key_ex_index() const { return ec_key_index_; }
+
+  const ENGINE* engine() const { return engine_; }
+
+ private:
+  const int rsa_index_;
+  const int ec_key_index_;
+  ENGINE* const engine_;
+};
+
+base::LazyInstance<BoringSSLEngine>::Leaky global_boringssl_engine =
+    LAZY_INSTANCE_INITIALIZER;
+
+
+// VectorBignumSize returns the number of bytes needed to represent the bignum
+// given in |v|, i.e. the length of |v| less any leading zero bytes.
+size_t VectorBignumSize(const std::vector<uint8>& v) {
+  size_t size = v.size();
+  // Ignore any leading zero bytes.
+  for (size_t i = 0; i < v.size() && v[i] == 0; i++) {
+    size--;
+  }
+  return size;
+}
+
+KeyExData* RsaGetExData(const RSA* rsa) {
+  return reinterpret_cast<KeyExData*>(
+      RSA_get_ex_data(rsa, global_boringssl_engine.Get().rsa_ex_index()));
+}
+
+size_t RsaMethodSize(const RSA *rsa) {
+  const KeyExData *ex_data = RsaGetExData(rsa);
+  return ex_data->cached_size;
+}
+
+int RsaMethodEncrypt(RSA* rsa,
+                     size_t* out_len,
+                     uint8_t* out,
+                     size_t max_out,
+                     const uint8_t* in,
+                     size_t in_len,
+                     int padding) {
+  NOTIMPLEMENTED();
+  OPENSSL_PUT_ERROR(RSA, encrypt, RSA_R_UNKNOWN_ALGORITHM_TYPE);
+  return 0;
+}
+
+int RsaMethodSignRaw(RSA* rsa,
+                     size_t* out_len,
+                     uint8_t* out,
+                     size_t max_out,
+                     const uint8_t* in,
+                     size_t in_len,
                      int padding) {
   DCHECK_EQ(RSA_PKCS1_PADDING, padding);
   if (padding != RSA_PKCS1_PADDING) {
@@ -153,22 +198,22 @@
     // the same Android version as the "NONEwithRSA"
     // java.security.Signature algorithm, so the same version checks
     // for GetRsaLegacyKey should work.
-    RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
-    return -1;
+    OPENSSL_PUT_ERROR(RSA, sign_raw, RSA_R_UNKNOWN_PADDING_TYPE);
+    return 0;
   }
 
   // Retrieve private key JNI reference.
-  RsaAppData* app_data = static_cast<RsaAppData*>(RSA_get_app_data(rsa));
-  if (!app_data || !app_data->private_key) {
+  const KeyExData *ex_data = RsaGetExData(rsa);
+  if (!ex_data || !ex_data->private_key) {
     LOG(WARNING) << "Null JNI reference passed to RsaMethodPrivEnc!";
-    RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
-    return -1;
+    OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
+    return 0;
   }
 
   // Pre-4.2 legacy codepath.
-  if (app_data->legacy_rsa) {
-    int ret = app_data->legacy_rsa->meth->rsa_priv_enc(
-        flen, from, to, app_data->legacy_rsa, ANDROID_RSA_PKCS1_PADDING);
+  if (ex_data->legacy_rsa) {
+    int ret = ex_data->legacy_rsa->meth->rsa_priv_enc(
+        in_len, in, out, ex_data->legacy_rsa, ANDROID_RSA_PKCS1_PADDING);
     if (ret < 0) {
       LOG(WARNING) << "Could not sign message in RsaMethodPrivEnc!";
       // System OpenSSL will use a separate error queue, so it is still
@@ -178,126 +223,92 @@
       // if there were some way to convince Java to do it. (Without going
       // through Java, it's difficult to get a handle on a system OpenSSL
       // function; dlopen loads a second copy.)
-      RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
-      return -1;
+      OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
+      return 0;
     }
-    return ret;
+    *out_len = ret;
+    return 1;
   }
 
-  base::StringPiece from_piece(reinterpret_cast<const char*>(from), flen);
+  base::StringPiece from_piece(reinterpret_cast<const char*>(in), in_len);
   std::vector<uint8> result;
   // For RSA keys, this function behaves as RSA_private_encrypt with
   // PKCS#1 padding.
-  if (!RawSignDigestWithPrivateKey(app_data->private_key,
-                                   from_piece, &result)) {
+  if (!RawSignDigestWithPrivateKey(ex_data->private_key, from_piece, &result)) {
     LOG(WARNING) << "Could not sign message in RsaMethodPrivEnc!";
-    RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
-    return -1;
+    OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
+    return 0;
   }
 
   size_t expected_size = static_cast<size_t>(RSA_size(rsa));
   if (result.size() > expected_size) {
     LOG(ERROR) << "RSA Signature size mismatch, actual: "
                <<  result.size() << ", expected <= " << expected_size;
-    RSAerr(RSA_F_RSA_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR);
-    return -1;
+    OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
+    return 0;
+  }
+
+  if (max_out < expected_size) {
+    OPENSSL_PUT_ERROR(RSA, sign_raw, RSA_R_DATA_TOO_LARGE);
+    return 0;
   }
 
   // Copy result to OpenSSL-provided buffer. RawSignDigestWithPrivateKey
   // should pad with leading 0s, but if it doesn't, pad the result.
   size_t zero_pad = expected_size - result.size();
-  memset(to, 0, zero_pad);
-  memcpy(to + zero_pad, &result[0], result.size());
+  memset(out, 0, zero_pad);
+  memcpy(out + zero_pad, &result[0], result.size());
+  *out_len = expected_size;
 
-  return expected_size;
+  return 1;
 }
 
-int RsaMethodPrivDec(int flen,
-                     const unsigned char* from,
-                     unsigned char* to,
-                     RSA* rsa,
+int RsaMethodDecrypt(RSA* rsa,
+                     size_t* out_len,
+                     uint8_t* out,
+                     size_t max_out,
+                     const uint8_t* in,
+                     size_t in_len,
                      int padding) {
   NOTIMPLEMENTED();
-  RSAerr(RSA_F_RSA_PRIVATE_DECRYPT, RSA_R_RSA_OPERATIONS_NOT_SUPPORTED);
-  return -1;
-}
-
-int RsaMethodInit(RSA* rsa) {
+  OPENSSL_PUT_ERROR(RSA, decrypt, RSA_R_UNKNOWN_ALGORITHM_TYPE);
   return 0;
 }
 
-int RsaMethodFinish(RSA* rsa) {
-  // Ensure the global JNI reference created with this wrapper is
-  // properly destroyed with it.
-  RsaAppData* app_data = static_cast<RsaAppData*>(RSA_get_app_data(rsa));
-  if (app_data != NULL) {
-    RSA_set_app_data(rsa, NULL);
-    ReleaseKey(app_data->private_key);
-    delete app_data;
-  }
-  // Actual return value is ignored by OpenSSL. There are no docs
-  // explaining what this is supposed to be.
+int RsaMethodVerifyRaw(RSA* rsa,
+                       size_t* out_len,
+                       uint8_t* out,
+                       size_t max_out,
+                       const uint8_t* in,
+                       size_t in_len,
+                       int padding) {
+  NOTIMPLEMENTED();
+  OPENSSL_PUT_ERROR(RSA, verify_raw, RSA_R_UNKNOWN_ALGORITHM_TYPE);
   return 0;
 }
 
 const RSA_METHOD android_rsa_method = {
-  /* .name = */ "Android signing-only RSA method",
-  /* .rsa_pub_enc = */ RsaMethodPubEnc,
-  /* .rsa_pub_dec = */ RsaMethodPubDec,
-  /* .rsa_priv_enc = */ RsaMethodPrivEnc,
-  /* .rsa_priv_dec = */ RsaMethodPrivDec,
-  /* .rsa_mod_exp = */ NULL,
-  /* .bn_mod_exp = */ NULL,
-  /* .init = */ RsaMethodInit,
-  /* .finish = */ RsaMethodFinish,
-  // This flag is necessary to tell OpenSSL to avoid checking the content
-  // (i.e. internal fields) of the private key. Otherwise, it will complain
-  // it's not valid for the certificate.
-  /* .flags = */ RSA_METHOD_FLAG_NO_CHECK,
-  /* .app_data = */ NULL,
-  /* .rsa_sign = */ NULL,
-  /* .rsa_verify = */ NULL,
-  /* .rsa_keygen = */ NULL,
+    {
+     0 /* references */,
+     1 /* is_static */
+    } /* common */,
+    NULL /* app_data */,
+
+    NULL /* init */,
+    NULL /* finish */,
+    RsaMethodSize,
+    NULL /* sign */,
+    NULL /* verify */,
+    RsaMethodEncrypt,
+    RsaMethodSignRaw,
+    RsaMethodDecrypt,
+    RsaMethodVerifyRaw,
+    NULL /* mod_exp */,
+    NULL /* bn_mod_exp */,
+    RSA_FLAG_OPAQUE,
+    NULL /* keygen */,
 };
 
-// Copy the contents of an encoded big integer into an existing BIGNUM.
-// This function modifies |*num| in-place.
-// |new_bytes| is the byte encoding of the new value.
-// |num| points to the BIGNUM which will be assigned with the new value.
-// Returns true on success, false otherwise. On failure, |*num| is
-// not modified.
-bool CopyBigNumFromBytes(const std::vector<uint8>& new_bytes,
-                         BIGNUM* num) {
-  BIGNUM* ret = BN_bin2bn(
-      reinterpret_cast<const unsigned char*>(&new_bytes[0]),
-      static_cast<int>(new_bytes.size()),
-      num);
-  return (ret != NULL);
-}
-
-// Decode the contents of an encoded big integer and either create a new
-// BIGNUM object (if |*num_ptr| is NULL on input) or copy it (if
-// |*num_ptr| is not NULL).
-// |new_bytes| is the byte encoding of the new value.
-// |num_ptr| is the address of a BIGNUM pointer. |*num_ptr| can be NULL.
-// Returns true on success, false otherwise. On failure, |*num_ptr| is
-// not modified. On success, |*num_ptr| will always be non-NULL and
-// point to a valid BIGNUM object.
-bool SwapBigNumPtrFromBytes(const std::vector<uint8>& new_bytes,
-                            BIGNUM** num_ptr) {
-  BIGNUM* old_num = *num_ptr;
-  BIGNUM* new_num = BN_bin2bn(
-      reinterpret_cast<const unsigned char*>(&new_bytes[0]),
-      static_cast<int>(new_bytes.size()),
-      old_num);
-  if (new_num == NULL)
-    return false;
-
-  if (old_num == NULL)
-    *num_ptr = new_num;
-  return true;
-}
-
 // Setup an EVP_PKEY to wrap an existing platform RSA PrivateKey object.
 // |private_key| is the JNI reference (local or global) to the object.
 // |legacy_rsa|, if non-NULL, is a pointer to the system OpenSSL RSA object
@@ -311,24 +322,8 @@
 bool GetRsaPkeyWrapper(jobject private_key,
                        AndroidRSA* legacy_rsa,
                        EVP_PKEY* pkey) {
-  crypto::ScopedRSA rsa(RSA_new());
-  RSA_set_method(rsa.get(), &android_rsa_method);
-
-  // HACK: RSA_size() doesn't work with custom RSA_METHODs. To ensure that
-  // it will return the right value, set the 'n' field of the RSA object
-  // to match the private key's modulus.
-  //
-  // TODO(davidben): After switching to BoringSSL, consider making RSA_size call
-  // into an RSA_METHOD hook.
-  std::vector<uint8> modulus;
-  if (!GetRSAKeyModulus(private_key, &modulus)) {
-    LOG(ERROR) << "Failed to get private key modulus";
-    return false;
-  }
-  if (!SwapBigNumPtrFromBytes(modulus, &rsa.get()->n)) {
-    LOG(ERROR) << "Failed to decode private key modulus";
-    return false;
-  }
+  crypto::ScopedRSA rsa(
+      RSA_new_method(global_boringssl_engine.Get().engine()));
 
   ScopedJavaGlobalRef<jobject> global_key;
   global_key.Reset(NULL, private_key);
@@ -336,10 +331,19 @@
     LOG(ERROR) << "Could not create global JNI reference";
     return false;
   }
-  RsaAppData* app_data = new RsaAppData();
-  app_data->private_key = global_key.Release();
-  app_data->legacy_rsa = legacy_rsa;
-  RSA_set_app_data(rsa.get(), app_data);
+
+  std::vector<uint8> modulus;
+  if (!GetRSAKeyModulus(private_key, &modulus)) {
+    LOG(ERROR) << "Failed to get private key modulus";
+    return false;
+  }
+
+  KeyExData* ex_data = new KeyExData;
+  ex_data->private_key = global_key.Release();
+  ex_data->legacy_rsa = legacy_rsa;
+  ex_data->cached_size = VectorBignumSize(modulus);
+  RSA_set_ex_data(
+      rsa.get(), global_boringssl_engine.Get().rsa_ex_index(), ex_data);
   EVP_PKEY_assign_RSA(pkey, rsa.release());
   return true;
 }
@@ -398,7 +402,7 @@
     if (sys_rsa->engine) {
       // |private_key| may not have an engine if the PrivateKey did not come
       // from the key store, such as in unit tests.
-      if (!strcmp(sys_rsa->engine->id, "keystore")) {
+      if (strcmp(sys_rsa->engine->id, "keystore") == 0) {
         LeakEngine(private_key);
       } else {
         NOTREACHED();
@@ -431,266 +435,67 @@
   return pkey;
 }
 
-// Custom DSA_METHOD that uses the platform APIs.
-// Note that for now, only signing through DSA_sign() is really supported.
-// all other method pointers are either stubs returning errors, or no-ops.
-// See <openssl/dsa.h> for exact declaration of DSA_METHOD.
-//
-// Note: There is no DSA_set_app_data() and DSA_get_app_data() functions,
-//       but RSA_set_app_data() is defined as a simple macro that calls
-//       RSA_set_ex_data() with a hard-coded index of 0, so this code
-//       does the same thing here.
-
-DSA_SIG* DsaMethodDoSign(const unsigned char* dgst,
-                         int dlen,
-                         DSA* dsa) {
-  // Extract the JNI reference to the PrivateKey object.
-  jobject private_key = reinterpret_cast<jobject>(DSA_get_ex_data(dsa, 0));
-  if (private_key == NULL)
-    return NULL;
-
-  // Sign the message with it, calling platform APIs.
-  std::vector<uint8> signature;
-  if (!RawSignDigestWithPrivateKey(
-          private_key,
-          base::StringPiece(
-              reinterpret_cast<const char*>(dgst),
-              static_cast<size_t>(dlen)),
-          &signature)) {
-    return NULL;
-  }
-
-  // Note: With DSA, the actual signature might be smaller than DSA_size().
-  size_t max_expected_size = static_cast<size_t>(DSA_size(dsa));
-  if (signature.size() > max_expected_size) {
-    LOG(ERROR) << "DSA Signature size mismatch, actual: "
-               << signature.size() << ", expected <= "
-               << max_expected_size;
-    return NULL;
-  }
-
-  // Convert the signature into a DSA_SIG object.
-  const unsigned char* sigbuf =
-      reinterpret_cast<const unsigned char*>(&signature[0]);
-  int siglen = static_cast<size_t>(signature.size());
-  DSA_SIG* dsa_sig = d2i_DSA_SIG(NULL, &sigbuf, siglen);
-  return dsa_sig;
-}
-
-int DsaMethodSignSetup(DSA* dsa,
-                       BN_CTX* ctx_in,
-                       BIGNUM** kinvp,
-                       BIGNUM** rp) {
-  NOTIMPLEMENTED();
-  DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_INVALID_DIGEST_TYPE);
-  return -1;
-}
-
-int DsaMethodDoVerify(const unsigned char* dgst,
-                      int dgst_len,
-                      DSA_SIG* sig,
-                      DSA* dsa) {
-  NOTIMPLEMENTED();
-  DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_INVALID_DIGEST_TYPE);
-  return -1;
-}
-
-int DsaMethodFinish(DSA* dsa) {
-  // Free the global JNI reference that was created with this
-  // wrapper key.
-  jobject key = reinterpret_cast<jobject>(DSA_get_ex_data(dsa,0));
-  if (key != NULL) {
-    DSA_set_ex_data(dsa, 0, NULL);
-    ReleaseKey(key);
-  }
-  // Actual return value is ignored by OpenSSL. There are no docs
-  // explaining what this is supposed to be.
-  return 0;
-}
-
-const DSA_METHOD android_dsa_method = {
-  /* .name = */ "Android signing-only DSA method",
-  /* .dsa_do_sign = */ DsaMethodDoSign,
-  /* .dsa_sign_setup = */ DsaMethodSignSetup,
-  /* .dsa_do_verify = */ DsaMethodDoVerify,
-  /* .dsa_mod_exp = */ NULL,
-  /* .bn_mod_exp = */ NULL,
-  /* .init = */ NULL,  // nothing to do here.
-  /* .finish = */ DsaMethodFinish,
-  /* .flags = */ 0,
-  /* .app_data = */ NULL,
-  /* .dsa_paramgem = */ NULL,
-  /* .dsa_keygen = */ NULL
-};
-
-// Setup an EVP_PKEY to wrap an existing DSA platform PrivateKey object.
-// |private_key| is a JNI reference (local or global) to the object.
-// |pkey| is the EVP_PKEY to setup as a wrapper.
-// Returns true on success, false otherwise.
-// On success, this creates a global JNI reference to the same object
-// that will be owned by and destroyed with the EVP_PKEY.
-bool GetDsaPkeyWrapper(jobject private_key, EVP_PKEY* pkey) {
-  crypto::ScopedDSA dsa(DSA_new());
-  DSA_set_method(dsa.get(), &android_dsa_method);
-
-  // DSA_size() doesn't work with custom DSA_METHODs. To ensure it
-  // returns the right value, set the 'q' field in the DSA object to
-  // match the parameter from the platform key.
-  std::vector<uint8> q;
-  if (!GetDSAKeyParamQ(private_key, &q)) {
-    LOG(ERROR) << "Can't extract Q parameter from DSA private key";
-    return false;
-  }
-  if (!SwapBigNumPtrFromBytes(q, &dsa.get()->q)) {
-    LOG(ERROR) << "Can't decode Q parameter from DSA private key";
-    return false;
-  }
-
-  ScopedJavaGlobalRef<jobject> global_key;
-  global_key.Reset(NULL, private_key);
-  if (global_key.is_null()) {
-    LOG(ERROR) << "Could not create global JNI reference";
-    return false;
-  }
-  DSA_set_ex_data(dsa.get(), 0, global_key.Release());
-  EVP_PKEY_assign_DSA(pkey, dsa.release());
-  return true;
-}
-
 // Custom ECDSA_METHOD that uses the platform APIs.
 // Note that for now, only signing through ECDSA_sign() is really supported.
 // all other method pointers are either stubs returning errors, or no-ops.
-//
-// Note: The ECDSA_METHOD structure doesn't have init/finish
-//       methods. As such, the only way to to ensure the global
-//       JNI reference is properly released when the EVP_PKEY is
-//       destroyed is to use a custom EX_DATA type.
 
-// Used to ensure that the global JNI reference associated with a custom
-// EC_KEY + ECDSA_METHOD wrapper is released when its EX_DATA is destroyed
-// (this function is called when EVP_PKEY_free() is called on the wrapper).
-void ExDataFree(void* parent,
-                void* ptr,
-                CRYPTO_EX_DATA* ad,
-                int idx,
-                long argl,
-                void* argp) {
-  jobject private_key = reinterpret_cast<jobject>(ptr);
-  if (private_key == NULL)
-    return;
-
-  CRYPTO_set_ex_data(ad, idx, NULL);
-  ReleaseKey(private_key);
+jobject EcKeyGetKey(const EC_KEY* ec_key) {
+  KeyExData* ex_data = reinterpret_cast<KeyExData*>(EC_KEY_get_ex_data(
+      ec_key, global_boringssl_engine.Get().ec_key_ex_index()));
+  return ex_data->private_key;
 }
 
-int ExDataDup(CRYPTO_EX_DATA* to,
-              CRYPTO_EX_DATA* from,
-              void* from_d,
-              int idx,
-              long argl,
-              void* argp) {
-  // This callback shall never be called with the current OpenSSL
-  // implementation (the library only ever duplicates EX_DATA items
-  // for SSL and BIO objects). But provide this to catch regressions
-  // in the future.
-  CHECK(false) << "ExDataDup was called for ECDSA custom key !?";
-  // Return value is currently ignored by OpenSSL.
-  return 0;
+size_t EcdsaMethodGroupOrderSize(const EC_KEY* ec_key) {
+  KeyExData* ex_data = reinterpret_cast<KeyExData*>(EC_KEY_get_ex_data(
+      ec_key, global_boringssl_engine.Get().ec_key_ex_index()));
+  return ex_data->cached_size;
 }
 
-class EcdsaExDataIndex {
-public:
-  int ex_data_index() { return ex_data_index_; }
-
-  EcdsaExDataIndex() {
-    ex_data_index_ = ECDSA_get_ex_new_index(0,           // argl
-                                            NULL,        // argp
-                                            NULL,        // new_func
-                                            ExDataDup,   // dup_func
-                                            ExDataFree); // free_func
-  }
-
-private:
-  int ex_data_index_;
-};
-
-// Returns the index of the custom EX_DATA used to store the JNI reference.
-int EcdsaGetExDataIndex(void) {
-  // Use a LazyInstance to perform thread-safe lazy initialization.
-  // Use a leaky one, since OpenSSL doesn't provide a way to release
-  // allocated EX_DATA indices.
-  static base::LazyInstance<EcdsaExDataIndex>::Leaky s_instance =
-      LAZY_INSTANCE_INITIALIZER;
-  return s_instance.Get().ex_data_index();
-}
-
-ECDSA_SIG* EcdsaMethodDoSign(const unsigned char* dgst,
-                             int dgst_len,
-                             const BIGNUM* inv,
-                             const BIGNUM* rp,
-                             EC_KEY* eckey) {
+int EcdsaMethodSign(const uint8_t* digest,
+                    size_t digest_len,
+                    uint8_t* sig,
+                    unsigned int* sig_len,
+                    EC_KEY* ec_key) {
   // Retrieve private key JNI reference.
-  jobject private_key = reinterpret_cast<jobject>(
-      ECDSA_get_ex_data(eckey, EcdsaGetExDataIndex()));
+  jobject private_key = EcKeyGetKey(ec_key);
   if (!private_key) {
-    LOG(WARNING) << "Null JNI reference passed to EcdsaMethodDoSign!";
-    return NULL;
+    LOG(WARNING) << "Null JNI reference passed to EcdsaMethodSign!";
+    return 0;
   }
   // Sign message with it through JNI.
   std::vector<uint8> signature;
-  base::StringPiece digest(
-      reinterpret_cast<const char*>(dgst),
-      static_cast<size_t>(dgst_len));
-  if (!RawSignDigestWithPrivateKey(
-          private_key, digest, &signature)) {
-    LOG(WARNING) << "Could not sign message in EcdsaMethodDoSign!";
-    return NULL;
+  base::StringPiece digest_sp(reinterpret_cast<const char*>(digest),
+                              digest_len);
+  if (!RawSignDigestWithPrivateKey(private_key, digest_sp, &signature)) {
+    LOG(WARNING) << "Could not sign message in EcdsaMethodSign!";
+    return 0;
   }
 
   // Note: With ECDSA, the actual signature may be smaller than
   // ECDSA_size().
-  size_t max_expected_size = static_cast<size_t>(ECDSA_size(eckey));
+  size_t max_expected_size = ECDSA_size(ec_key);
   if (signature.size() > max_expected_size) {
     LOG(ERROR) << "ECDSA Signature size mismatch, actual: "
                <<  signature.size() << ", expected <= "
                << max_expected_size;
-    return NULL;
+    return 0;
   }
 
-  // Convert signature to ECDSA_SIG object
-  const unsigned char* sigbuf =
-      reinterpret_cast<const unsigned char*>(&signature[0]);
-  long siglen = static_cast<long>(signature.size());
-  return d2i_ECDSA_SIG(NULL, &sigbuf, siglen);
+  memcpy(sig, &signature[0], signature.size());
+  *sig_len = signature.size();
+  return 1;
 }
 
-int EcdsaMethodSignSetup(EC_KEY* eckey,
-                         BN_CTX* ctx,
-                         BIGNUM** kinv,
-                         BIGNUM** r) {
+int EcdsaMethodVerify(const uint8_t* digest,
+                      size_t digest_len,
+                      const uint8_t* sig,
+                      size_t sig_len,
+                      EC_KEY* ec_key) {
   NOTIMPLEMENTED();
-  ECDSAerr(ECDSA_F_ECDSA_SIGN_SETUP, ECDSA_R_ERR_EC_LIB);
-  return -1;
+  OPENSSL_PUT_ERROR(ECDSA, ECDSA_do_verify, ECDSA_R_NOT_IMPLEMENTED);
+  return 0;
 }
 
-int EcdsaMethodDoVerify(const unsigned char* dgst,
-                        int dgst_len,
-                        const ECDSA_SIG* sig,
-                        EC_KEY* eckey) {
-  NOTIMPLEMENTED();
-  ECDSAerr(ECDSA_F_ECDSA_DO_VERIFY, ECDSA_R_ERR_EC_LIB);
-  return -1;
-}
-
-const ECDSA_METHOD android_ecdsa_method = {
-  /* .name = */ "Android signing-only ECDSA method",
-  /* .ecdsa_do_sign = */ EcdsaMethodDoSign,
-  /* .ecdsa_sign_setup = */ EcdsaMethodSignSetup,
-  /* .ecdsa_do_verify = */ EcdsaMethodDoVerify,
-  /* .flags = */ 0,
-  /* .app_data = */ NULL,
-};
-
 // Setup an EVP_PKEY to wrap an existing platform PrivateKey object.
 // |private_key| is the JNI reference (local or global) to the object.
 // |pkey| is the EVP_PKEY to setup as a wrapper.
@@ -699,26 +504,8 @@
 // is owned by and destroyed with the EVP_PKEY. I.e. the caller shall
 // always free |private_key| after the call.
 bool GetEcdsaPkeyWrapper(jobject private_key, EVP_PKEY* pkey) {
-  crypto::ScopedEC_KEY eckey(EC_KEY_new());
-  ECDSA_set_method(eckey.get(), &android_ecdsa_method);
-
-  // To ensure that ECDSA_size() works properly, craft a custom EC_GROUP
-  // that has the same order than the private key.
-  std::vector<uint8> order;
-  if (!GetECKeyOrder(private_key, &order)) {
-    LOG(ERROR) << "Can't extract order parameter from EC private key";
-    return false;
-  }
-  ScopedEC_GROUP group(EC_GROUP_new(EC_GFp_nist_method()));
-  if (!group.get()) {
-    LOG(ERROR) << "Can't create new EC_GROUP";
-    return false;
-  }
-  if (!CopyBigNumFromBytes(order, &group.get()->order)) {
-    LOG(ERROR) << "Can't decode order from PrivateKey";
-    return false;
-  }
-  EC_KEY_set_group(eckey.get(), group.release());
+  crypto::ScopedEC_KEY ec_key(
+      EC_KEY_new_method(global_boringssl_engine.Get().engine()));
 
   ScopedJavaGlobalRef<jobject> global_key;
   global_key.Reset(NULL, private_key);
@@ -726,14 +513,40 @@
     LOG(ERROR) << "Can't create global JNI reference";
     return false;
   }
-  ECDSA_set_ex_data(eckey.get(),
-                    EcdsaGetExDataIndex(),
-                    global_key.Release());
 
-  EVP_PKEY_assign_EC_KEY(pkey, eckey.release());
+  std::vector<uint8> order;
+  if (!GetECKeyOrder(private_key, &order)) {
+    LOG(ERROR) << "Can't extract order parameter from EC private key";
+    return false;
+  }
+
+  KeyExData* ex_data = new KeyExData;
+  ex_data->private_key = global_key.Release();
+  ex_data->legacy_rsa = NULL;
+  ex_data->cached_size = VectorBignumSize(order);
+
+  EC_KEY_set_ex_data(
+      ec_key.get(), global_boringssl_engine.Get().ec_key_ex_index(), ex_data);
+
+  EVP_PKEY_assign_EC_KEY(pkey, ec_key.release());
   return true;
 }
 
+const ECDSA_METHOD android_ecdsa_method = {
+    {
+     0 /* references */,
+     1 /* is_static */
+    } /* common */,
+    NULL /* app_data */,
+
+    NULL /* init */,
+    NULL /* finish */,
+    EcdsaMethodGroupOrderSize,
+    EcdsaMethodSign,
+    EcdsaMethodVerify,
+    ECDSA_FLAG_OPAQUE,
+};
+
 }  // namespace
 
 EVP_PKEY* GetOpenSSLPrivateKeyWrapper(jobject private_key) {
@@ -765,10 +578,6 @@
         }
       }
       break;
-    case PRIVATE_KEY_TYPE_DSA:
-      if (!GetDsaPkeyWrapper(private_key, pkey.get()))
-        return NULL;
-      break;
     case PRIVATE_KEY_TYPE_ECDSA:
       if (!GetEcdsaPkeyWrapper(private_key, pkey.get()))
         return NULL;
diff --git a/net/android/keystore_unittest.cc b/net/android/keystore_unittest.cc
index 076693f8..4fe38ab 100644
--- a/net/android/keystore_unittest.cc
+++ b/net/android/keystore_unittest.cc
@@ -205,54 +205,6 @@
   return GetPKCS8PrivateKeyJava(PRIVATE_KEY_TYPE_RSA, key);
 }
 
-const char kTestDsaKeyFile[] = "android-test-key-dsa.pem";
-const char kTestDsaPublicKeyFile[] = "android-test-key-dsa-public.pem";
-
-// The DSA test hash must be 20 bytes exactly.
-const char kTestDsaHash[] = "0123456789ABCDEFGHIJ";
-
-// Retrieve a JNI local ref for our test DSA key.
-ScopedJava GetDSATestKeyJava() {
-  std::string key;
-  if (!ImportPrivateKeyFileAsPkcs8(kTestDsaKeyFile, &key))
-    return ScopedJava();
-  return GetPKCS8PrivateKeyJava(PRIVATE_KEY_TYPE_DSA, key);
-}
-
-// Call this function to verify that one message signed with our
-// test DSA private key is correct. Since DSA signing introduces
-// random elements in the signature, it is not possible to compare
-// signature bits directly. However, one can use the public key
-// to do the check.
-bool VerifyTestDSASignature(const base::StringPiece& message,
-                            const base::StringPiece& signature) {
-  crypto::ScopedEVP_PKEY pkey(ImportPublicKeyFile(kTestDsaPublicKeyFile));
-  if (!pkey.get())
-    return false;
-
-  crypto::ScopedDSA pub_key(EVP_PKEY_get1_DSA(pkey.get()));
-  if (!pub_key.get()) {
-    LOG(ERROR) << "Could not get DSA public key: "
-               << GetOpenSSLErrorString();
-    return false;
-  }
-
-  const unsigned char* digest =
-      reinterpret_cast<const unsigned char*>(message.data());
-  int digest_len = static_cast<int>(message.size());
-  const unsigned char* sigbuf =
-      reinterpret_cast<const unsigned char*>(signature.data());
-  int siglen = static_cast<int>(signature.size());
-
-  int ret = DSA_verify(
-      0, digest, digest_len, sigbuf, siglen, pub_key.get());
-  if (ret != 1) {
-    LOG(ERROR) << "DSA_verify() failed: " << GetOpenSSLErrorString();
-    return false;
-  }
-  return true;
-}
-
 const char kTestEcdsaKeyFile[] = "android-test-key-ecdsa.pem";
 const char kTestEcdsaPublicKeyFile[] = "android-test-key-ecdsa-public.pem";
 
@@ -268,7 +220,7 @@
 }
 
 // Call this function to verify that one message signed with our
-// test DSA private key is correct. Since DSA signing introduces
+// test ECDSA private key is correct. Since ECDSA signing introduces
 // random elements in the signature, it is not possible to compare
 // signature bits directly. However, one can use the public key
 // to do the check.
@@ -338,28 +290,6 @@
       signature_size = static_cast<size_t>(p_len);
       break;
     }
-    case EVP_PKEY_DSA:
-    {
-      crypto::ScopedDSA dsa(EVP_PKEY_get1_DSA(openssl_key));
-      if (!dsa.get()) {
-        LOG(ERROR) << "Could not get DSA from EVP_PKEY: "
-                   << GetOpenSSLErrorString();
-        return false;
-      }
-      // Note, the actual signature can be smaller than DSA_size()
-      max_signature_size = static_cast<size_t>(DSA_size(dsa.get()));
-      unsigned char* p = OpenSSLWriteInto(&signature,
-                                          max_signature_size);
-      unsigned int p_len = 0;
-      // Note: first parameter is ignored by function.
-      int ret = DSA_sign(0, digest, digest_len, p, &p_len, dsa.get());
-      if (ret != 1) {
-        LOG(ERROR) << "DSA_sign() failed: " << GetOpenSSLErrorString();
-        return false;
-      }
-      signature_size = static_cast<size_t>(p_len);
-      break;
-    }
     case EVP_PKEY_EC:
     {
       crypto::ScopedEC_KEY ecdsa(EVP_PKEY_get1_EC_KEY(openssl_key));
@@ -519,41 +449,6 @@
   ASSERT_EQ(0, BN_cmp(bn.get(), rsa.get()->n));
 }
 
-TEST(AndroidKeyStore,GetDSAKeyParamQ) {
-  crypto::OpenSSLErrStackTracer err_trace(FROM_HERE);
-  InitEnv();
-
-  // Load the test DSA key.
-  crypto::ScopedEVP_PKEY pkey(ImportPrivateKeyFile(kTestDsaKeyFile));
-  ASSERT_TRUE(pkey.get());
-
-  // Convert it to encoded PKCS#8 bytes.
-  std::string pkcs8_data;
-  ASSERT_TRUE(GetPrivateKeyPkcs8Bytes(pkey, &pkcs8_data));
-
-  // Create platform PrivateKey object from it.
-  ScopedJava key_java = GetPKCS8PrivateKeyJava(PRIVATE_KEY_TYPE_DSA,
-                                                pkcs8_data);
-  ASSERT_FALSE(key_java.is_null());
-
-  // Retrieve the corresponding Q parameter through JNI
-  std::vector<uint8> q_java;
-  ASSERT_TRUE(GetDSAKeyParamQ(key_java.obj(), &q_java));
-
-  // Create an OpenSSL BIGNUM from it.
-  crypto::ScopedBIGNUM bn(
-      BN_bin2bn(reinterpret_cast<const unsigned char*>(&q_java[0]),
-                static_cast<int>(q_java.size()),
-                NULL));
-  ASSERT_TRUE(bn.get());
-
-  // Compare it to the one in the RSA key, they must be identical.
-  crypto::ScopedDSA dsa(EVP_PKEY_get1_DSA(pkey.get()));
-  ASSERT_TRUE(dsa.get()) << GetOpenSSLErrorString();
-
-  ASSERT_EQ(0, BN_cmp(bn.get(), dsa.get()->q));
-}
-
 TEST(AndroidKeyStore,GetPrivateKeyTypeRSA) {
   crypto::OpenSSLErrStackTracer err_trace(FROM_HERE);
 
@@ -616,56 +511,6 @@
       CompareSignatureWithOpenSSL(message, signature, openssl_key.get()));
 }
 
-TEST(AndroidKeyStore,GetPrivateKeyTypeDSA) {
-  crypto::OpenSSLErrStackTracer err_trace(FROM_HERE);
-
-  ScopedJava dsa_key = GetDSATestKeyJava();
-  ASSERT_FALSE(dsa_key.is_null());
-  EXPECT_EQ(PRIVATE_KEY_TYPE_DSA,
-            GetPrivateKeyType(dsa_key.obj()));
-}
-
-TEST(AndroidKeyStore,SignWithPrivateKeyDSA) {
-  ScopedJava dsa_key = GetDSATestKeyJava();
-  ASSERT_FALSE(dsa_key.is_null());
-
-  crypto::ScopedEVP_PKEY openssl_key(ImportPrivateKeyFile(kTestDsaKeyFile));
-  ASSERT_TRUE(openssl_key.get());
-
-  std::string message = kTestDsaHash;
-  ASSERT_EQ(20U, message.size());
-
-  std::string signature;
-  DoKeySigning(dsa_key.obj(), openssl_key.get(), message, &signature);
-  ASSERT_TRUE(VerifyTestDSASignature(message, signature));
-}
-
-TEST(AndroidKeyStore,SignWithWrapperKeyDSA) {
-  crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
-
-  ScopedJava dsa_key = GetDSATestKeyJava();
-  ASSERT_FALSE(dsa_key.is_null());
-
-  crypto::ScopedEVP_PKEY wrapper_key(
-      GetOpenSSLPrivateKeyWrapper(dsa_key.obj()));
-  ASSERT_TRUE(wrapper_key.get());
-
-  crypto::ScopedEVP_PKEY openssl_key(ImportPrivateKeyFile(kTestDsaKeyFile));
-  ASSERT_TRUE(openssl_key.get());
-
-  // Check that DSA_size() works correctly on the wrapper.
-  EXPECT_EQ(EVP_PKEY_size(openssl_key.get()),
-            EVP_PKEY_size(wrapper_key.get()));
-
-  std::string message = kTestDsaHash;
-  std::string signature;
-  DoKeySigningWithWrapper(wrapper_key.get(),
-                          openssl_key.get(),
-                          message,
-                          &signature);
-  ASSERT_TRUE(VerifyTestDSASignature(message, signature));
-}
-
 TEST(AndroidKeyStore,GetPrivateKeyTypeECDSA) {
   crypto::OpenSSLErrStackTracer err_trace(FROM_HERE);
 
diff --git a/net/cert/cert_verify_proc_openssl.cc b/net/cert/cert_verify_proc_openssl.cc
index 0122fac..7643240 100644
--- a/net/cert/cert_verify_proc_openssl.cc
+++ b/net/cert/cert_verify_proc_openssl.cc
@@ -101,7 +101,7 @@
   STACK_OF(X509)* chain = X509_STORE_CTX_get_chain(store_ctx);
   X509* verified_cert = NULL;
   std::vector<X509*> verified_chain;
-  for (int i = 0; i < sk_X509_num(chain); ++i) {
+  for (size_t i = 0; i < sk_X509_num(chain); ++i) {
     X509* cert = sk_X509_value(chain, i);
     if (i == 0) {
       verified_cert = cert;
@@ -111,7 +111,7 @@
 
     // Only check the algorithm status for certificates that are not in the
     // trust store.
-    if (i < store_ctx->last_untrusted) {
+    if (i < static_cast<size_t>(store_ctx->last_untrusted)) {
       int sig_alg = OBJ_obj2nid(cert->sig_alg->algorithm);
       if (sig_alg == NID_md2WithRSAEncryption) {
         verify_result->has_md2 = true;
@@ -151,7 +151,7 @@
 void AppendPublicKeyHashes(X509_STORE_CTX* store_ctx,
                            HashValueVector* hashes) {
   STACK_OF(X509)* chain = X509_STORE_CTX_get_chain(store_ctx);
-  for (int i = 0; i < sk_X509_num(chain); ++i) {
+  for (size_t i = 0; i < sk_X509_num(chain); ++i) {
     X509* cert = sk_X509_value(chain, i);
 
     std::string der_data;
diff --git a/net/cert/x509_certificate_openssl.cc b/net/cert/x509_certificate_openssl.cc
index 005423ba..504f3ae 100644
--- a/net/cert/x509_certificate_openssl.cc
+++ b/net/cert/x509_certificate_openssl.cc
@@ -5,10 +5,10 @@
 #include "net/cert/x509_certificate.h"
 
 #include <openssl/asn1.h>
+#include <openssl/bytestring.h>
 #include <openssl/crypto.h>
 #include <openssl/obj_mac.h>
 #include <openssl/pem.h>
-#include <openssl/pkcs7.h>
 #include <openssl/sha.h>
 #include <openssl/ssl.h>
 #include <openssl/x509v3.h>
@@ -40,27 +40,20 @@
     const char* data, int length,
     X509Certificate::OSCertHandles* handles) {
   crypto::EnsureOpenSSLInit();
-  const unsigned char* der_data = reinterpret_cast<const unsigned char*>(data);
-  crypto::ScopedOpenSSL<PKCS7, PKCS7_free>::Type pkcs7_cert(
-      d2i_PKCS7(NULL, &der_data, length));
-  if (!pkcs7_cert.get())
-    return;
+  crypto::OpenSSLErrStackTracer err_cleaner(FROM_HERE);
 
-  STACK_OF(X509)* certs = NULL;
-  int nid = OBJ_obj2nid(pkcs7_cert.get()->type);
-  if (nid == NID_pkcs7_signed) {
-    certs = pkcs7_cert.get()->d.sign->cert;
-  } else if (nid == NID_pkcs7_signedAndEnveloped) {
-    certs = pkcs7_cert.get()->d.signed_and_enveloped->cert;
-  }
+  CBS der_data;
+  CBS_init(&der_data, reinterpret_cast<const uint8_t*>(data), length);
+  STACK_OF(X509)* certs = sk_X509_new_null();
 
-  if (certs) {
-    for (int i = 0; i < sk_X509_num(certs); ++i) {
+  if (PKCS7_get_certificates(certs, &der_data)) {
+    for (size_t i = 0; i < sk_X509_num(certs); ++i) {
       X509* x509_cert =
           X509Certificate::DupOSCertHandle(sk_X509_value(certs, i));
       handles->push_back(x509_cert);
     }
   }
+  sk_X509_pop_free(certs, X509_free);
 }
 
 void ParsePrincipalValues(X509_NAME* name,
@@ -114,7 +107,7 @@
   if (!alt_names.get())
     return;
 
-  for (int i = 0; i < sk_GENERAL_NAME_num(alt_names.get()); ++i) {
+  for (size_t i = 0; i < sk_GENERAL_NAME_num(alt_names.get()); ++i) {
     const GENERAL_NAME* name = sk_GENERAL_NAME_value(alt_names.get(), i);
     if (name->type == GEN_DNS && dns_names) {
       const unsigned char* dns_name = ASN1_STRING_data(name->d.dNSName);
@@ -509,7 +502,7 @@
 
   // and 'cert_names'.
   for (size_t n = 0; n < cert_names.size(); ++n) {
-    for (int m = 0; m < sk_X509_NAME_num(issuer_names.get()); ++m) {
+    for (size_t m = 0; m < sk_X509_NAME_num(issuer_names.get()); ++m) {
       X509_NAME* issuer = sk_X509_NAME_value(issuer_names.get(), m);
       if (X509_NAME_cmp(issuer, cert_names[n]) == 0) {
         return true;
diff --git a/net/http/des.cc b/net/http/des.cc
index 79240cf..daac8a4 100644
--- a/net/http/des.cc
+++ b/net/http/des.cc
@@ -93,10 +93,10 @@
   crypto::EnsureOpenSSLInit();
 
   DES_key_schedule ks;
-  DES_set_key_unchecked(
-      reinterpret_cast<const_DES_cblock*>(const_cast<uint8*>(key)), &ks);
+  DES_set_key(
+      reinterpret_cast<const DES_cblock*>(key), &ks);
 
-  DES_ecb_encrypt(reinterpret_cast<const_DES_cblock*>(const_cast<uint8*>(src)),
+  DES_ecb_encrypt(reinterpret_cast<const DES_cblock*>(src),
                   reinterpret_cast<DES_cblock*>(hash), &ks, DES_ENCRYPT);
 }
 
diff --git a/net/net.gyp b/net/net.gyp
index bda1845..3b38400 100644
--- a/net/net.gyp
+++ b/net/net.gyp
@@ -255,7 +255,7 @@
               'third_party/mozilla_security_manager/nsPKCS12Blob.h',
             ],
             'dependencies': [
-              '../third_party/openssl/openssl.gyp:openssl',
+              '../third_party/boringssl/boringssl.gyp:boringssl',
             ],
           },
           {  # else !use_openssl: remove the unneeded files
@@ -466,7 +466,7 @@
         }],
         [ 'OS == "android"', {
             'dependencies': [
-              '../third_party/openssl/openssl.gyp:openssl',
+              '../third_party/boringssl/boringssl.gyp:boringssl',
               'net_jni_headers',
             ],
             'sources!': [
@@ -475,11 +475,6 @@
               'cert/cert_verify_proc_openssl.cc',
               'cert/test_root_certs_openssl.cc',
             ],
-            # The net/android/keystore_openssl.cc source file needs to
-            # access an OpenSSL-internal header.
-            'include_dirs': [
-              '../third_party/openssl',
-            ],
           },
         ],
         [ 'use_icu_alternatives_on_android == 1', {
@@ -594,7 +589,7 @@
         [ 'use_openssl == 1', {
           # Avoid compiling/linking with the system library.
           'dependencies': [
-            '../third_party/openssl/openssl.gyp:openssl',
+            '../third_party/boringssl/boringssl.gyp:boringssl',
           ],
         }, {  # use_openssl == 0
           'conditions': [
@@ -797,7 +792,7 @@
         }],
         [ 'OS == "android"', {
             'dependencies': [
-              '../third_party/openssl/openssl.gyp:openssl',
+              '../third_party/boringssl/boringssl.gyp:boringssl',
             ],
             'sources!': [
               'dns/dns_config_service_posix_unittest.cc',
@@ -979,7 +974,7 @@
           'conditions': [
             ['use_openssl==1', {
               'dependencies': [
-                '../third_party/openssl/openssl.gyp:openssl',
+                '../third_party/boringssl/boringssl.gyp:boringssl',
               ],
             }, {
               'dependencies': [
@@ -1382,7 +1377,7 @@
           ],
           'dependencies': [
             '../base/base.gyp:base',
-            '../third_party/openssl/openssl.gyp:openssl',
+            '../third_party/boringssl/boringssl.gyp:boringssl',
             'balsa',
             'epoll_server',
             'net',
@@ -1427,7 +1422,7 @@
           'dependencies': [
               '../testing/gtest.gyp:gtest',
               '../testing/gmock.gyp:gmock',
-              '../third_party/openssl/openssl.gyp:openssl',
+              '../third_party/boringssl/boringssl.gyp:boringssl',
               'flip_in_mem_edsm_server_base',
               'net',
               'net_test_support',
diff --git a/net/net_nacl.gyp b/net/net_nacl.gyp
index 33a63d0..7ca48ed 100644
--- a/net/net_nacl.gyp
+++ b/net/net_nacl.gyp
@@ -25,7 +25,7 @@
         '../crypto/crypto_nacl.gyp:crypto_nacl',
         '../native_client/tools.gyp:prep_toolchain',
         '../native_client_sdk/native_client_sdk_untrusted.gyp:nacl_io_untrusted',
-        '../third_party/openssl/openssl_nacl.gyp:openssl_nacl',
+        '../third_party/boringssl/boringssl_nacl.gyp:boringssl_nacl',
         '../url/url_nacl.gyp:url_nacl',
         'net.gyp:net_derived_sources',
         'net.gyp:net_resources',
diff --git a/net/quic/crypto/aead_base_decrypter_openssl.cc b/net/quic/crypto/aead_base_decrypter_openssl.cc
index 2190bf69..fad0fe1 100644
--- a/net/quic/crypto/aead_base_decrypter_openssl.cc
+++ b/net/quic/crypto/aead_base_decrypter_openssl.cc
@@ -86,21 +86,18 @@
     return false;
   }
 
-  ssize_t len = EVP_AEAD_CTX_open(
-      ctx_.get(), output, ciphertext.size(),
+  if (!EVP_AEAD_CTX_open(
+      ctx_.get(), output, output_length, ciphertext.size(),
       reinterpret_cast<const uint8_t*>(nonce.data()), nonce.size(),
       reinterpret_cast<const uint8_t*>(ciphertext.data()), ciphertext.size(),
       reinterpret_cast<const uint8_t*>(associated_data.data()),
-      associated_data.size());
-
-  if (len < 0) {
+      associated_data.size())) {
     // Because QuicFramer does trial decryption, decryption errors are expected
     // when encryption level changes. So we don't log decryption errors.
     ClearOpenSslErrors();
     return false;
   }
 
-  *output_length = len;
   return true;
 }
 
diff --git a/net/quic/crypto/aead_base_encrypter_openssl.cc b/net/quic/crypto/aead_base_encrypter_openssl.cc
index 9f053ab..7f2d3c6 100644
--- a/net/quic/crypto/aead_base_encrypter_openssl.cc
+++ b/net/quic/crypto/aead_base_encrypter_openssl.cc
@@ -81,14 +81,18 @@
     return false;
   }
 
-  ssize_t len = EVP_AEAD_CTX_seal(
-      ctx_.get(), output, plaintext.size() + auth_tag_size_,
-      reinterpret_cast<const uint8_t*>(nonce.data()), nonce.size(),
-      reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size(),
-      reinterpret_cast<const uint8_t*>(associated_data.data()),
-      associated_data.size());
-
-  if (len < 0) {
+  size_t len;
+  if (!EVP_AEAD_CTX_seal(
+          ctx_.get(),
+          output,
+          &len,
+          plaintext.size() + auth_tag_size_,
+          reinterpret_cast<const uint8_t*>(nonce.data()),
+          nonce.size(),
+          reinterpret_cast<const uint8_t*>(plaintext.data()),
+          plaintext.size(),
+          reinterpret_cast<const uint8_t*>(associated_data.data()),
+          associated_data.size())) {
     DLogOpenSslErrors();
     return false;
   }
diff --git a/net/socket/openssl_ssl_util.cc b/net/socket/openssl_ssl_util.cc
index a11436c..231f77c 100644
--- a/net/socket/openssl_ssl_util.cc
+++ b/net/socket/openssl_ssl_util.cc
@@ -4,6 +4,8 @@
 
 #include "net/socket/openssl_ssl_util.h"
 
+#include <errno.h>
+
 #include <openssl/err.h>
 #include <openssl/ssl.h>
 
@@ -39,16 +41,16 @@
     net_error_lib_ = ERR_get_next_error_library();
   }
 
-  int net_error_lib() const { return net_error_lib_; }
+  unsigned net_error_lib() const { return net_error_lib_; }
 
  private:
-  int net_error_lib_;
+  unsigned net_error_lib_;
 };
 
 base::LazyInstance<OpenSSLNetErrorLibSingleton>::Leaky g_openssl_net_error_lib =
     LAZY_INSTANCE_INITIALIZER;
 
-int OpenSSLNetErrorLib() {
+unsigned OpenSSLNetErrorLib() {
   return g_openssl_net_error_lib.Get().net_error_lib();
 }
 
@@ -162,7 +164,7 @@
     NOTREACHED();
     err = ERR_INVALID_ARGUMENT;
   }
-  ERR_PUT_error(OpenSSLNetErrorLib(), 0, err,
+  ERR_put_error(OpenSSLNetErrorLib(), 0, err,
                 location.file_name(), location.line_number());
 }
 
diff --git a/net/socket/ssl_client_socket_openssl.cc b/net/socket/ssl_client_socket_openssl.cc
index 0c480c9..1c00180 100644
--- a/net/socket/ssl_client_socket_openssl.cc
+++ b/net/socket/ssl_client_socket_openssl.cc
@@ -7,8 +7,8 @@
 
 #include "net/socket/ssl_client_socket_openssl.h"
 
+#include <errno.h>
 #include <openssl/err.h>
-#include <openssl/opensslv.h>
 #include <openssl/ssl.h>
 
 #include "base/bind.h"
@@ -153,6 +153,7 @@
     // but that is an OpenSSL issue.
     SSL_CTX_set_next_proto_select_cb(ssl_ctx_.get(), SelectNextProtoCallback,
                                      NULL);
+    ssl_ctx_->tlsext_channel_id_enabled_new = 1;
   }
 
   static std::string GetSessionCacheKey(const SSL* ssl) {
@@ -248,7 +249,7 @@
 
   // Must increase the reference count manually for sk_X509_dup
   openssl_chain_.reset(sk_X509_dup(other.openssl_chain_.get()));
-  for (int i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
+  for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
     X509* x = sk_X509_value(openssl_chain_.get(), i);
     CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
   }
@@ -267,7 +268,7 @@
     return;
 
   X509Certificate::OSCertHandles intermediates;
-  for (int i = 1; i < sk_X509_num(chain); ++i)
+  for (size_t i = 1; i < sk_X509_num(chain); ++i)
     intermediates.push_back(sk_X509_value(chain, i));
 
   os_chain_ =
@@ -277,7 +278,7 @@
   openssl_chain_.reset(sk_X509_dup(chain));
 
   std::vector<base::StringPiece> der_chain;
-  for (int i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
+  for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
     X509* x = sk_X509_value(openssl_chain_.get(), i);
     // Increase the reference count for the certs in openssl_chain_.
     CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
@@ -296,7 +297,7 @@
   openssl_chain_.reset(sk_X509_dup(chain));
 
   std::vector<base::StringPiece> der_chain;
-  for (int i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
+  for (size_t i = 0; i < sk_X509_num(openssl_chain_.get()); ++i) {
     X509* x = sk_X509_value(openssl_chain_.get(), i);
 
     // Increase the reference count for the certs in openssl_chain_.
@@ -507,8 +508,8 @@
     return false;
   // If there is data waiting to be sent, or data read from the network that
   // has not yet been consumed.
-  if (BIO_ctrl_pending(transport_bio_) > 0 ||
-      BIO_ctrl_wpending(transport_bio_) > 0) {
+  if (BIO_pending(transport_bio_) > 0 ||
+      BIO_wpending(transport_bio_) > 0) {
     return false;
   }
 
@@ -578,11 +579,9 @@
   const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_);
   CHECK(cipher);
   ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL);
-  const COMP_METHOD* compression = SSL_get_current_compression(ssl_);
 
   ssl_info->connection_status = EncodeSSLConnectionStatus(
-      SSL_CIPHER_get_id(cipher),
-      compression ? compression->type : 0,
+      SSL_CIPHER_get_id(cipher), 0 /* no compression */,
       GetNetSSLVersion(ssl_));
 
   bool peer_supports_renego_ext = !!SSL_get_secure_renegotiation_support(ssl_);
@@ -732,7 +731,7 @@
                       "!aECDH:!AESGCM+AES256");
   // Walk through all the installed ciphers, seeing if any need to be
   // appended to the cipher removal |command|.
-  for (int i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
+  for (size_t i = 0; i < sk_SSL_CIPHER_num(ciphers); ++i) {
     const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i);
     const uint16 id = SSL_CIPHER_get_id(cipher);
     // Remove any ciphers with a strength of less than 80 bits. Note the NSS
@@ -1206,7 +1205,7 @@
 
   if (!send_buffer_.get()) {
     // Get a fresh send buffer out of the send BIO.
-    size_t max_read = BIO_ctrl_pending(transport_bio_);
+    size_t max_read = BIO_pending(transport_bio_);
     if (!max_read)
       return 0;  // Nothing pending in the OpenSSL write BIO.
     send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
@@ -1329,7 +1328,7 @@
     // have one at hand.
     client_auth_cert_needed_ = true;
     STACK_OF(X509_NAME) *authorities = SSL_get_client_CA_list(ssl);
-    for (int i = 0; i < sk_X509_NAME_num(authorities); i++) {
+    for (size_t i = 0; i < sk_X509_NAME_num(authorities); i++) {
       X509_NAME *ca_name = (X509_NAME *)sk_X509_NAME_value(authorities, i);
       unsigned char* str = NULL;
       int length = i2d_X509_NAME(ca_name, &str);
diff --git a/net/socket/ssl_server_socket_openssl.cc b/net/socket/ssl_server_socket_openssl.cc
index 7a1ce16..84ba622d 100644
--- a/net/socket/ssl_server_socket_openssl.cc
+++ b/net/socket/ssl_server_socket_openssl.cc
@@ -305,7 +305,7 @@
 
   if (!send_buffer_.get()) {
     // Get a fresh send buffer out of the send BIO.
-    size_t max_read = BIO_ctrl_pending(transport_bio_);
+    size_t max_read = BIO_pending(transport_bio_);
     if (!max_read)
       return 0;  // Nothing pending in the OpenSSL write BIO.
     send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read);
diff --git a/net/socket/ssl_session_cache_openssl_unittest.cc b/net/socket/ssl_session_cache_openssl_unittest.cc
index 41e195fa..54b1e3b 100644
--- a/net/socket/ssl_session_cache_openssl_unittest.cc
+++ b/net/socket/ssl_session_cache_openssl_unittest.cc
@@ -75,8 +75,8 @@
   // Called when an SSL object is copied through SSL_dup(). This needs to copy
   // the value as well.
   static int KeyDup(CRYPTO_EX_DATA* to,
-                    CRYPTO_EX_DATA* from,
-                    void* from_fd,
+                    const CRYPTO_EX_DATA* from,
+                    void** from_fd,
                     int idx,
                     long argl,
                     void* argp) {
diff --git a/net/tools/flip_server/acceptor_thread.cc b/net/tools/flip_server/acceptor_thread.cc
index 5dfece1d..2b65e5d 100644
--- a/net/tools/flip_server/acceptor_thread.cc
+++ b/net/tools/flip_server/acceptor_thread.cc
@@ -4,6 +4,7 @@
 
 #include "net/tools/flip_server/acceptor_thread.h"
 
+#include <errno.h>
 #include <netinet/in.h>
 #include <netinet/tcp.h>  // For TCP_NODELAY
 #include <sys/socket.h>
diff --git a/net/tools/flip_server/spdy_ssl.cc b/net/tools/flip_server/spdy_ssl.cc
index 2a5cb0e4..19ea52e 100644
--- a/net/tools/flip_server/spdy_ssl.cc
+++ b/net/tools/flip_server/spdy_ssl.cc
@@ -80,6 +80,7 @@
   SSL_CTX_set_mode(state->ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
 #endif
 
+#if !defined(OPENSSL_IS_BORINGSSL)
   // Proper methods to disable compression don't exist until 0.9.9+. For now
   // we must manipulate the stack of compression methods directly.
   if (disable_ssl_compression) {
@@ -90,6 +91,7 @@
       static_cast<void>(sk_SSL_COMP_delete(ssl_comp_methods, i));
     }
   }
+#endif
 }
 
 SSL* CreateSSLContext(SSL_CTX* ssl_ctx) {
diff --git a/remoting/host/token_validator_base.cc b/remoting/host/token_validator_base.cc
index 8a5c2c3..452a182 100644
--- a/remoting/host/token_validator_base.cc
+++ b/remoting/host/token_validator_base.cc
@@ -120,6 +120,9 @@
   client_cert_store = new net::ClientCertStoreWin();
 #elif defined(OS_MACOSX)
   client_cert_store = new net::ClientCertStoreMac();
+#elif defined(USE_OPENSSL)
+    // OpenSSL does not use the ClientCertStore infrastructure.
+  client_cert_store = NULL;
 #else
 #error Unknown platform.
 #endif
diff --git a/remoting/remoting_nacl.gyp b/remoting/remoting_nacl.gyp
index c2598c9..0dd96b1 100644
--- a/remoting/remoting_nacl.gyp
+++ b/remoting/remoting_nacl.gyp
@@ -108,7 +108,7 @@
         '../third_party/libvpx/libvpx_nacl.gyp:libvpx_nacl',
         '../third_party/libwebm/libwebm_nacl.gyp:libwebm_nacl',
         '../third_party/libyuv/libyuv_nacl.gyp:libyuv_nacl',
-        '../third_party/openssl/openssl_nacl.gyp:openssl_nacl',
+        '../third_party/boringssl/boringssl_nacl.gyp:boringssl_nacl',
         '../third_party/opus/opus_nacl.gyp:opus_nacl',
         'remoting_proto_nacl',
         'remoting_webrtc_nacl',
@@ -160,7 +160,7 @@
           '>(tc_lib_dir_pnacl_newlib)/libjingle_p2p_constants_nacl.a',
           '>(tc_lib_dir_pnacl_newlib)/libmedia_yuv_nacl.a',
           '>(tc_lib_dir_pnacl_newlib)/libmodp_b64_nacl.a',
-          '>(tc_lib_dir_pnacl_newlib)/libopenssl_nacl.a',
+          '>(tc_lib_dir_pnacl_newlib)/libboringssl_nacl.a',
           '>(tc_lib_dir_pnacl_newlib)/libopus_nacl.a',
           '>(tc_lib_dir_pnacl_newlib)/libppapi.a',
           '>(tc_lib_dir_pnacl_newlib)/libppapi_cpp.a',
@@ -196,7 +196,7 @@
         '../third_party/libwebm/libwebm_nacl.gyp:libwebm_nacl',
         '../third_party/libyuv/libyuv_nacl.gyp:libyuv_nacl',
         '../third_party/modp_b64/modp_b64_nacl.gyp:modp_b64_nacl',
-        '../third_party/openssl/openssl_nacl.gyp:openssl_nacl',
+        '../third_party/boringssl/boringssl_nacl.gyp:boringssl_nacl',
         '../url/url_nacl.gyp:url_nacl',
         'remoting_client_plugin_lib_nacl',
         'remoting_proto_nacl',
@@ -227,7 +227,7 @@
         '-lexpat_nacl',
         '-lmodp_b64_nacl',
         '-lopus_nacl',
-        '-lopenssl_nacl',
+        '-lboringssl_nacl',
         '-licui18n_nacl',
         '-licuuc_nacl',
         '-licudata_nacl',
diff --git a/third_party/boringssl/BUILD.gn b/third_party/boringssl/BUILD.gn
new file mode 100644
index 0000000..468d17c6
--- /dev/null
+++ b/third_party/boringssl/BUILD.gn
@@ -0,0 +1,76 @@
+# Copyright 2014 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+# Config for us and everybody else depending on BoringSSL.
+config("openssl_config") {
+  include_dirs = []
+  include_dirs += [ "src/include" ]
+}
+
+# Config internal to this build file.
+config("openssl_internal_config") {
+  visibility = ":*"  # Only targets in this file can depend on this.
+}
+
+# The list of BoringSSL files is kept in boringssl.gypi.
+gypi_values = exec_script(
+    "//build/gypi_to_gn.py",
+    [ rebase_path("//third_party/boringssl/boringssl.gypi") ],
+    "scope",
+    [ "//third_party/boringssl/boringssl.gypi" ])
+
+component("boringssl") {
+  sources = gypi_values.boringssl_lib_sources
+
+  direct_dependent_configs = [ ":openssl_config" ]
+
+  cflags = []
+
+  configs -= [ "//build/config/compiler:chromium_code" ]
+  configs += [ "//build/config/compiler:no_chromium_code" ]
+
+  # Also gets the include dirs from :openssl_config
+  include_dirs = [
+    "src/include",
+    # This is for arm_arch.h, which is needed by some asm files. Since the
+    # asm files are generated and kept in a different directory, they
+    # cannot use relative paths to find this file.
+    "src/crypto",
+  ]
+
+  if (cpu_arch == "x64") {
+    if (is_mac) {
+      sources += gypi_values.boringssl_mac_x86_64_sources
+    } else if (is_linux || is_android) {
+      sources += gypi_values.boringssl_linux_x86_64_sources
+    } else if (is_win) {
+      sources += gypi_values.boringssl_win_x86_64_sources
+    } else {
+      defines += [ "OPENSSL_NO_ASM" ]
+    }
+  } else if (cpu_arch == "x86") {
+    if (is_mac) {
+      sources += gypi_values.boringssl_mac_x86_sources
+    } else if (is_linux || is_android) {
+      sources += gypi_values.boringssl_linux_x86_sources
+    } else {
+      defines += [ "OPENSSL_NO_ASM" ]
+    }
+  } else if (cpu_arch == "arm") {
+    sources += gypi_values.boringssl_linux_arm_sources
+  } else {
+    defines += [ "OPENSSL_NO_ASM" ]
+  }
+
+  if (is_component_build) {
+    if (!is_win) {
+      configs -= [ "//build/config/gcc:symbol_visibility_hidden" ]
+    }
+    if (is_posix && !is_mac) {
+      # Avoid link failures on Linux x86-64.
+      # See http://rt.openssl.org/Ticket/Display.html?id=2466&user=guest&pass=guest
+      ldflags += [ "-Wl,-Bsymbolic" ]
+    }
+  }
+}
diff --git a/third_party/boringssl/boringssl.gyp b/third_party/boringssl/boringssl.gyp
index 19e3fcb..fa7c5b6 100644
--- a/third_party/boringssl/boringssl.gyp
+++ b/third_party/boringssl/boringssl.gyp
@@ -9,7 +9,7 @@
   'targets': [
     {
       'target_name': 'boringssl',
-      'type': 'static_library',
+      'type': '<(component)',
       'includes': [
         'boringssl.gypi',
       ],
@@ -52,6 +52,19 @@
         ['target_arch != "arm" and target_arch != "ia32" and target_arch != "x64"', {
           'defines': [ 'OPENSSL_NO_ASM' ],
         }],
+        ['component == "shared_library"', {
+          'xcode_settings': {
+            'GCC_SYMBOLS_PRIVATE_EXTERN': 'NO',  # no -fvisibility=hidden
+          },
+          'cflags!': [ '-fvisibility=hidden' ],
+          'conditions': [
+            ['os_posix == 1 and OS != "mac"', {
+              # Avoid link failures on Linux x86-64.
+              # See http://rt.openssl.org/Ticket/Display.html?id=2466&user=guest&pass=guest
+              'ldflags+': [ '-Wl,-Bsymbolic' ],
+            }],
+          ],
+        }],
       ],
       'include_dirs': [
         'src/include',
diff --git a/third_party/boringssl/boringssl_nacl.gyp b/third_party/boringssl/boringssl_nacl.gyp
new file mode 100644
index 0000000..6ab4b9d
--- /dev/null
+++ b/third_party/boringssl/boringssl_nacl.gyp
@@ -0,0 +1,50 @@
+# Copyright 2014 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+{
+  'includes': [
+    '../../native_client/build/untrusted.gypi',
+  ],
+  'targets': [
+    {
+      'target_name': 'boringssl_nacl',
+      'type': 'none',
+      'variables': {
+        'nlib_target': 'libboringssl_nacl.a',
+        'build_glibc': 0,
+        'build_newlib': 0,
+        'build_pnacl_newlib': 1,
+      },
+      'dependencies': [
+        '<(DEPTH)/native_client/tools.gyp:prep_toolchain',
+        '<(DEPTH)/native_client_sdk/native_client_sdk_untrusted.gyp:nacl_io_untrusted',
+      ],
+      'includes': [
+        # Include the auto-generated gypi file.
+        'boringssl.gypi'
+      ],
+      'sources': [
+        '<@(boringssl_lib_sources)',
+      ],
+      'defines': [
+        'OPENSSL_NO_ASM',
+      ],
+      'include_dirs': [
+        'src/include',
+        # This is for arm_arch.h, which is needed by some asm files. Since the
+        # asm files are generated and kept in a different directory, they
+        # cannot use relative paths to find this file.
+        'src/crypto',
+      ],
+      'direct_dependent_settings': {
+        'include_dirs': [
+          'src/include',
+        ],
+      },
+      'pnacl_compile_flags': [
+        '-Wno-sometimes-uninitialized',
+        '-Wno-unused-variable',
+      ],
+    },  # target boringssl_nacl
+  ],
+}
diff --git a/third_party/boringssl/boringssl_tests.gypi b/third_party/boringssl/boringssl_tests.gypi
index 788c4c53..aa74b8f50 100644
--- a/third_party/boringssl/boringssl_tests.gypi
+++ b/third_party/boringssl/boringssl_tests.gypi
@@ -7,93 +7,13 @@
 {
   'targets': [
     {
-      'target_name': 'boringssl_sha1_test',
+      'target_name': 'boringssl_base64_test',
       'type': 'executable',
       'dependencies': [
         'boringssl',
       ],
       'sources': [
-        'src/crypto/sha/sha1_test.c',
-      ],
-    },
-    {
-      'target_name': 'boringssl_gcm_test',
-      'type': 'executable',
-      'dependencies': [
-        'boringssl',
-      ],
-      'sources': [
-        'src/crypto/modes/gcm_test.c',
-      ],
-    },
-    {
-      'target_name': 'boringssl_err_test',
-      'type': 'executable',
-      'dependencies': [
-        'boringssl',
-      ],
-      'sources': [
-        'src/crypto/err/err_test.c',
-      ],
-    },
-    {
-      'target_name': 'boringssl_dsa_test',
-      'type': 'executable',
-      'dependencies': [
-        'boringssl',
-      ],
-      'sources': [
-        'src/crypto/dsa/dsa_test.c',
-      ],
-    },
-    {
-      'target_name': 'boringssl_dh_test',
-      'type': 'executable',
-      'dependencies': [
-        'boringssl',
-      ],
-      'sources': [
-        'src/crypto/dh/dh_test.c',
-      ],
-    },
-    {
-      'target_name': 'boringssl_aead_test',
-      'type': 'executable',
-      'dependencies': [
-        'boringssl',
-      ],
-      'sources': [
-        'src/crypto/cipher/aead_test.c',
-      ],
-    },
-    {
-      'target_name': 'boringssl_cipher_test',
-      'type': 'executable',
-      'dependencies': [
-        'boringssl',
-      ],
-      'sources': [
-        'src/crypto/cipher/cipher_test.c',
-      ],
-    },
-    {
-      'target_name': 'boringssl_hmac_test',
-      'type': 'executable',
-      'dependencies': [
-        'boringssl',
-      ],
-      'sources': [
-        'src/crypto/hmac/hmac_test.c',
-      ],
-    },
-    {
-      'target_name': 'boringssl_lhash_test',
-      'type': 'executable',
-      'dependencies': [
-        'boringssl',
-      ],
-      'sources': [
-        'src/crypto/lhash/lhash_test.c',
+        'src/crypto/base64/base64_test.c',
       ],
     },
     {
@@ -107,36 +27,6 @@
       ],
     },
     {
-      'target_name': 'boringssl_md5_test',
-      'type': 'executable',
-      'dependencies': [
-        'boringssl',
-      ],
-      'sources': [
-        'src/crypto/md5/md5_test.c',
-      ],
-    },
-    {
-      'target_name': 'boringssl_rsa_test',
-      'type': 'executable',
-      'dependencies': [
-        'boringssl',
-      ],
-      'sources': [
-        'src/crypto/rsa/rsa_test.c',
-      ],
-    },
-    {
-      'target_name': 'boringssl_example_sign',
-      'type': 'executable',
-      'dependencies': [
-        'boringssl',
-      ],
-      'sources': [
-        'src/crypto/evp/example_sign.c',
-      ],
-    },
-    {
       'target_name': 'boringssl_bn_test',
       'type': 'executable',
       'dependencies': [
@@ -157,6 +47,46 @@
       ],
     },
     {
+      'target_name': 'boringssl_aead_test',
+      'type': 'executable',
+      'dependencies': [
+        'boringssl',
+      ],
+      'sources': [
+        'src/crypto/cipher/aead_test.c',
+      ],
+    },
+    {
+      'target_name': 'boringssl_cipher_test',
+      'type': 'executable',
+      'dependencies': [
+        'boringssl',
+      ],
+      'sources': [
+        'src/crypto/cipher/cipher_test.c',
+      ],
+    },
+    {
+      'target_name': 'boringssl_dh_test',
+      'type': 'executable',
+      'dependencies': [
+        'boringssl',
+      ],
+      'sources': [
+        'src/crypto/dh/dh_test.c',
+      ],
+    },
+    {
+      'target_name': 'boringssl_dsa_test',
+      'type': 'executable',
+      'dependencies': [
+        'boringssl',
+      ],
+      'sources': [
+        'src/crypto/dsa/dsa_test.c',
+      ],
+    },
+    {
       'target_name': 'boringssl_example_mul',
       'type': 'executable',
       'dependencies': [
@@ -176,10 +106,91 @@
         'src/crypto/ecdsa/ecdsa_test.c',
       ],
     },
+    {
+      'target_name': 'boringssl_err_test',
+      'type': 'executable',
+      'dependencies': [
+        'boringssl',
+      ],
+      'sources': [
+        'src/crypto/err/err_test.c',
+      ],
+    },
+    {
+      'target_name': 'boringssl_example_sign',
+      'type': 'executable',
+      'dependencies': [
+        'boringssl',
+      ],
+      'sources': [
+        'src/crypto/evp/example_sign.c',
+      ],
+    },
+    {
+      'target_name': 'boringssl_hmac_test',
+      'type': 'executable',
+      'dependencies': [
+        'boringssl',
+      ],
+      'sources': [
+        'src/crypto/hmac/hmac_test.c',
+      ],
+    },
+    {
+      'target_name': 'boringssl_lhash_test',
+      'type': 'executable',
+      'dependencies': [
+        'boringssl',
+      ],
+      'sources': [
+        'src/crypto/lhash/lhash_test.c',
+      ],
+    },
+    {
+      'target_name': 'boringssl_md5_test',
+      'type': 'executable',
+      'dependencies': [
+        'boringssl',
+      ],
+      'sources': [
+        'src/crypto/md5/md5_test.c',
+      ],
+    },
+    {
+      'target_name': 'boringssl_gcm_test',
+      'type': 'executable',
+      'dependencies': [
+        'boringssl',
+      ],
+      'sources': [
+        'src/crypto/modes/gcm_test.c',
+      ],
+    },
+    {
+      'target_name': 'boringssl_rsa_test',
+      'type': 'executable',
+      'dependencies': [
+        'boringssl',
+      ],
+      'sources': [
+        'src/crypto/rsa/rsa_test.c',
+      ],
+    },
+    {
+      'target_name': 'boringssl_sha1_test',
+      'type': 'executable',
+      'dependencies': [
+        'boringssl',
+      ],
+      'sources': [
+        'src/crypto/sha/sha1_test.c',
+      ],
+    },
   ],
   'variables': {
     'boringssl_test_targets': [
       'boringssl_aead_test',
+      'boringssl_base64_test',
       'boringssl_bio_test',
       'boringssl_bn_test',
       'boringssl_bytestring_test',
diff --git a/third_party/boringssl/boringssl_unittest.cc b/third_party/boringssl/boringssl_unittest.cc
index 3638128..819399b 100644
--- a/third_party/boringssl/boringssl_unittest.cc
+++ b/third_party/boringssl/boringssl_unittest.cc
@@ -113,6 +113,10 @@
   TestProcess("aead_test", args);
 }
 
+TEST(BoringSSL, Base64) {
+  TestSimple("base64_test");
+}
+
 TEST(BoringSSL, BIO) {
   TestSimple("bio_test");
 }
diff --git a/third_party/boringssl/linux-x86/crypto/aes/aes-586.S b/third_party/boringssl/linux-x86/crypto/aes/aes-586.S
index 0f744ca..4adcf36 100644
--- a/third_party/boringssl/linux-x86/crypto/aes/aes-586.S
+++ b/third_party/boringssl/linux-x86/crypto/aes/aes-586.S
@@ -1001,7 +1001,7 @@
 	call	.L004pic_point
 .L004pic_point:
 	popl	%ebp
-	leal	OPENSSL_ia32cap_P,%eax
+	leal	OPENSSL_ia32cap_P-.L004pic_point(%ebp),%eax
 	leal	.LAES_Te-.L004pic_point(%ebp),%ebp
 	leal	764(%esp),%ebx
 	subl	%ebp,%ebx
@@ -2193,7 +2193,7 @@
 	call	.L010pic_point
 .L010pic_point:
 	popl	%ebp
-	leal	OPENSSL_ia32cap_P,%eax
+	leal	OPENSSL_ia32cap_P-.L010pic_point(%ebp),%eax
 	leal	.LAES_Td-.L010pic_point(%ebp),%ebp
 	leal	764(%esp),%ebx
 	subl	%ebp,%ebx
@@ -2249,7 +2249,7 @@
 	call	.L013pic_point
 .L013pic_point:
 	popl	%ebp
-	leal	OPENSSL_ia32cap_P,%eax
+	leal	OPENSSL_ia32cap_P-.L013pic_point(%ebp),%eax
 	cmpl	$0,40(%esp)
 	leal	.LAES_Te-.L013pic_point(%ebp),%ebp
 	jne	.L014picked_te
@@ -3242,4 +3242,4 @@
 .byte	65,69,83,32,102,111,114,32,120,56,54,44,32,67,82,89
 .byte	80,84,79,71,65,77,83,32,98,121,32,60,97,112,112,114
 .byte	111,64,111,112,101,110,115,115,108,46,111,114,103,62,0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/linux-x86/crypto/aes/aesni-x86.S b/third_party/boringssl/linux-x86/crypto/aes/aesni-x86.S
index 8d1d6ae..0694c74 100644
--- a/third_party/boringssl/linux-x86/crypto/aes/aesni-x86.S
+++ b/third_party/boringssl/linux-x86/crypto/aes/aesni-x86.S
@@ -2195,4 +2195,4 @@
 .byte	83,45,78,73,44,32,67,82,89,80,84,79,71,65,77,83
 .byte	32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115
 .byte	115,108,46,111,114,103,62,0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/linux-x86/crypto/aes/vpaes-x86.S b/third_party/boringssl/linux-x86/crypto/aes/vpaes-x86.S
index 187c6e6..8a420524 100644
--- a/third_party/boringssl/linux-x86/crypto/aes/vpaes-x86.S
+++ b/third_party/boringssl/linux-x86/crypto/aes/vpaes-x86.S
@@ -660,4 +660,4 @@
 	popl	%ebp
 	ret
 .size	vpaes_cbc_encrypt,.-.L_vpaes_cbc_encrypt_begin
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/linux-x86/crypto/bn/bn-586.S b/third_party/boringssl/linux-x86/crypto/bn/bn-586.S
index 92c8ac8..2d2c13d 100644
--- a/third_party/boringssl/linux-x86/crypto/bn/bn-586.S
+++ b/third_party/boringssl/linux-x86/crypto/bn/bn-586.S
@@ -1383,4 +1383,4 @@
 	popl	%ebp
 	ret
 .size	bn_sub_part_words,.-.L_bn_sub_part_words_begin
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/linux-x86/crypto/bn/co-586.S b/third_party/boringssl/linux-x86/crypto/bn/co-586.S
index c021250..6ea84009 100644
--- a/third_party/boringssl/linux-x86/crypto/bn/co-586.S
+++ b/third_party/boringssl/linux-x86/crypto/bn/co-586.S
@@ -1253,4 +1253,4 @@
 	popl	%esi
 	ret
 .size	bn_sqr_comba4,.-.L_bn_sqr_comba4_begin
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/linux-x86/crypto/bn/x86-mont.S b/third_party/boringssl/linux-x86/crypto/bn/x86-mont.S
index 6733a3347..3032940 100644
--- a/third_party/boringssl/linux-x86/crypto/bn/x86-mont.S
+++ b/third_party/boringssl/linux-x86/crypto/bn/x86-mont.S
@@ -336,4 +336,4 @@
 .byte	54,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121
 .byte	32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46
 .byte	111,114,103,62,0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/linux-x86/crypto/cpu-x86-asm.S b/third_party/boringssl/linux-x86/crypto/cpu-x86-asm.S
index 4ca8586..bcd3c4c 100644
--- a/third_party/boringssl/linux-x86/crypto/cpu-x86-asm.S
+++ b/third_party/boringssl/linux-x86/crypto/cpu-x86-asm.S
@@ -153,11 +153,14 @@
 .L_OPENSSL_rdtsc_begin:
 	xorl	%eax,%eax
 	xorl	%edx,%edx
-	leal	OPENSSL_ia32cap_P,%ecx
+	call	.L009PIC_me_up
+.L009PIC_me_up:
+	popl	%ecx
+	leal	OPENSSL_ia32cap_P-.L009PIC_me_up(%ecx),%ecx
 	btl	$4,(%ecx)
-	jnc	.L009notsc
+	jnc	.L010notsc
 	.byte	0x0f,0x31
-.L009notsc:
+.L010notsc:
 	ret
 .size	OPENSSL_rdtsc,.-.L_OPENSSL_rdtsc_begin
 .globl	OPENSSL_instrument_halt
@@ -165,16 +168,19 @@
 .align	16
 OPENSSL_instrument_halt:
 .L_OPENSSL_instrument_halt_begin:
-	leal	OPENSSL_ia32cap_P,%ecx
+	call	.L011PIC_me_up
+.L011PIC_me_up:
+	popl	%ecx
+	leal	OPENSSL_ia32cap_P-.L011PIC_me_up(%ecx),%ecx
 	btl	$4,(%ecx)
-	jnc	.L010nohalt
+	jnc	.L012nohalt
 .long	2421723150
 	andl	$3,%eax
-	jnz	.L010nohalt
+	jnz	.L012nohalt
 	pushfl
 	popl	%eax
 	btl	$9,%eax
-	jnc	.L010nohalt
+	jnc	.L012nohalt
 	.byte	0x0f,0x31
 	pushl	%edx
 	pushl	%eax
@@ -184,7 +190,7 @@
 	sbbl	4(%esp),%edx
 	addl	$8,%esp
 	ret
-.L010nohalt:
+.L012nohalt:
 	xorl	%eax,%eax
 	xorl	%edx,%edx
 	ret
@@ -197,21 +203,21 @@
 	pushfl
 	popl	%eax
 	btl	$9,%eax
-	jnc	.L011nospin
+	jnc	.L013nospin
 	movl	4(%esp),%eax
 	movl	8(%esp),%ecx
 .long	2430111262
 	xorl	%eax,%eax
 	movl	(%ecx),%edx
-	jmp	.L012spin
+	jmp	.L014spin
 .align	16
-.L012spin:
+.L014spin:
 	incl	%eax
 	cmpl	(%ecx),%edx
-	je	.L012spin
+	je	.L014spin
 .long	529567888
 	ret
-.L011nospin:
+.L013nospin:
 	xorl	%eax,%eax
 	xorl	%edx,%edx
 	ret
@@ -223,12 +229,15 @@
 .L_OPENSSL_wipe_cpu_begin:
 	xorl	%eax,%eax
 	xorl	%edx,%edx
-	leal	OPENSSL_ia32cap_P,%ecx
+	call	.L015PIC_me_up
+.L015PIC_me_up:
+	popl	%ecx
+	leal	OPENSSL_ia32cap_P-.L015PIC_me_up(%ecx),%ecx
 	movl	(%ecx),%ecx
 	btl	$1,(%ecx)
-	jnc	.L013no_x87
+	jnc	.L016no_x87
 .long	4007259865,4007259865,4007259865,4007259865,2430851995
-.L013no_x87:
+.L016no_x87:
 	leal	4(%esp),%eax
 	ret
 .size	OPENSSL_wipe_cpu,.-.L_OPENSSL_wipe_cpu_begin
@@ -242,11 +251,11 @@
 	pushl	%ebx
 	nop
 	movl	(%edx),%eax
-.L014spin:
+.L017spin:
 	leal	(%eax,%ecx,1),%ebx
 	nop
 .long	447811568
-	jne	.L014spin
+	jne	.L017spin
 	movl	%ebx,%eax
 	popl	%ebx
 	ret
@@ -287,32 +296,32 @@
 	movl	8(%esp),%ecx
 	xorl	%eax,%eax
 	cmpl	$7,%ecx
-	jae	.L015lot
+	jae	.L018lot
 	cmpl	$0,%ecx
-	je	.L016ret
-.L017little:
+	je	.L019ret
+.L020little:
 	movb	%al,(%edx)
 	subl	$1,%ecx
 	leal	1(%edx),%edx
-	jnz	.L017little
-.L016ret:
+	jnz	.L020little
+.L019ret:
 	ret
 .align	16
-.L015lot:
+.L018lot:
 	testl	$3,%edx
-	jz	.L018aligned
+	jz	.L021aligned
 	movb	%al,(%edx)
 	leal	-1(%ecx),%ecx
 	leal	1(%edx),%edx
-	jmp	.L015lot
-.L018aligned:
+	jmp	.L018lot
+.L021aligned:
 	movl	%eax,(%edx)
 	leal	-4(%ecx),%ecx
 	testl	$-4,%ecx
 	leal	4(%edx),%edx
-	jnz	.L018aligned
+	jnz	.L021aligned
 	cmpl	$0,%ecx
-	jne	.L017little
+	jne	.L020little
 	ret
 .size	OPENSSL_cleanse,.-.L_OPENSSL_cleanse_begin
 .globl	OPENSSL_ia32_rdrand
@@ -321,14 +330,14 @@
 OPENSSL_ia32_rdrand:
 .L_OPENSSL_ia32_rdrand_begin:
 	movl	$8,%ecx
-.L019loop:
+.L022loop:
 .byte	15,199,240
-	jc	.L020break
-	loop	.L019loop
-.L020break:
+	jc	.L023break
+	loop	.L022loop
+.L023break:
 	cmpl	$0,%eax
 	cmovel	%ecx,%eax
 	ret
 .size	OPENSSL_ia32_rdrand,.-.L_OPENSSL_ia32_rdrand_begin
 .hidden	OPENSSL_ia32cap_P
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/linux-x86/crypto/md5/md5-586.S b/third_party/boringssl/linux-x86/crypto/md5/md5-586.S
index 8c7d4e28..b8ab21e 100644
--- a/third_party/boringssl/linux-x86/crypto/md5/md5-586.S
+++ b/third_party/boringssl/linux-x86/crypto/md5/md5-586.S
@@ -678,4 +678,4 @@
 	popl	%esi
 	ret
 .size	md5_block_asm_data_order,.-.L_md5_block_asm_data_order_begin
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/linux-x86/crypto/modes/ghash-x86.S b/third_party/boringssl/linux-x86/crypto/modes/ghash-x86.S
index f81eeb5..32d6b2d 100644
--- a/third_party/boringssl/linux-x86/crypto/modes/ghash-x86.S
+++ b/third_party/boringssl/linux-x86/crypto/modes/ghash-x86.S
@@ -1264,4 +1264,4 @@
 .byte	82,89,80,84,79,71,65,77,83,32,98,121,32,60,97,112
 .byte	112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62
 .byte	0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/linux-x86/crypto/rc4/rc4-586.S b/third_party/boringssl/linux-x86/crypto/rc4/rc4-586.S
index 4d63575..164d313 100644
--- a/third_party/boringssl/linux-x86/crypto/rc4/rc4-586.S
+++ b/third_party/boringssl/linux-x86/crypto/rc4/rc4-586.S
@@ -33,7 +33,10 @@
 	movl	%ebp,32(%esp)
 	testl	$-8,%edx
 	jz	.L003go4loop4
-	leal	OPENSSL_ia32cap_P,%ebp
+	call	.L004PIC_me_up
+.L004PIC_me_up:
+	popl	%ebp
+	leal	OPENSSL_ia32cap_P-.L004PIC_me_up(%ebp),%ebp
 	btl	$26,(%ebp)
 	jnc	.L003go4loop4
 	movl	32(%esp),%ebp
@@ -51,9 +54,9 @@
 	movq	(%esi),%mm0
 	movl	(%edi,%eax,4),%ecx
 	movd	(%edi,%edx,4),%mm2
-	jmp	.L004loop_mmx_enter
+	jmp	.L005loop_mmx_enter
 .align	16
-.L005loop_mmx:
+.L006loop_mmx:
 	addb	%cl,%bl
 	psllq	$56,%mm1
 	movl	(%edi,%ebx,4),%edx
@@ -68,7 +71,7 @@
 	movq	%mm2,-8(%ebp,%esi,1)
 	movl	(%edi,%eax,4),%ecx
 	movd	(%edi,%edx,4),%mm2
-.L004loop_mmx_enter:
+.L005loop_mmx_enter:
 	addb	%cl,%bl
 	movl	(%edi,%ebx,4),%edx
 	movl	%ecx,(%edi,%ebx,4)
@@ -157,19 +160,19 @@
 	movb	%dl,%bl
 	cmpl	-4(%edi),%esi
 	leal	8(%esi),%esi
-	jb	.L005loop_mmx
+	jb	.L006loop_mmx
 	psllq	$56,%mm1
 	pxor	%mm1,%mm2
 	movq	%mm2,-8(%ebp,%esi,1)
 	emms
 	cmpl	24(%esp),%esi
-	je	.L006done
+	je	.L007done
 	jmp	.L002loop1
 .align	16
 .L003go4loop4:
 	leal	-4(%esi,%edx,1),%edx
 	movl	%edx,28(%esp)
-.L007loop4:
+.L008loop4:
 	addb	%cl,%bl
 	movl	(%edi,%ebx,4),%edx
 	movl	%ecx,(%edi,%ebx,4)
@@ -215,9 +218,9 @@
 	movl	%ebp,(%ecx,%esi,1)
 	leal	4(%esi),%esi
 	movl	(%edi,%eax,4),%ecx
-	jb	.L007loop4
+	jb	.L008loop4
 	cmpl	24(%esp),%esi
-	je	.L006done
+	je	.L007done
 	movl	32(%esp),%ebp
 .align	16
 .L002loop1:
@@ -235,11 +238,11 @@
 	cmpl	24(%esp),%esi
 	movb	%dl,-1(%ebp,%esi,1)
 	jb	.L002loop1
-	jmp	.L006done
+	jmp	.L007done
 .align	16
 .L001RC4_CHAR:
 	movzbl	(%edi,%eax,1),%ecx
-.L008cloop1:
+.L009cloop1:
 	addb	%cl,%bl
 	movzbl	(%edi,%ebx,1),%edx
 	movb	%cl,(%edi,%ebx,1)
@@ -252,8 +255,8 @@
 	movzbl	(%edi,%eax,1),%ecx
 	cmpl	24(%esp),%esi
 	movb	%dl,-1(%ebp,%esi,1)
-	jb	.L008cloop1
-.L006done:
+	jb	.L009cloop1
+.L007done:
 	decb	%al
 	movl	%ebx,-4(%edi)
 	movb	%al,-8(%edi)
@@ -276,60 +279,63 @@
 	movl	20(%esp),%edi
 	movl	24(%esp),%ebp
 	movl	28(%esp),%esi
-	leal	OPENSSL_ia32cap_P,%edx
+	call	.L010PIC_me_up
+.L010PIC_me_up:
+	popl	%edx
+	leal	OPENSSL_ia32cap_P-.L010PIC_me_up(%edx),%edx
 	leal	8(%edi),%edi
 	leal	(%esi,%ebp,1),%esi
 	negl	%ebp
 	xorl	%eax,%eax
 	movl	%ebp,-4(%edi)
 	btl	$20,(%edx)
-	jc	.L009c1stloop
+	jc	.L011c1stloop
 .align	16
-.L010w1stloop:
+.L012w1stloop:
 	movl	%eax,(%edi,%eax,4)
 	addb	$1,%al
-	jnc	.L010w1stloop
+	jnc	.L012w1stloop
 	xorl	%ecx,%ecx
 	xorl	%edx,%edx
 .align	16
-.L011w2ndloop:
+.L013w2ndloop:
 	movl	(%edi,%ecx,4),%eax
 	addb	(%esi,%ebp,1),%dl
 	addb	%al,%dl
 	addl	$1,%ebp
 	movl	(%edi,%edx,4),%ebx
-	jnz	.L012wnowrap
+	jnz	.L014wnowrap
 	movl	-4(%edi),%ebp
-.L012wnowrap:
+.L014wnowrap:
 	movl	%eax,(%edi,%edx,4)
 	movl	%ebx,(%edi,%ecx,4)
 	addb	$1,%cl
-	jnc	.L011w2ndloop
-	jmp	.L013exit
+	jnc	.L013w2ndloop
+	jmp	.L015exit
 .align	16
-.L009c1stloop:
+.L011c1stloop:
 	movb	%al,(%edi,%eax,1)
 	addb	$1,%al
-	jnc	.L009c1stloop
+	jnc	.L011c1stloop
 	xorl	%ecx,%ecx
 	xorl	%edx,%edx
 	xorl	%ebx,%ebx
 .align	16
-.L014c2ndloop:
+.L016c2ndloop:
 	movb	(%edi,%ecx,1),%al
 	addb	(%esi,%ebp,1),%dl
 	addb	%al,%dl
 	addl	$1,%ebp
 	movb	(%edi,%edx,1),%bl
-	jnz	.L015cnowrap
+	jnz	.L017cnowrap
 	movl	-4(%edi),%ebp
-.L015cnowrap:
+.L017cnowrap:
 	movb	%al,(%edi,%edx,1)
 	movb	%bl,(%edi,%ecx,1)
 	addb	$1,%cl
-	jnc	.L014c2ndloop
+	jnc	.L016c2ndloop
 	movl	$-1,256(%edi)
-.L013exit:
+.L015exit:
 	xorl	%eax,%eax
 	movl	%eax,-8(%edi)
 	movl	%eax,-4(%edi)
@@ -344,24 +350,27 @@
 .align	16
 RC4_options:
 .L_RC4_options_begin:
-	call	.L016pic_point
-.L016pic_point:
+	call	.L018pic_point
+.L018pic_point:
 	popl	%eax
-	leal	.L017opts-.L016pic_point(%eax),%eax
-	leal	OPENSSL_ia32cap_P,%edx
+	leal	.L019opts-.L018pic_point(%eax),%eax
+	call	.L020PIC_me_up
+.L020PIC_me_up:
+	popl	%edx
+	leal	OPENSSL_ia32cap_P-.L020PIC_me_up(%edx),%edx
 	movl	(%edx),%edx
 	btl	$20,%edx
-	jc	.L0181xchar
+	jc	.L0211xchar
 	btl	$26,%edx
-	jnc	.L019ret
+	jnc	.L022ret
 	addl	$25,%eax
 	ret
-.L0181xchar:
+.L0211xchar:
 	addl	$12,%eax
-.L019ret:
+.L022ret:
 	ret
 .align	64
-.L017opts:
+.L019opts:
 .byte	114,99,52,40,52,120,44,105,110,116,41,0
 .byte	114,99,52,40,49,120,44,99,104,97,114,41,0
 .byte	114,99,52,40,56,120,44,109,109,120,41,0
@@ -370,4 +379,4 @@
 .byte	111,64,111,112,101,110,115,115,108,46,111,114,103,62,0
 .align	64
 .size	RC4_options,.-.L_RC4_options_begin
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/linux-x86/crypto/sha/sha1-586.S b/third_party/boringssl/linux-x86/crypto/sha/sha1-586.S
index b1610d8..a60ed37 100644
--- a/third_party/boringssl/linux-x86/crypto/sha/sha1-586.S
+++ b/third_party/boringssl/linux-x86/crypto/sha/sha1-586.S
@@ -1379,4 +1379,4 @@
 .byte	102,111,114,109,32,102,111,114,32,120,56,54,44,32,67,82
 .byte	89,80,84,79,71,65,77,83,32,98,121,32,60,97,112,112
 .byte	114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/linux-x86/crypto/sha/sha256-586.S b/third_party/boringssl/linux-x86/crypto/sha/sha256-586.S
index 9b70481..cabd5c0 100644
--- a/third_party/boringssl/linux-x86/crypto/sha/sha256-586.S
+++ b/third_party/boringssl/linux-x86/crypto/sha/sha256-586.S
@@ -3346,4 +3346,4 @@
 	popl	%ebp
 	ret
 .size	sha256_block_data_order,.-.L_sha256_block_data_order_begin
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/linux-x86/crypto/sha/sha512-586.S b/third_party/boringssl/linux-x86/crypto/sha/sha512-586.S
index 37cec09..2a09ccb2 100644
--- a/third_party/boringssl/linux-x86/crypto/sha/sha512-586.S
+++ b/third_party/boringssl/linux-x86/crypto/sha/sha512-586.S
@@ -564,4 +564,4 @@
 .byte	67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97
 .byte	112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103
 .byte	62,0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/aes/aes-586.S b/third_party/boringssl/mac-x86/crypto/aes/aes-586.S
index d2c87d7..f5ecf56 100644
--- a/third_party/boringssl/mac-x86/crypto/aes/aes-586.S
+++ b/third_party/boringssl/mac-x86/crypto/aes/aes-586.S
@@ -3206,4 +3206,4 @@
 L_OPENSSL_ia32cap_P$non_lazy_ptr:
 .indirect_symbol	_OPENSSL_ia32cap_P
 .long	0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/aes/aesni-x86.S b/third_party/boringssl/mac-x86/crypto/aes/aesni-x86.S
index ac5504c..6e9784ed 100644
--- a/third_party/boringssl/mac-x86/crypto/aes/aesni-x86.S
+++ b/third_party/boringssl/mac-x86/crypto/aes/aesni-x86.S
@@ -2155,4 +2155,4 @@
 .byte	83,45,78,73,44,32,67,82,89,80,84,79,71,65,77,83
 .byte	32,98,121,32,60,97,112,112,114,111,64,111,112,101,110,115
 .byte	115,108,46,111,114,103,62,0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/aes/vpaes-x86.S b/third_party/boringssl/mac-x86/crypto/aes/vpaes-x86.S
index 8b3d993a..3728ccdc 100644
--- a/third_party/boringssl/mac-x86/crypto/aes/vpaes-x86.S
+++ b/third_party/boringssl/mac-x86/crypto/aes/vpaes-x86.S
@@ -634,4 +634,4 @@
 	popl	%ebx
 	popl	%ebp
 	ret
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/bn/bn-586.S b/third_party/boringssl/mac-x86/crypto/bn/bn-586.S
index 32e9e8e..0047706 100644
--- a/third_party/boringssl/mac-x86/crypto/bn/bn-586.S
+++ b/third_party/boringssl/mac-x86/crypto/bn/bn-586.S
@@ -1369,4 +1369,4 @@
 	popl	%ebx
 	popl	%ebp
 	ret
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/bn/co-586.S b/third_party/boringssl/mac-x86/crypto/bn/co-586.S
index 08f183b3..7827985d 100644
--- a/third_party/boringssl/mac-x86/crypto/bn/co-586.S
+++ b/third_party/boringssl/mac-x86/crypto/bn/co-586.S
@@ -1245,4 +1245,4 @@
 	popl	%edi
 	popl	%esi
 	ret
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/bn/x86-mont.S b/third_party/boringssl/mac-x86/crypto/bn/x86-mont.S
index 578373b..f008d36c 100644
--- a/third_party/boringssl/mac-x86/crypto/bn/x86-mont.S
+++ b/third_party/boringssl/mac-x86/crypto/bn/x86-mont.S
@@ -334,4 +334,4 @@
 .byte	54,44,32,67,82,89,80,84,79,71,65,77,83,32,98,121
 .byte	32,60,97,112,112,114,111,64,111,112,101,110,115,115,108,46
 .byte	111,114,103,62,0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/cpu-x86-asm.S b/third_party/boringssl/mac-x86/crypto/cpu-x86-asm.S
index e53351c1..701bc66 100644
--- a/third_party/boringssl/mac-x86/crypto/cpu-x86-asm.S
+++ b/third_party/boringssl/mac-x86/crypto/cpu-x86-asm.S
@@ -325,4 +325,4 @@
 L_OPENSSL_ia32cap_P$non_lazy_ptr:
 .indirect_symbol	_OPENSSL_ia32cap_P
 .long	0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/md5/md5-586.S b/third_party/boringssl/mac-x86/crypto/md5/md5-586.S
index 5aaed10..a77d6539 100644
--- a/third_party/boringssl/mac-x86/crypto/md5/md5-586.S
+++ b/third_party/boringssl/mac-x86/crypto/md5/md5-586.S
@@ -676,4 +676,4 @@
 	popl	%edi
 	popl	%esi
 	ret
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/modes/ghash-x86.S b/third_party/boringssl/mac-x86/crypto/modes/ghash-x86.S
index 9ad7fa9..231d63a 100644
--- a/third_party/boringssl/mac-x86/crypto/modes/ghash-x86.S
+++ b/third_party/boringssl/mac-x86/crypto/modes/ghash-x86.S
@@ -1250,4 +1250,4 @@
 .byte	82,89,80,84,79,71,65,77,83,32,98,121,32,60,97,112
 .byte	112,114,111,64,111,112,101,110,115,115,108,46,111,114,103,62
 .byte	0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/rc4/rc4-586.S b/third_party/boringssl/mac-x86/crypto/rc4/rc4-586.S
index 1a246e7..841fbda7 100644
--- a/third_party/boringssl/mac-x86/crypto/rc4/rc4-586.S
+++ b/third_party/boringssl/mac-x86/crypto/rc4/rc4-586.S
@@ -377,4 +377,4 @@
 L_OPENSSL_ia32cap_P$non_lazy_ptr:
 .indirect_symbol	_OPENSSL_ia32cap_P
 .long	0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/sha/sha1-586.S b/third_party/boringssl/mac-x86/crypto/sha/sha1-586.S
index 6b043ce..9bf1cd2 100644
--- a/third_party/boringssl/mac-x86/crypto/sha/sha1-586.S
+++ b/third_party/boringssl/mac-x86/crypto/sha/sha1-586.S
@@ -1377,4 +1377,4 @@
 .byte	102,111,114,109,32,102,111,114,32,120,56,54,44,32,67,82
 .byte	89,80,84,79,71,65,77,83,32,98,121,32,60,97,112,112
 .byte	114,111,64,111,112,101,110,115,115,108,46,111,114,103,62,0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/sha/sha256-586.S b/third_party/boringssl/mac-x86/crypto/sha/sha256-586.S
index 75390a9..0f75720 100644
--- a/third_party/boringssl/mac-x86/crypto/sha/sha256-586.S
+++ b/third_party/boringssl/mac-x86/crypto/sha/sha256-586.S
@@ -3344,4 +3344,4 @@
 	popl	%ebx
 	popl	%ebp
 	ret
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/mac-x86/crypto/sha/sha512-586.S b/third_party/boringssl/mac-x86/crypto/sha/sha512-586.S
index c7ecc91..8f0f1e7 100644
--- a/third_party/boringssl/mac-x86/crypto/sha/sha512-586.S
+++ b/third_party/boringssl/mac-x86/crypto/sha/sha512-586.S
@@ -562,4 +562,4 @@
 .byte	67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97
 .byte	112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103
 .byte	62,0
-#endif
\ No newline at end of file
+#endif
diff --git a/third_party/boringssl/update_gypi_and_asm.py b/third_party/boringssl/update_gypi_and_asm.py
index 8e61591..781f107e 100644
--- a/third_party/boringssl/update_gypi_and_asm.py
+++ b/third_party/boringssl/update_gypi_and_asm.py
@@ -13,12 +13,12 @@
 # OS_ARCH_COMBOS maps from OS and platform to the OpenSSL assembly "style" for
 # that platform and the extension used by asm files.
 OS_ARCH_COMBOS = [
-    ('linux', 'arm', 'elf', 'S'),
-    ('linux', 'x86', 'elf', 'S'),
-    ('linux', 'x86_64', 'elf', 'S'),
-    ('mac', 'x86', 'macosx', 'S'),
-    ('mac', 'x86_64', 'macosx', 'S'),
-    ('win', 'x86_64', 'masm', 'asm'),
+    ('linux', 'arm', 'elf', [''], 'S'),
+    ('linux', 'x86', 'elf', ['-fPIC'], 'S'),
+    ('linux', 'x86_64', 'elf', [''], 'S'),
+    ('mac', 'x86', 'macosx', ['-fPIC'], 'S'),
+    ('mac', 'x86_64', 'macosx', [''], 'S'),
+    ('win', 'x86_64', 'masm', [''], 'asm'),
 ]
 
 # NON_PERL_FILES enumerates assembly files that are not processed by the
@@ -152,7 +152,7 @@
   asmfiles = {}
 
   for osarch in OS_ARCH_COMBOS:
-    (osname, arch, perlasm_style, asm_ext) = osarch
+    (osname, arch, perlasm_style, extra_args, asm_ext) = osarch
     key = (osname, arch)
     outDir = '%s-%s' % key
 
@@ -165,7 +165,8 @@
       output = output.replace('${ASM_EXT}', asm_ext)
 
       if arch == ArchForAsmFilename(filename):
-        PerlAsm(output, perlasm['input'], perlasm_style, perlasm['extra_args'])
+        PerlAsm(output, perlasm['input'], perlasm_style,
+                perlasm['extra_args'] + extra_args)
         asmfiles.setdefault(key, []).append(output)
 
   for (key, non_perl_asm_files) in NON_PERL_FILES.iteritems():
@@ -206,7 +207,7 @@
     test_gypi.write(FILE_HEADER + '{\n  \'targets\': [\n')
 
     test_names = []
-    for test in test_c_files:
+    for test in sorted(test_c_files):
       test_name = 'boringssl_%s' % os.path.splitext(os.path.basename(test))[0]
       test_gypi.write("""    {
       'target_name': '%s',
diff --git a/third_party/libjingle/libjingle.gyp b/third_party/libjingle/libjingle.gyp
index 15383056..4ec4641 100644
--- a/third_party/libjingle/libjingle.gyp
+++ b/third_party/libjingle/libjingle.gyp
@@ -158,7 +158,7 @@
           'HAVE_OPENSSL_SSL_H',
         ],
         'dependencies': [
-          '../../third_party/openssl/openssl.gyp:openssl',
+          '../../third_party/boringssl/boringssl.gyp:boringssl',
         ],
       }, {
         'defines': [
diff --git a/third_party/libjingle/libjingle_nacl.gyp b/third_party/libjingle/libjingle_nacl.gyp
index dc9ef0b..8b1b498 100644
--- a/third_party/libjingle/libjingle_nacl.gyp
+++ b/third_party/libjingle/libjingle_nacl.gyp
@@ -25,7 +25,7 @@
         '<(DEPTH)/native_client/tools.gyp:prep_toolchain',
         '<(DEPTH)/native_client_sdk/native_client_sdk_untrusted.gyp:nacl_io_untrusted',
         '<(DEPTH)/third_party/expat/expat_nacl.gyp:expat_nacl',
-        '<(DEPTH)/third_party/openssl/openssl_nacl.gyp:openssl_nacl',
+        '<(DEPTH)/third_party/boringssl/boringssl_nacl.gyp:boringssl_nacl',
         'libjingle_p2p_constants_nacl',
       ],
       'defines': [
diff --git a/third_party/usrsctp/usrsctp.gyp b/third_party/usrsctp/usrsctp.gyp
index 56ea9ea..04952aba 100644
--- a/third_party/usrsctp/usrsctp.gyp
+++ b/third_party/usrsctp/usrsctp.gyp
@@ -28,7 +28,7 @@
           'SCTP_USE_OPENSSL_SHA1',
         ],
         'dependencies': [
-          '<(DEPTH)/third_party/openssl/openssl.gyp:openssl',
+          '<(DEPTH)/third_party/boringssl/boringssl.gyp:boringssl',
         ],
       },
       {  # else use_openssl==0, use NSS.