gh-155742: Use PyBytesWriter in PySSL_RAND() (#157731)

Replace soft deprecated PyBytes_FromStringAndSize() with
PyBytesWriter.

Remove 'pseudo' parameter of PySSL_RAND(): it's no longer needed since
ssl.RAND_pseudo_bytes() has been removed (in 2022,
commit d435a18c53).

Add a test on ssl.RAND_bytes(0).
This commit is contained in:
Victor Stinner authored and GitHub committed 2026-09-18 15:10:42 +02:00
1 parent 86c93a5b84
commit c7dbdb5f6b
2 files changed
+11 -14

No files matched your search

+2
View File
@@ -469,6 +469,8 @@ class BasicSocketTests(unittest.TestCase):
if v:
data = ssl.RAND_bytes(16)
self.assertEqual(len(data), 16)
self.assertEqual(ssl.RAND_bytes(0), b'')
else:
self.assertRaises(ssl.SSLError, ssl.RAND_bytes, 16)
+9 -14
View File
@@ -6243,10 +6243,9 @@ _ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
}
static PyObject *
PySSL_RAND(PyObject *module, int len, int pseudo)
PySSL_RAND(PyObject *module, int len)
{
int ok;
PyObject *bytes;
unsigned long err;
const char *errstr;
PyObject *v;
@@ -6256,20 +6255,16 @@ PySSL_RAND(PyObject *module, int len, int pseudo)
return NULL;
}
bytes = PyBytes_FromStringAndSize(NULL, len);
if (bytes == NULL)
PyBytesWriter *writer = PyBytesWriter_Create(len);
if (writer == NULL) {
return NULL;
if (pseudo) {
ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
if (ok == 0 || ok == 1)
return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
}
else {
ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
if (ok == 1)
return bytes;
ok = RAND_bytes(PyBytesWriter_GetData(writer), len);
if (ok == 1) {
return PyBytesWriter_Finish(writer);
}
Py_DECREF(bytes);
PyBytesWriter_Discard(writer);
err = ERR_get_error();
errstr = ERR_reason_error_string(err);
@@ -6294,7 +6289,7 @@ static PyObject *
_ssl_RAND_bytes_impl(PyObject *module, int n)
/*[clinic end generated code: output=977da635e4838bc7 input=2e78ce1e86336776]*/
{
return PySSL_RAND(module, n, 0);
return PySSL_RAND(module, n);
}