From ab40497041a1fb2e367d8b7e9aad207a40f14bc7 Mon Sep 17 00:00:00 2001
From: Donald Stufft <donald.stufft@gmail.com>
Date: Sun, 24 Feb 2013 06:58:12 -0500
Subject: [PATCH] Properly handle strings with internal nul

The strings from NaCl can contain nul characters inside the string
and are not nul terminated. Using ffi.buffer with an explict
size will prevent issues here.
---
 nacl/hash.py   | 4 ++--
 nacl/random.py | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/nacl/hash.py b/nacl/hash.py
index 1f1e3ab3..cee6e7ce 100644
--- a/nacl/hash.py
+++ b/nacl/hash.py
@@ -8,7 +8,7 @@ def sha256(message, binary=False):
     digest = nacl.ffi.new("unsigned char[]", nacl.lib.crypto_hash_sha256_BYTES)
     if not nacl.lib.crypto_hash_sha256(digest, message, len(message)):
         raise CryptoError("Hashing failed")
-    digest = nacl.ffi.string(digest)
+    digest = nacl.ffi.buffer(digest, nacl.lib.crypto_hash_sha256_BYTES)[:]
 
     if binary:
         return digest
@@ -19,7 +19,7 @@ def sha512(message, binary=False):
     digest = nacl.ffi.new("unsigned char[]", nacl.lib.crypto_hash_sha512_BYTES)
     if not nacl.lib.crypto_hash_sha512(digest, message, len(message)):
         raise CryptoError("Hashing failed")
-    digest = nacl.ffi.string(digest)
+    digest = nacl.ffi.buffer(digest, nacl.lib.crypto_hash_sha512_BYTES)[:]
 
     if binary:
         return digest
diff --git a/nacl/random.py b/nacl/random.py
index 18038a63..ded56fae 100644
--- a/nacl/random.py
+++ b/nacl/random.py
@@ -4,4 +4,4 @@ from . import nacl
 def random(size=32):
     data = nacl.ffi.new("unsigned char[]", size)
     nacl.lib.randombytes(data, size)
-    return nacl.ffi.string(data)
+    return nacl.ffi.buffer(data, size)[:]
-- 
GitLab