We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Empty subject or issuer in x.509 certificates throws Unknown OpenSSL error.
When trying to build a x509 certificate with an empty string as issuer or subject name, an unknown OpenSSL error is thrown. Maybe that should be handled differently.

**Tested on:**
```
Ubuntu 16.04.2 LTS
OpenSSL 1.0.2g  1 Mar 2016
cryptography 1.9
```
```
macOS Sierra 10.12.5
OpenSSL 0.9.8zh 14 Jan 2016
cryptography 1.9
```
**To reproduce:**
```
$ python openssl_error.py
```
```
Traceback (most recent call last):
  File "openssl_error.py", line 19, in <module>
    cert = builder.sign(private_key, hashes.SHA256(), default_backend())
  File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/x509/base.py", line 564, in sign
    return backend.create_x509_certificate(self, private_key, algorithm)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 746, in create_x509_certificate
    x509_cert, _encode_name_gc(self, builder._subject_name)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/encode_asn1.py", line 103, in _encode_name_gc
    subject = _encode_name(backend, attributes)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/encode_asn1.py", line 97, in _encode_name
    backend.openssl_assert(res == 1)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 107, in openssl_assert
    return binding._openssl_assert(self._lib, ok)
  File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 75, in _openssl_assert
    errors_with_text
cryptography.exceptions.InternalError: Unknown OpenSSL error. This error is commonly encountered when another library is not cleaning up the OpenSSL error stack. If you are using cryptography with another library that uses OpenSSL try disabling it before reporting a bug. Otherwise please file an issue at https://github.com/pyca/cryptography/issues with information on how to reproduce this. ([_OpenSSLErrorWithText(code=218603672L, lib=13, func=122, reason=152, reason_text='error:0D07A098:asn1 encoding routines:ASN1_mbstring_ncopy:string too short')])
```

**openssl_error.py**
```
import six
import datetime
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import hashes

builder = x509.CertificateBuilder()
builder = builder.serial_number(x509.random_serial_number())
builder = builder.not_valid_before(datetime.datetime.today())
builder = builder.not_valid_after(datetime.datetime.today())

# Empty strings here seems to make it crash.
builder = builder.subject_name(x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, six.u('')), ]))
builder = builder.issuer_name(x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, six.u('')), ]))

private_key = rsa.generate_private_key(65537, 2048, default_backend())
builder = builder.public_key(private_key.public_key())
cert = builder.sign(private_key, hashes.SHA256(), default_backend())
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/cryptography/x509/name.py`
Content:
```
1 # This file is dual licensed under the terms of the Apache License, Version
2 # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3 # for complete details.
4 
5 from __future__ import absolute_import, division, print_function
6 
7 import six
8 
9 from cryptography import utils
10 from cryptography.x509.oid import NameOID, ObjectIdentifier
11 
12 
13 class NameAttribute(object):
14     def __init__(self, oid, value):
15         if not isinstance(oid, ObjectIdentifier):
16             raise TypeError(
17                 "oid argument must be an ObjectIdentifier instance."
18             )
19 
20         if not isinstance(value, six.text_type):
21             raise TypeError(
22                 "value argument must be a text type."
23             )
24 
25         if oid == NameOID.COUNTRY_NAME and len(value.encode("utf8")) != 2:
26             raise ValueError(
27                 "Country name must be a 2 character country code"
28             )
29 
30         self._oid = oid
31         self._value = value
32 
33     oid = utils.read_only_property("_oid")
34     value = utils.read_only_property("_value")
35 
36     def __eq__(self, other):
37         if not isinstance(other, NameAttribute):
38             return NotImplemented
39 
40         return (
41             self.oid == other.oid and
42             self.value == other.value
43         )
44 
45     def __ne__(self, other):
46         return not self == other
47 
48     def __hash__(self):
49         return hash((self.oid, self.value))
50 
51     def __repr__(self):
52         return "<NameAttribute(oid={0.oid}, value={0.value!r})>".format(self)
53 
54 
55 class RelativeDistinguishedName(object):
56     def __init__(self, attributes):
57         attributes = frozenset(attributes)
58         if not attributes:
59             raise ValueError("a relative distinguished name cannot be empty")
60         if not all(isinstance(x, NameAttribute) for x in attributes):
61             raise TypeError("attributes must be an iterable of NameAttribute")
62 
63         self._attributes = attributes
64 
65     def get_attributes_for_oid(self, oid):
66         return [i for i in self if i.oid == oid]
67 
68     def __eq__(self, other):
69         if not isinstance(other, RelativeDistinguishedName):
70             return NotImplemented
71 
72         return self._attributes == other._attributes
73 
74     def __ne__(self, other):
75         return not self == other
76 
77     def __hash__(self):
78         return hash(self._attributes)
79 
80     def __iter__(self):
81         return iter(self._attributes)
82 
83     def __len__(self):
84         return len(self._attributes)
85 
86     def __repr__(self):
87         return "<RelativeDistinguishedName({0!r})>".format(list(self))
88 
89 
90 class Name(object):
91     def __init__(self, attributes):
92         attributes = list(attributes)
93         if all(isinstance(x, NameAttribute) for x in attributes):
94             self._attributes = [
95                 RelativeDistinguishedName([x]) for x in attributes
96             ]
97         elif all(isinstance(x, RelativeDistinguishedName) for x in attributes):
98             self._attributes = attributes
99         else:
100             raise TypeError(
101                 "attributes must be a list of NameAttribute"
102                 " or a list RelativeDistinguishedName"
103             )
104 
105     def get_attributes_for_oid(self, oid):
106         return [i for i in self if i.oid == oid]
107 
108     @property
109     def rdns(self):
110         return self._attributes
111 
112     def public_bytes(self, backend):
113         return backend.x509_name_bytes(self)
114 
115     def __eq__(self, other):
116         if not isinstance(other, Name):
117             return NotImplemented
118 
119         return self._attributes == other._attributes
120 
121     def __ne__(self, other):
122         return not self == other
123 
124     def __hash__(self):
125         # TODO: this is relatively expensive, if this looks like a bottleneck
126         # for you, consider optimizing!
127         return hash(tuple(self._attributes))
128 
129     def __iter__(self):
130         for rdn in self._attributes:
131             for ava in rdn:
132                 yield ava
133 
134     def __len__(self):
135         return sum(len(rdn) for rdn in self._attributes)
136 
137     def __repr__(self):
138         return "<Name({0!r})>".format(list(self))
139
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/cryptography/x509/name.py b/src/cryptography/x509/name.py
--- a/src/cryptography/x509/name.py
+++ b/src/cryptography/x509/name.py
@@ -27,6 +27,9 @@
                 "Country name must be a 2 character country code"
             )
 
+        if len(value) == 0:
+            raise ValueError("Value cannot be an empty string")
+
         self._oid = oid
         self._value = value

{"golden_diff": "diff --git a/src/cryptography/x509/name.py b/src/cryptography/x509/name.py\n--- a/src/cryptography/x509/name.py\n+++ b/src/cryptography/x509/name.py\n@@ -27,6 +27,9 @@\n                 \"Country name must be a 2 character country code\"\n             )\n \n+        if len(value) == 0:\n+            raise ValueError(\"Value cannot be an empty string\")\n+\n         self._oid = oid\n         self._value = value\n", "issue": "Empty subject or issuer in x.509 certificates throws Unknown OpenSSL error.\nWhen trying to build a x509 certificate with an empty string as issuer or subject name, an unknown OpenSSL error is thrown. Maybe that should be handled differently.\r\n\r\n**Tested on:**\r\n```\r\nUbuntu 16.04.2 LTS\r\nOpenSSL 1.0.2g  1 Mar 2016\r\ncryptography 1.9\r\n```\r\n```\r\nmacOS Sierra 10.12.5\r\nOpenSSL 0.9.8zh 14 Jan 2016\r\ncryptography 1.9\r\n```\r\n**To reproduce:**\r\n```\r\n$ python openssl_error.py\r\n```\r\n```\r\nTraceback (most recent call last):\r\n  File \"openssl_error.py\", line 19, in <module>\r\n    cert = builder.sign(private_key, hashes.SHA256(), default_backend())\r\n  File \"/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/x509/base.py\", line 564, in sign\r\n    return backend.create_x509_certificate(self, private_key, algorithm)\r\n  File \"/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py\", line 746, in create_x509_certificate\r\n    x509_cert, _encode_name_gc(self, builder._subject_name)\r\n  File \"/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/encode_asn1.py\", line 103, in _encode_name_gc\r\n    subject = _encode_name(backend, attributes)\r\n  File \"/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/encode_asn1.py\", line 97, in _encode_name\r\n    backend.openssl_assert(res == 1)\r\n  File \"/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py\", line 107, in openssl_assert\r\n    return binding._openssl_assert(self._lib, ok)\r\n  File \"/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py\", line 75, in _openssl_assert\r\n    errors_with_text\r\ncryptography.exceptions.InternalError: Unknown OpenSSL error. This error is commonly encountered when another library is not cleaning up the OpenSSL error stack. If you are using cryptography with another library that uses OpenSSL try disabling it before reporting a bug. Otherwise please file an issue at https://github.com/pyca/cryptography/issues with information on how to reproduce this. ([_OpenSSLErrorWithText(code=218603672L, lib=13, func=122, reason=152, reason_text='error:0D07A098:asn1 encoding routines:ASN1_mbstring_ncopy:string too short')])\r\n```\r\n\r\n**openssl_error.py**\r\n```\r\nimport six\r\nimport datetime\r\nfrom cryptography import x509\r\nfrom cryptography.hazmat.backends import default_backend\r\nfrom cryptography.hazmat.primitives.asymmetric import rsa\r\nfrom cryptography.hazmat.primitives import hashes\r\n\r\nbuilder = x509.CertificateBuilder()\r\nbuilder = builder.serial_number(x509.random_serial_number())\r\nbuilder = builder.not_valid_before(datetime.datetime.today())\r\nbuilder = builder.not_valid_after(datetime.datetime.today())\r\n\r\n# Empty strings here seems to make it crash.\r\nbuilder = builder.subject_name(x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, six.u('')), ]))\r\nbuilder = builder.issuer_name(x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, six.u('')), ]))\r\n\r\nprivate_key = rsa.generate_private_key(65537, 2048, default_backend())\r\nbuilder = builder.public_key(private_key.public_key())\r\ncert = builder.sign(private_key, hashes.SHA256(), default_backend())\r\n```\n", "before_files": [{"content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom __future__ import absolute_import, division, print_function\n\nimport six\n\nfrom cryptography import utils\nfrom cryptography.x509.oid import NameOID, ObjectIdentifier\n\n\nclass NameAttribute(object):\n    def __init__(self, oid, value):\n        if not isinstance(oid, ObjectIdentifier):\n            raise TypeError(\n                \"oid argument must be an ObjectIdentifier instance.\"\n            )\n\n        if not isinstance(value, six.text_type):\n            raise TypeError(\n                \"value argument must be a text type.\"\n            )\n\n        if oid == NameOID.COUNTRY_NAME and len(value.encode(\"utf8\")) != 2:\n            raise ValueError(\n                \"Country name must be a 2 character country code\"\n            )\n\n        self._oid = oid\n        self._value = value\n\n    oid = utils.read_only_property(\"_oid\")\n    value = utils.read_only_property(\"_value\")\n\n    def __eq__(self, other):\n        if not isinstance(other, NameAttribute):\n            return NotImplemented\n\n        return (\n            self.oid == other.oid and\n            self.value == other.value\n        )\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __hash__(self):\n        return hash((self.oid, self.value))\n\n    def __repr__(self):\n        return \"<NameAttribute(oid={0.oid}, value={0.value!r})>\".format(self)\n\n\nclass RelativeDistinguishedName(object):\n    def __init__(self, attributes):\n        attributes = frozenset(attributes)\n        if not attributes:\n            raise ValueError(\"a relative distinguished name cannot be empty\")\n        if not all(isinstance(x, NameAttribute) for x in attributes):\n            raise TypeError(\"attributes must be an iterable of NameAttribute\")\n\n        self._attributes = attributes\n\n    def get_attributes_for_oid(self, oid):\n        return [i for i in self if i.oid == oid]\n\n    def __eq__(self, other):\n        if not isinstance(other, RelativeDistinguishedName):\n            return NotImplemented\n\n        return self._attributes == other._attributes\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __hash__(self):\n        return hash(self._attributes)\n\n    def __iter__(self):\n        return iter(self._attributes)\n\n    def __len__(self):\n        return len(self._attributes)\n\n    def __repr__(self):\n        return \"<RelativeDistinguishedName({0!r})>\".format(list(self))\n\n\nclass Name(object):\n    def __init__(self, attributes):\n        attributes = list(attributes)\n        if all(isinstance(x, NameAttribute) for x in attributes):\n            self._attributes = [\n                RelativeDistinguishedName([x]) for x in attributes\n            ]\n        elif all(isinstance(x, RelativeDistinguishedName) for x in attributes):\n            self._attributes = attributes\n        else:\n            raise TypeError(\n                \"attributes must be a list of NameAttribute\"\n                \" or a list RelativeDistinguishedName\"\n            )\n\n    def get_attributes_for_oid(self, oid):\n        return [i for i in self if i.oid == oid]\n\n    @property\n    def rdns(self):\n        return self._attributes\n\n    def public_bytes(self, backend):\n        return backend.x509_name_bytes(self)\n\n    def __eq__(self, other):\n        if not isinstance(other, Name):\n            return NotImplemented\n\n        return self._attributes == other._attributes\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __hash__(self):\n        # TODO: this is relatively expensive, if this looks like a bottleneck\n        # for you, consider optimizing!\n        return hash(tuple(self._attributes))\n\n    def __iter__(self):\n        for rdn in self._attributes:\n            for ava in rdn:\n                yield ava\n\n    def __len__(self):\n        return sum(len(rdn) for rdn in self._attributes)\n\n    def __repr__(self):\n        return \"<Name({0!r})>\".format(list(self))\n", "path": "src/cryptography/x509/name.py"}], "after_files": [{"content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom __future__ import absolute_import, division, print_function\n\nimport six\n\nfrom cryptography import utils\nfrom cryptography.x509.oid import NameOID, ObjectIdentifier\n\n\nclass NameAttribute(object):\n    def __init__(self, oid, value):\n        if not isinstance(oid, ObjectIdentifier):\n            raise TypeError(\n                \"oid argument must be an ObjectIdentifier instance.\"\n            )\n\n        if not isinstance(value, six.text_type):\n            raise TypeError(\n                \"value argument must be a text type.\"\n            )\n\n        if oid == NameOID.COUNTRY_NAME and len(value.encode(\"utf8\")) != 2:\n            raise ValueError(\n                \"Country name must be a 2 character country code\"\n            )\n\n        if len(value) == 0:\n            raise ValueError(\"Value cannot be an empty string\")\n\n        self._oid = oid\n        self._value = value\n\n    oid = utils.read_only_property(\"_oid\")\n    value = utils.read_only_property(\"_value\")\n\n    def __eq__(self, other):\n        if not isinstance(other, NameAttribute):\n            return NotImplemented\n\n        return (\n            self.oid == other.oid and\n            self.value == other.value\n        )\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __hash__(self):\n        return hash((self.oid, self.value))\n\n    def __repr__(self):\n        return \"<NameAttribute(oid={0.oid}, value={0.value!r})>\".format(self)\n\n\nclass RelativeDistinguishedName(object):\n    def __init__(self, attributes):\n        attributes = frozenset(attributes)\n        if not attributes:\n            raise ValueError(\"a relative distinguished name cannot be empty\")\n        if not all(isinstance(x, NameAttribute) for x in attributes):\n            raise TypeError(\"attributes must be an iterable of NameAttribute\")\n\n        self._attributes = attributes\n\n    def get_attributes_for_oid(self, oid):\n        return [i for i in self if i.oid == oid]\n\n    def __eq__(self, other):\n        if not isinstance(other, RelativeDistinguishedName):\n            return NotImplemented\n\n        return self._attributes == other._attributes\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __hash__(self):\n        return hash(self._attributes)\n\n    def __iter__(self):\n        return iter(self._attributes)\n\n    def __len__(self):\n        return len(self._attributes)\n\n    def __repr__(self):\n        return \"<RelativeDistinguishedName({0!r})>\".format(list(self))\n\n\nclass Name(object):\n    def __init__(self, attributes):\n        attributes = list(attributes)\n        if all(isinstance(x, NameAttribute) for x in attributes):\n            self._attributes = [\n                RelativeDistinguishedName([x]) for x in attributes\n            ]\n        elif all(isinstance(x, RelativeDistinguishedName) for x in attributes):\n            self._attributes = attributes\n        else:\n            raise TypeError(\n                \"attributes must be a list of NameAttribute\"\n                \" or a list RelativeDistinguishedName\"\n            )\n\n    def get_attributes_for_oid(self, oid):\n        return [i for i in self if i.oid == oid]\n\n    @property\n    def rdns(self):\n        return self._attributes\n\n    def public_bytes(self, backend):\n        return backend.x509_name_bytes(self)\n\n    def __eq__(self, other):\n        if not isinstance(other, Name):\n            return NotImplemented\n\n        return self._attributes == other._attributes\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __hash__(self):\n        # TODO: this is relatively expensive, if this looks like a bottleneck\n        # for you, consider optimizing!\n        return hash(tuple(self._attributes))\n\n    def __iter__(self):\n        for rdn in self._attributes:\n            for ava in rdn:\n                yield ava\n\n    def __len__(self):\n        return sum(len(rdn) for rdn in self._attributes)\n\n    def __repr__(self):\n        return \"<Name({0!r})>\".format(list(self))\n", "path": "src/cryptography/x509/name.py"}]}