feat: Implement ES256 for JWT verification (#340)

feat: Implement EC256 for JWT verification
diff --git a/google/auth/crypt/__init__.py b/google/auth/crypt/__init__.py
index 39929fa..15ac950 100644
--- a/google/auth/crypt/__init__.py
+++ b/google/auth/crypt/__init__.py
@@ -31,6 +31,10 @@
     private_key = open('private_key.pem').read()
     signer = crypt.RSASigner.from_string(private_key)
     signature = signer.sign(message)
+
+The code above also works for :class:`ES256Signer` and :class:`ES256Verifier`.
+Note that these two classes are only available if your `cryptography` dependency
+version is at least 1.4.0.
 """
 
 import six
@@ -38,8 +42,23 @@
 from google.auth.crypt import base
 from google.auth.crypt import rsa
 
+try:
+    from google.auth.crypt import es256
+except ImportError:  # pragma: NO COVER
+    es256 = None
 
-__all__ = ["RSASigner", "RSAVerifier", "Signer", "Verifier"]
+if es256 is not None:  # pragma: NO COVER
+    __all__ = [
+        "ES256Signer",
+        "ES256Verifier",
+        "RSASigner",
+        "RSAVerifier",
+        "Signer",
+        "Verifier",
+    ]
+else:  # pragma: NO COVER
+    __all__ = ["RSASigner", "RSAVerifier", "Signer", "Verifier"]
+
 
 # Aliases to maintain the v1.0.0 interface, as the crypt module was split
 # into submodules.
@@ -48,9 +67,13 @@
 RSASigner = rsa.RSASigner
 RSAVerifier = rsa.RSAVerifier
 
+if es256 is not None:  # pragma: NO COVER
+    ES256Signer = es256.ES256Signer
+    ES256Verifier = es256.ES256Verifier
 
-def verify_signature(message, signature, certs):
-    """Verify an RSA cryptographic signature.
+
+def verify_signature(message, signature, certs, verifier_cls=rsa.RSAVerifier):
+    """Verify an RSA or ECDSA cryptographic signature.
 
     Checks that the provided ``signature`` was generated from ``bytes`` using
     the private key associated with the ``cert``.
@@ -60,6 +83,9 @@
         signature (Union[str, bytes]): The cryptographic signature to check.
         certs (Union[Sequence, str, bytes]): The certificate or certificates
             to use to check the signature.
+        verifier_cls (Optional[~google.auth.crypt.base.Signer]): Which verifier
+            class to use for verification. This can be used to select different
+            algorithms, such as RSA or ECDSA. Default value is :class:`RSAVerifier`.
 
     Returns:
         bool: True if the signature is valid, otherwise False.
@@ -68,7 +94,7 @@
         certs = [certs]
 
     for cert in certs:
-        verifier = rsa.RSAVerifier.from_string(cert)
+        verifier = verifier_cls.from_string(cert)
         if verifier.verify(message, signature):
             return True
     return False
diff --git a/google/auth/crypt/es256.py b/google/auth/crypt/es256.py
new file mode 100644
index 0000000..5bfd57f
--- /dev/null
+++ b/google/auth/crypt/es256.py
@@ -0,0 +1,145 @@
+# Copyright 2017 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""ECDSA (ES256) verifier and signer that use the ``cryptography`` library.
+"""
+
+import cryptography.exceptions
+from cryptography.hazmat import backends
+from cryptography.hazmat.primitives import hashes
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import ec
+from cryptography.hazmat.primitives.asymmetric import padding
+import cryptography.x509
+import pkg_resources
+
+from google.auth import _helpers
+from google.auth.crypt import base
+
+_IMPORT_ERROR_MSG = (
+    "cryptography>=1.4.0 is required to use cryptography-based ECDSA " "algorithms"
+)
+
+try:  # pragma: NO COVER
+    release = pkg_resources.get_distribution("cryptography").parsed_version
+    if release < pkg_resources.parse_version("1.4.0"):
+        raise ImportError(_IMPORT_ERROR_MSG)
+except pkg_resources.DistributionNotFound:  # pragma: NO COVER
+    raise ImportError(_IMPORT_ERROR_MSG)
+
+
+_CERTIFICATE_MARKER = b"-----BEGIN CERTIFICATE-----"
+_BACKEND = backends.default_backend()
+_PADDING = padding.PKCS1v15()
+
+
+class ES256Verifier(base.Verifier):
+    """Verifies ECDSA cryptographic signatures using public keys.
+
+    Args:
+        public_key (
+                cryptography.hazmat.primitives.asymmetric.ec.ECDSAPublicKey):
+            The public key used to verify signatures.
+    """
+
+    def __init__(self, public_key):
+        self._pubkey = public_key
+
+    @_helpers.copy_docstring(base.Verifier)
+    def verify(self, message, signature):
+        message = _helpers.to_bytes(message)
+        try:
+            self._pubkey.verify(signature, message, ec.ECDSA(hashes.SHA256()))
+            return True
+        except (ValueError, cryptography.exceptions.InvalidSignature):
+            return False
+
+    @classmethod
+    def from_string(cls, public_key):
+        """Construct an Verifier instance from a public key or public
+        certificate string.
+
+        Args:
+            public_key (Union[str, bytes]): The public key in PEM format or the
+                x509 public key certificate.
+
+        Returns:
+            Verifier: The constructed verifier.
+
+        Raises:
+            ValueError: If the public key can't be parsed.
+        """
+        public_key_data = _helpers.to_bytes(public_key)
+
+        if _CERTIFICATE_MARKER in public_key_data:
+            cert = cryptography.x509.load_pem_x509_certificate(
+                public_key_data, _BACKEND
+            )
+            pubkey = cert.public_key()
+
+        else:
+            pubkey = serialization.load_pem_public_key(public_key_data, _BACKEND)
+
+        return cls(pubkey)
+
+
+class ES256Signer(base.Signer, base.FromServiceAccountMixin):
+    """Signs messages with an ECDSA private key.
+
+    Args:
+        private_key (
+                cryptography.hazmat.primitives.asymmetric.ec.ECDSAPrivateKey):
+            The private key to sign with.
+        key_id (str): Optional key ID used to identify this private key. This
+            can be useful to associate the private key with its associated
+            public key or certificate.
+    """
+
+    def __init__(self, private_key, key_id=None):
+        self._key = private_key
+        self._key_id = key_id
+
+    @property
+    @_helpers.copy_docstring(base.Signer)
+    def key_id(self):
+        return self._key_id
+
+    @_helpers.copy_docstring(base.Signer)
+    def sign(self, message):
+        message = _helpers.to_bytes(message)
+        return self._key.sign(message, ec.ECDSA(hashes.SHA256()))
+
+    @classmethod
+    def from_string(cls, key, key_id=None):
+        """Construct a RSASigner from a private key in PEM format.
+
+        Args:
+            key (Union[bytes, str]): Private key in PEM format.
+            key_id (str): An optional key id used to identify the private key.
+
+        Returns:
+            google.auth.crypt._cryptography_rsa.RSASigner: The
+            constructed signer.
+
+        Raises:
+            ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode).
+            UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded
+                into a UTF-8 ``str``.
+            ValueError: If ``cryptography`` "Could not deserialize key data."
+        """
+        key = _helpers.to_bytes(key)
+        private_key = serialization.load_pem_private_key(
+            key, password=None, backend=_BACKEND
+        )
+        return cls(private_key, key_id=key_id)