https://github.com/python/cpython/commit/c7dbdb5f6be5c6eba382a0aabe66a2e36c884fa1
commit: c7dbdb5f6be5c6eba382a0aabe66a2e36c884fa1
branch: main
author: Victor Stinner <[email protected]>
committer: vstinner <[email protected]>
date: 2026-09-18T15:10:42+02:00
summary:
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 d435a18c537a62a89a70005885e6e09f58997d8a).
Add a test on ssl.RAND_bytes(0).
files:
M Lib/test/test_ssl.py
M Modules/_ssl.c
diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py
index 37323b7ebc6b1a..abd7710a1d570a 100644
--- a/Lib/test/test_ssl.py
+++ b/Lib/test/test_ssl.py
@@ -469,6 +469,8 @@ def test_random(self):
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)
diff --git a/Modules/_ssl.c b/Modules/_ssl.c
index 9bddb9ce62d5b9..7a780dce967c79 100644
--- a/Modules/_ssl.c
+++ b/Modules/_ssl.c
@@ -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);
}
_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]