Merge pull request #1848 from reaperhulk/invalid-token

Twofactor invalid token
diff --git a/src/cryptography/hazmat/primitives/asymmetric/utils.py b/src/cryptography/hazmat/primitives/asymmetric/utils.py
index 71f4ff8..29390e4 100644
--- a/src/cryptography/hazmat/primitives/asymmetric/utils.py
+++ b/src/cryptography/hazmat/primitives/asymmetric/utils.py
@@ -4,6 +4,7 @@
 
 from __future__ import absolute_import, division, print_function
 
+from pyasn1.codec.ber import eoo
 from pyasn1.codec.der import decoder, encoder
 from pyasn1.error import PyAsn1Error
 from pyasn1.type import namedtype, univ
@@ -28,6 +29,12 @@
         raise ValueError(
             "The signature contains bytes after the end of the ASN.1 sequence."
         )
+    # pyasn1 can erroneously return this from top-level DER decoding.
+    # It's intended as a sentinel in recursive BER decoding, so it's
+    # returned even though an asn1Spec is provided.
+    if eoo.endOfOctets.isSameTypeWith(data) and data == eoo.endOfOctets:
+        raise ValueError("Invalid signature data. Unable to decode ASN.1")
+
     r = int(data.getComponentByName('r'))
     s = int(data.getComponentByName('s'))
     return (r, s)
diff --git a/tests/hazmat/primitives/test_asym_utils.py b/tests/hazmat/primitives/test_asym_utils.py
index bf55bad..c3fbedf 100644
--- a/tests/hazmat/primitives/test_asym_utils.py
+++ b/tests/hazmat/primitives/test_asym_utils.py
@@ -63,3 +63,8 @@
         # This byte sequence has an invalid ASN.1 sequence length as well as
         # an invalid integer length for the second integer.
         decode_rfc6979_signature(b"0\x07\x02\x01\x01\x02\x02\x01")
+
+    with pytest.raises(ValueError):
+        # This is the BER "end-of-contents octets," which pyasn1 is
+        # wrongly willing to return from top-level DER decoding.
+        decode_rfc6979_signature(b"\x00\x00")