1 from ctypescrypto import libcrypto
2 from ctypes import c_char_p, c_void_p, c_int, string_at, c_long,POINTER,byref, create_string_buffer
5 Provides interface to OpenSSL memory bios
6 use str() or unicode() to get contents of writable bio
7 use bio member to pass to libcrypto function
9 def __init__(self,data=None):
10 """ If data is specified, creates read-only BIO. If data is
11 None, creates writable BIO, contents of which can be retrieved by str() or unicode()
14 method=libcrypto.BIO_s_mem()
15 self.bio=libcrypto.BIO_new(method)
17 self.bio=libcrypto.BIO_new_mem_buf(c_char_p(data),len(data))
20 Cleans up memory used by bio
22 libcrypto.BIO_free(self.bio)
26 Returns current contents of buffer as byte string
29 l=libcrypto.BIO_ctrl(self.bio,3,0,byref(p))
31 def __unicode__(self):
33 Attempts to interpret current contents of buffer as UTF-8 string and convert it to unicode
35 return str(self).decode("utf-8")
36 def read(self,length=None):
38 Reads data from readble BIO. For test purposes.
39 @param length - if specifed, limits amount of data read. If not BIO is read until end of buffer
41 if not length is None:
42 if type(length)!=type(0):
43 raise TypeError("length to read should be number")
44 buf=create_string_buffer(length)
45 readbytes=libcrypto.BIO_read(self.bio,buf,length)
47 raise NotImplementedError("Function is not supported by this BIO")
52 return buf.raw[:readbytes]
54 buf=create_string_buffer(1024)
58 r=libcrypto.BIO_read(self.bio,buf,1024)
60 raise NotImplementedError("Function is not supported by this BIO")
69 Writes data to writable bio. For test purposes
71 if isinstance(data,unicode):
72 data=data.encode("utf-8")
73 r=libcrypto.BIO_write(self.bio,data,len(data))
75 raise NotImplementedError("Function not supported by this BIO")
77 raise IOError("Not all data were successfully written")
80 Resets the read-only bio to start and discards all data from writable bio
82 libcrypto.BIO_ctrl(self.bio,1,0,None)
83 libcrypto.BIO_s_mem.restype=c_void_p
84 libcrypto.BIO_new.restype=c_void_p
85 libcrypto.BIO_new.argtypes=(c_void_p,)
86 libcrypto.BIO_ctrl.restype=c_long
87 libcrypto.BIO_ctrl.argtypes=(c_void_p,c_int,c_long,POINTER(c_char_p))
88 libcrypto.BIO_read.argtypes=(c_void_p,c_char_p,c_int)
89 libcrypto.BIO_write.argtypes=(c_void_p,c_char_p,c_int)
90 libcrypto.BIO_free.argtypes=(c_void_p,)
91 libcrypto.BIO_new_mem_buf.restype=c_void_p
92 libcrypto.BIO_new_mem_buf.argtypes=(c_char_p,c_int)
93 libcrypto.BIO_ctrl.argtypes=(c_void_p,c_int,c_int,c_void_p)