Beispiel #1
0
def prettify_string(rough_string):
    """Return an XML string with added whitespace for legibility,
    using .NET infrastructure.

    Parameters
    ----------
    rough_string : str
        XML string
    """
    mStream = MemoryStream()
    writer = XmlTextWriter(mStream, Encoding.UTF8)
    document = XmlDocument()

    document.LoadXml(rough_string)

    writer.Formatting = Formatting.Indented

    writer.WriteStartDocument()
    document.WriteContentTo(writer)
    writer.Flush()
    mStream.Flush()

    mStream.Position = 0

    sReader = StreamReader(mStream)

    formattedXml = sReader.ReadToEnd()

    return formattedXml
Beispiel #2
0
    def serialize(self,
                  document,
                  indent=False,
                  encoding=bridge.ENCODING,
                  prefixes=None,
                  omit_declaration=False):
        doc = XmlDocument()
        doc.LoadXml(self.__start_document(document))
        if document.xml_text:
            doc.DocumentElement.AppendChild(
                doc.CreateTextNode(document.xml_text))
        self.__serialize_element(doc, doc.DocumentElement, document)

        settings = XmlWriterSettings()
        settings.Indent = indent
        settings.Encoding = Encoding.GetEncoding(encoding)
        settings.OmitXmlDeclaration = omit_declaration

        ms = MemoryStream()
        xw = XmlWriter.Create(ms, settings)
        doc.Save(xw)
        sr = StreamReader(ms)
        ms.Seek(0, SeekOrigin.Begin)
        content = sr.ReadToEnd()
        ms.Close()

        return content
Beispiel #3
0
    def encode_job(self, job):
        random_bytes = Array.CreateInstance(Byte, 2)
        Random().NextBytes(random_bytes)

        data = Encoding.UTF8.GetBytes(JavaScriptSerializer().Serialize(job))
        with MemoryStream(data.Length) as initialStream:
            initialStream.Write(data, 0, data.Length)
            initialStream.Seek(0, SeekOrigin.Begin)
            with MemoryStream() as resultStream:
                with GZipStream(resultStream,
                                CompressionMode.Compress) as zipStream:
                    buffer = Array.CreateInstance(Byte, 4096)
                    bytesRead = initialStream.Read(buffer, 0, buffer.Length)
                    zipStream.Write(buffer, 0, bytesRead)
                    while bytesRead != 0:
                        bytesRead = initialStream.Read(buffer, 0,
                                                       buffer.Length)
                        zipStream.Write(buffer, 0, bytesRead)

                result = resultStream.ToArray()
                result[:2] = random_bytes
                return {
                    Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(
                        0, 8):
                    Convert.ToBase64String(Guid.NewGuid().ToByteArray()),
                    "data":
                    Convert.ToBase64String(result)
                }
Beispiel #4
0
    def _dotnet_decrypt(data, key):
        """Perform decrypting of provided encrypted data.

        If 'digest' is True data must be hex digest, otherwise data should be
        encrypted bytes.

        This function is symmetrical with encrypt function.
        """
        data = Array[Byte](map(Byte, map(ord, data)))
        key = Array[Byte](map(Byte, key))
        rm = RijndaelManaged()
        dec_transform = rm.CreateDecryptor(key, Array[Byte](_vector))

        mem = MemoryStream()
        cs = CryptoStream(mem, dec_transform, CryptoStreamMode.Write)
        cs.Write(data, 0, data.Length)
        cs.FlushFinalBlock()

        mem.Position = 0
        decrypted = Array.CreateInstance(Byte, mem.Length)
        mem.Read(decrypted, 0, decrypted.Length)

        cs.Close()
        utfEncoder = UTF8Encoding()
        return utfEncoder.GetString(decrypted)
    def get_idf(self, args, request, uiApplication):
        '''
        deserializes a ModelSnapshot from the POST and then uses the DPV
        idf writer to export the ModelSnapshot as an IDF file.
        '''
        clr.AddReference('DpvApplication')
        clr.AddReference('DesignPerformanceViewer')
        from DesignPerformanceViewer.Model import ModelSnapshotImporter
        from DesignPerformanceViewer.EnergyPlusCalculation import IdfWriter
        from System.IO import StreamReader
        from System.IO import MemoryStream
        from System.Text import Encoding

        if request.HttpMethod == 'POST':
            body = request.InputStream
            encoding = request.ContentEncoding
            reader = StreamReader(body, encoding)
            snapshot_xml = reader.ReadToEnd()

            snapshot = ModelSnapshotImporter().Import(snapshot_xml)
        elif request.HttpMethod == 'GET':
            snapshot = self.take_snapshot(uiApplication)
        else:
            return (404, 'text/plain',
                    'invalid HTTP method: ' + request.HttpMethod)
        ms = MemoryStream()
        writer = IdfWriter(ms, Encoding.UTF8)
        writer.Write(snapshot)
        ms.Position = 0
        idf = StreamReader(ms, Encoding.UTF8).ReadToEnd()
        print 'idf=', idf
        return (200, 'text/plain', idf)
Beispiel #6
0
def createDatasetWithCompoundType(h5file):

    mtype = createMemType()
    ftype = createFileType()

    npoints = 4
    shape = Array[Int64]((npoints, ))
    dspace = H5S.create_simple(shape.Length, shape)

    dset = H5D.create(h5file, 'DS1', ftype, dspace)

    ms = MemoryStream()
    writer = BinaryWriter(ms)

    writer.Write(Int32(1153))
    s = 'Exterior (static)'
    if IntPtr.Size == 8:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64())
    else:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32())
    writer.Write(Double(53.23))
    writer.Write(Double(24.57))

    writer.Write(Int32(1184))
    s = 'Intake'
    if IntPtr.Size == 8:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64())
    else:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32())
    writer.Write(Double(55.12))
    writer.Write(Double(22.95))

    writer.Write(Int32(1027))
    s = 'Intake manifold'
    if IntPtr.Size == 8:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64())
    else:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32())
    writer.Write(Double(103.55))
    writer.Write(Double(31.23))

    writer.Write(Int32(1313))
    s = 'Exhaust manifold'
    if IntPtr.Size == 8:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64())
    else:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32())
    writer.Write(Double(1252.89))
    writer.Write(Double(84.11))

    byteArray = ms.ToArray()

    H5D.write(dset, mtype, H5Array[Byte](byteArray))

    H5S.close(dspace)
    H5T.close(ftype)
    H5T.close(mtype)

    return dset
Beispiel #7
0
def stream_bitmap(imagebytes):
    memoryStream = MemoryStream(imagebytes)
    memoryStream.Position = 0
    image = Imaging.BitmapImage()
    image.BeginInit()
    image.StreamSource = memoryStream
    image.CacheOption = Imaging.BitmapCacheOption.OnLoad
    image.EndInit()
    return image
    def pick(snip=False):
        snipper = PickSnipTool(PickSnipTool.take_screenshot(), snip=snip)

        while True:
            result = snipper.ShowDialog()
            if result in [DialogResult.OK, DialogResult.Cancel]:
                break
            if snipper.mouse_down_seconds == 1:
                Mouse.Instance.Click(snipper.mouse_down)
                time.sleep(0.5)
            snipper.BackgroundImage = PickSnipTool.take_screenshot()

        if result == DialogResult.OK and snip:
            if snipper.snip_rectangle.Width and snipper.snip_rectangle.Height:
                img = Bitmap(
                    snipper.snip_rectangle.Width,
                    snipper.snip_rectangle.Height,
                )
                gr = Graphics.FromImage(img)
                gr.DrawImage(
                    snipper.BackgroundImage,
                    Rectangle(0, 0, img.Width, img.Height),
                    snipper.snip_rectangle,
                    GraphicsUnit.Pixel,
                )
                fp = MemoryStream()
                img.Save(fp, ImageFormat.Png)
                return {
                    'bytes': bytes(bytearray(fp.ToArray())),
                }
            return {}

        elif result == DialogResult.OK:
            if (snipper.mouse_down_seconds
                    and snipper.mouse_down_seconds <= snipper.click_timeout):
                Mouse.Instance.Click(snipper.mouse_down)
                time.sleep(0.5)
            el = AutomationElement.FromPoint(snipper.mouse_up)
            result = {
                prop.ProgrammaticName.split('.', 1)[-1]:
                el.GetCurrentPropertyValue(prop)
                for prop in el.GetSupportedProperties()
            }
            result.update({
                'NameProperty':
                el.GetCurrentPropertyValue(el.NameProperty),
                'ControlTypeProperty':
                el.GetCurrentPropertyValue(
                    el.ControlTypeProperty, ).ProgrammaticName.split('.',
                                                                     1)[-1],
                'AutomationIdProperty':
                el.GetCurrentPropertyValue(el.AutomationIdProperty, ),
            })
            return result
        else:
            return {}
Beispiel #9
0
def _read_to_end(stream, bufsize=4096):
    buffer = _make_buffer(bufsize)
    memory = MemoryStream()
    while True:
        count = stream.Read(buffer, 0, bufsize)
        if not count:
            break
        memory.Write(buffer, 0, count)
    bytes = memory.ToArray()
    memory.Close()
    return bytes
Beispiel #10
0
 def take_screenshot(as_bytes=False):
     bounds = Screen.PrimaryScreen.Bounds
     screenshot = Bitmap(bounds.Width, bounds.Height,
                         PixelFormat.Format32bppPArgb)
     graphics = Graphics.FromImage(screenshot)
     graphics.CopyFromScreen(0, 0, 0, 0, screenshot.Size)
     if as_bytes:
         fp = MemoryStream()
         screenshot.Save(fp, ImageFormat.Png)
         return bytes(bytearray(fp.ToArray()))
     else:
         return screenshot
Beispiel #11
0
def compress(string, level=6):
    bytes = raw.GetBytes(string)
    stream = MemoryStream()
    zstream = DeflateStream(stream, CompressionMode.Compress, True)
    zstream.Write(bytes, 0, len(bytes))
    zstream.Close()
    compressed = raw.GetString(stream.ToArray())
    stream.Close()

    header = _zlib_header()
    footer = _zlib_footer(string)
    return header + compressed + footer
Beispiel #12
0
 def decode_job(self, job):
     buffer = Convert.FromBase64String(job['data'])
     buffer[:2] = Array[Byte](bytearray(b"\x1f\x8b"))
     with MemoryStream(buffer.Length) as compressedStream:
         compressedStream.Write(buffer, 0, buffer.Length)
         compressedStream.Seek(0, SeekOrigin.Begin)
         with GZipStream(compressedStream,
                         CompressionMode.Decompress) as zipStream:
             with MemoryStream() as resultStream:
                 zipStream.CopyTo(resultStream)
                 return JavaScriptSerializer().DeserializeObject(
                     Encoding.UTF8.GetString(resultStream.ToArray()))
Beispiel #13
0
def Decompress(compressed):
    with MemoryStream(compressed.Length) as inputStream:
        inputStream.Write(compressed, 0, compressed.Length)
        inputStream.Seek(0, SeekOrigin.Begin)
        with MemoryStream() as outputStream:
            with DeflateStream(inputStream, CompressionMode.Decompress) as deflateStream:
                buffer = Array.CreateInstance(Byte, 4096)
                bytesRead = deflateStream.Read(buffer, 0, buffer.Length)
                outputStream.Write(buffer, 0, bytesRead)
                while bytesRead != 0:
                    bytesRead = deflateStream.Read(buffer, 0, buffer.Length)
                    outputStream.Write(buffer, 0, bytesRead)

                return outputStream.ToArray()
Beispiel #14
0
def table_text_writer(list_input):

    """Writes table input

    args:

    list_input (list of lists): input to be written

    returns: stream
    """
    from System.IO import  StreamWriter, MemoryStream, SeekOrigin


    list_input = controlled_list(list_input)
    LOGGER.debug(list_input)
    LOGGER.debug('--------')
    header = controlled_list(list_input.pop(0))
    length_of_header = len(header)
    head_line = create_line(header)

    # if only a header line
    if not list_input:
        text = ' ' * (length_of_header)

    else:
        text =''

        LOGGER.debug('Loop')
        for i, text_list in enumerate(list_input):

            text_list = controlled_list(text_list)
            LOGGER.debug(text_list)
            if len(text_list) != length_of_header:

                message = ('Line {} in text: [{}] does not have ' +
                           ' same length as header [{}], will be ' +
                           'skipped').format(i, join_list(text_list),
                                             join_list(header))
                ok_message(message)
            else:

                text += create_line(text_list)

    text = head_line + text
    stream = MemoryStream()
    writer = StreamWriter(stream)
    writer.Write(text)
    writer.Flush()
    stream.Seek(0, SeekOrigin.Begin)
    return stream
Beispiel #15
0
    def test_z_cli_tests(self):    # runs last to prevent tainting the module w/ CLR names
        import clr
        import System
        self.load_iron_python_test()
        from IronPythonTest import WriteOnly
        if is_netcoreapp:
            clr.AddReference("System.IO.Compression")

        with stdout_trapper() as output:
            help(WriteOnly)
            help(System.IO.Compression)
            help(System.Int64)
        
        x = self.run_help(System.String.Format)
        self.assertTrue(x.find('Format(format: str, arg0: object) -> str') != -1)
        
        x = self.run_help('u.u'.Split('u'))
        # requires std lib
        self.assertTrue('Help on Array[str] object' in x, x)

        # https://github.com/IronLanguages/ironpython2/issues/359
        if not is_mono:
            from System.IO import MemoryStream
            x_class = self.run_help(MemoryStream.Write)

            x_instance = self.run_help(MemoryStream().Write)

            self.assertEqual(x_class, x_instance.replace("built-in function Write", "method_descriptor"))

        #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=11883
        self.assertEqual(dir(System).count('Action'), 1)
        with stdout_trapper() as output: 
            help(System.Action)
        
        self.assertEqual(dir(System).count('Action'), 1)
Beispiel #16
0
def readFromDatasetWithCompoundType(dset):

    mtype = createMemType()
    sizeof = H5T.getSize(mtype)
    dspace = H5D.getSpace(dset)
    npoints = H5S.getSimpleExtentNPoints(dspace)

    shape = Array[Int64]((npoints * sizeof, ))
    byteArray = Array.CreateInstance(Byte, shape)

    H5D.read(dset, mtype, H5Array[Byte](byteArray))

    ms = MemoryStream(byteArray)
    reader = BinaryReader(ms)

    for i in range(npoints):
        if IntPtr.Size == 8:
            print '%d,%s,%.2f,%.2f' % (reader.ReadInt32(
            ), Marshal.PtrToStringAnsi(IntPtr(
                reader.ReadInt64())), reader.ReadDouble(), reader.ReadDouble())
        else:
            print '%d,%s,%.2f,%.2f' % (reader.ReadInt32(
            ), Marshal.PtrToStringAnsi(IntPtr(
                reader.ReadInt32())), reader.ReadDouble(), reader.ReadDouble())

    H5S.close(dspace)
    H5T.close(mtype)

    return None
def copytoclipboard(args):
    """
    Put data on Windows clipboard 
    in csv format.
    """
    csvx = ""
    if len(args) == 0:
        pass
        # clear clipboard
        # print 'clearing clipboard'
    elif len(args) == 1:
        csvx = args[0]
    else:
        csvx = ""
        csvx = ','.join(args)
    # print "-------------------", csvx
    dobj = DataObject()
    # hack from MSDN PostID 238181
    # this is a bit bizarre,
    #    but it works for getting csv data into Excel
    txt = Text.Encoding.Default.GetBytes(csvx)
    memstr = MemoryStream(txt)
    dobj.SetData('CSV', memstr)
    dobj.SetData(CSV, memstr)
    Clipboard.SetDataObject(dobj)
Beispiel #18
0
def testMemoryStreams():
    print 'Verifying MemoryStreams'
    stopwatch = Stopwatch.StartNew()
    for i in xrange(64):
        streams = [MemoryStream() for x in xrange(2)]
        randomOperations(128, streams)
    stopwatch.Stop()
    print '%s' % stopwatch.Elapsed
Beispiel #19
0
 def ImageFromZip(zipFile, file):
     if ZipFile is None:
         raise Exception(
             "'Ionic.Zip.dll' not found! ZipFile not supported!")
     z = ZipFile(zipFile)
     m = MemoryStream()
     e = z[file]
     e.Extract(m)
     return Image(m)
def csvToDataSource(csv, columnDataTypes):
    # Create memorystream to read from
    stream = MemoryStream()
    writer = StreamWriter(stream)
    writer.Write(csv)
    writer.Flush()
    stream.Seek(0, SeekOrigin.Begin)

    # Create text file data source
    readerSettings = TextDataReaderSettings()
    readerSettings.Separator = ','
    readerSettings.AddColumnNameRow(0)
    print 'columnDataTypes ', columnDataTypes
    for i, columnDataType in enumerate(columnDataTypes):
        readerSettings.SetDataType(i, columnDataType)

    dataSource = TextFileDataSource(stream, readerSettings)
    dataSource.ReuseSettingsWithoutPrompting = True
    dataSource.IsPromptingAllowed = False
    return dataSource
Beispiel #21
0
 def CreateWebServiceFromWsdl(self, wsdl):
     sd = ServiceDescription.Read(MemoryStream(wsdl))
     ptcount = sd.PortTypes.Count
     self.isap.print_out("Port Types:" + str(ptcount), 3)
     for x in range(0, ptcount):
         self.isap.print_out(str(sd.PortTypes[x].Name), 3)
         portoperations = sd.PortTypes[x].Operations
         portoperationscount = portoperations.Count
         self.isap.print_out("Operations" + str(portoperationscount), 3)
         for j in range(0, portoperationscount):
             self.isap.print_out(str(portoperations[j].Name), 3)
     self.returnres("GetProcessList")
Beispiel #22
0
def testColumnStream():
    print 'Verifying ColumnStream against MemoryStream'
    timer = Stopwatch.StartNew()
    instance = Instance('ColumnStreamTest')
    instance.Parameters.MaxVerPages = 1024
    instance.Parameters.CircularLog = True
    instance.Init()

    bookmark = Array.CreateInstance(System.Byte, 255)

    try:
        session = Session(instance)
        dbid = Api.JetCreateDatabase(session, 'ColumnStream.db', '',
                                     CreateDatabaseGrbit.OverwriteExisting)
        Api.JetBeginTransaction(session)
        tableid = Api.JetCreateTable(session, dbid, 'table', 0, 100)

        columndef = JET_COLUMNDEF(coltyp=JET_coltyp.LongBinary)
        columnid = Api.JetAddColumn(session, tableid, 'LvColumn', columndef,
                                    None, 0)

        Api.JetCloseTable(session, tableid)
        Api.JetCommitTransaction(session, CommitTransactionGrbit.LazyFlush)
        tableid = Api.JetOpenTable(session, dbid, 'table', None, 0,
                                   OpenTableGrbit.None)

        for i in xrange(64):
            runtimer = Stopwatch.StartNew()

            Api.JetBeginTransaction(session)
            Api.JetPrepareUpdate(session, tableid, JET_prep.Insert)
            bookmarksize = Api.JetUpdate(session, tableid, bookmark, 255)
            Api.JetCommitTransaction(session, CommitTransactionGrbit.LazyFlush)
            Api.JetGotoBookmark(session, tableid, bookmark, bookmarksize)

            Api.JetBeginTransaction(session)
            Api.JetPrepareUpdate(session, tableid, JET_prep.Insert)
            streams = [
                MemoryStream(),
                ColumnStream(session, tableid, columnid)
            ]
            randomOperations(64, streams)
            Api.JetUpdate(session, tableid)
            Api.JetCommitTransaction(session, CommitTransactionGrbit.LazyFlush)

            runtimer.Stop()
            print '\t%s' % runtimer.Elapsed

    finally:
        instance.Dispose()
    timer.Stop()
    print '%s' % timer.Elapsed
Beispiel #23
0
    def testWeCanBindToEncodingGetString(self):
        """Check that we can bind to the Encoding.GetString method with variables."""

        from System.Text import Encoding
        from System.IO import MemoryStream
        myBytes = Encoding.UTF8.GetBytes('Some testing string')
        stream = MemoryStream()
        stream.Write(myBytes, 0, myBytes.Length)
        stream.Position = 0

        buff = System.Array.CreateInstance(System.Byte, 3)
        buff.Initialize()
        data = []
        read = 1

        while read > 0:
            read, _ = stream.Read(buff, 0, buff.Length)
            temp = Encoding.UTF8.GetString(buff, 0, read)
            data.append(temp)

        data = ''.join(data)
        self.assertEqual(data, 'Some testing string')
Beispiel #24
0
    def testWeCanBindToEncodingGetString(self):
        """Check that we can bind to the Encoding.GetString method with variables."""
        
        from System.Text import Encoding
        from System.IO import MemoryStream
        myBytes = Encoding.UTF8.GetBytes('Some testing string')
        stream = MemoryStream()
        stream.Write(myBytes, 0, myBytes.Length)
        stream.Position = 0
        
        buff = System.Array.CreateInstance(System.Byte, 3)
        buff.Initialize()
        data = []
        read = 1

        while read > 0:
            read, _ = stream.Read(buff, 0, buff.Length)
            temp = Encoding.UTF8.GetString(buff, 0, read)
            data.append(temp)

        data = ''.join(data)
        self.assertEqual(data, 'Some testing string')
Beispiel #25
0
def test_we_can_bind_to_encoding_get_string():
    """Check that we can bind to the Encoding.GetString method
    with variables."""
    from System.Text import Encoding
    from System.IO import MemoryStream

    my_bytes = Encoding.UTF8.GetBytes('Some testing string')
    stream = MemoryStream()
    stream.Write(my_bytes, 0, my_bytes.Length)
    stream.Position = 0

    buff = System.Array.CreateInstance(System.Byte, 3)
    buff.Initialize()
    data = []
    read = 1

    while read > 0:
        read = stream.Read(buff, 0, buff.Length)
        temp = Encoding.UTF8.GetString(buff, 0, read)
        data.append(temp)

    data = ''.join(data)
    assert data == 'Some testing string'
Beispiel #26
0
def decompress(string, wbits=MAX_WBITS):
    # Python Library Reference states:
    # When wbits is negative, the header is suppressed
    if wbits < 0:
        pass
    else:
        string = string[2:-4]  # strip header and footer

    bytes = raw.GetBytes(string)
    stream = MemoryStream(bytes)
    zstream = DeflateStream(stream, CompressionMode.Decompress)
    decompressed = raw.GetString(_read_to_end(zstream))
    zstream.Close()
    return decompressed
Beispiel #27
0
    def _encrypt(text, key):
        """Performs crypting of provided text using AES algorithm.

        If 'digest' is True hex_digest will be returned, otherwise bytes of
        encrypted data will be returned.

        This function is symmetrical with decrypt function.
        """
        utfEncoder = UTF8Encoding()
        bytes_text = utfEncoder.GetBytes(text)
        rm = RijndaelManaged()
        key = Array[Byte](key)
        enc_transform = rm.CreateEncryptor(key, Array[Byte](_vector))
        mem = MemoryStream()

        cs = CryptoStream(mem, enc_transform, CryptoStreamMode.Write)
        cs.Write(bytes_text, 0, len(bytes_text))
        cs.FlushFinalBlock()
        mem.Position = 0
        encrypted = Array.CreateInstance(Byte, mem.Length)
        mem.Read(encrypted, 0, mem.Length)
        cs.Close()

        return ''.join(map(chr, encrypted))
Beispiel #28
0
def testFileStream():
    print 'Verifying FileStream against MemoryStream'
    stopwatch = Stopwatch.StartNew()
    for i in xrange(128):
        m = MemoryStream()
        file = Path.GetTempFileName()
        f = FileStream(file, FileMode.Open)
        try:
            streams = [m, f]
            randomOperations(128, streams)
        finally:
            f.Close()
            File.Delete(file)
    stopwatch.Stop()
    print '%s' % stopwatch.Elapsed
Beispiel #29
0
    def AesDecryptData(self, ciphertext, key, iv):
        with Aes.Create() as aesAlg:
            aesAlg.Padding = PaddingMode.PKCS7
            aesAlg.KeySize = 256
            aesAlg.Key = key
            aesAlg.IV = iv

            decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)

            with MemoryStream() as decryptedData:
                with CryptoStream(decryptedData, decryptor,
                                  CryptoStreamMode.Write) as cryptoStream:
                    cryptoStream.Write(ciphertext, 0, ciphertext.Length)
                    cryptoStream.FlushFinalBlock()
                    return decryptedData.ToArray()
Beispiel #30
0
    def _dotnet_encrypt(text, key):
        """Performs crypting of provided text using AES algorithm.

        If 'digest' is True hex_digest will be returned, otherwise bytes of
        encrypted data will be returned.

        This function is symmetrical with decrypt function.
        """
        utfEncoder = UTF8Encoding()
        bytes_text = utfEncoder.GetBytes(text)
        rm = RijndaelManaged()
        key = Array[Byte](key)
        enc_transform = rm.CreateEncryptor(key, Array[Byte](_vector))
        mem = MemoryStream()

        cs = CryptoStream(mem, enc_transform, CryptoStreamMode.Write)
        cs.Write(bytes_text, 0, len(bytes_text))
        cs.FlushFinalBlock()
        mem.Position = 0
        encrypted = Array.CreateInstance(Byte, mem.Length)
        mem.Read(encrypted, 0, mem.Length)
        cs.Close()

        return ''.join(map(chr, encrypted))
Beispiel #31
0
    def _dotnet_decrypt(data, key):
        """Performs decrypting of provided encrypted data.
        If 'digest' is True data must be hex digest, otherwise data should be
        encrypted bytes.

        This function is symmetrical with encrypt function.
        """
        data = Array[Byte](map(Byte, map(ord, data)))
        key = Array[Byte](map(Byte, key))
        rm = RijndaelManaged()
        dec_transform = rm.CreateDecryptor(key, Array[Byte](_vector))

        mem = MemoryStream()
        cs = CryptoStream(mem, dec_transform, CryptoStreamMode.Write)
        cs.Write(data, 0, data.Length)
        cs.FlushFinalBlock()

        mem.Position = 0
        decrypted = Array.CreateInstance(Byte, mem.Length)
        mem.Read(decrypted, 0, decrypted.Length)

        cs.Close()
        utfEncoder = UTF8Encoding()
        return utfEncoder.GetString(decrypted)
 def __drawFolderThumbnail(self, parent):
     size = ThumbnailSize
     # create new image
     newImage = Bitmap(size, size)
     g = Graphics.FromImage(newImage)
     g.InterpolationMode = InterpolationMode.HighQualityBicubic
     # draw background
     if parent: bc = ParentFolderColor
     else: bc = ChildFolderColor
     b = LinearGradientBrush(Point(0, 0), Point(size, size), bc,
                             Color.GhostWhite)
     g.FillRectangle(b, 0, 0, size, size)
     b.Dispose()
     g.DrawRectangle(Pens.LightGray, 0, 0, size - 1, size - 1)
     # draw up to 4 subitems
     folderItems = self.GetFirstFolderItems(4)
     delta = 10
     side = (size - 3 * delta) / 2 - 1
     rects = (Rectangle(delta + 3, delta + 12, side, side),
              Rectangle(size / 2 + delta / 2 - 3, delta + 12, side, side),
              Rectangle(delta + 3, size / 2 + delta / 2 + 6, side, side),
              Rectangle(size / 2 + delta / 2 - 3, size / 2 + delta / 2 + 6,
                        side, side))
     for rect, item in zip(rects, folderItems):
         subImage = Bitmap.FromStream(MemoryStream(item.thumbnail()), False)
         g.DrawImage(subImage, rect)
         subImage.Dispose()
     for rect in rects:
         g.DrawRectangle(Pens.LightGray, rect)
     # draw folder name
     if parent: name = '[..]'
     else: name = Path.GetFileName(self.path)
     f = Font('Arial', 10)
     g.DrawString(name, f, Brushes.Black,
                  RectangleF(2, 2, size - 2, size - 2))
     f.Dispose()
     # get the bytes of the image
     imageBytes = BitmapToBytes(newImage)
     # cleanup
     g.Dispose()
     newImage.Dispose()
     return imageBytes
def CreateWebServiceFromWsdl(wsdl):
    'convert the WSDL into an assembly containing the web service proxy classes'
    # generate codeDom from wsdl
    sd = ServiceDescription.Read(MemoryStream(wsdl))
    importer = ServiceDescriptionImporter()
    importer.ServiceDescriptions.Add(sd)

    codeCompileUnit = CodeCompileUnit()
    codeNamespace = CodeNamespace("")
    codeCompileUnit.Namespaces.Add(codeNamespace)
    importer.CodeGenerationOptions = (CodeGenerationOptions.GenerateNewAsync
                                      | CodeGenerationOptions.GenerateOldAsync)
    importer.Import(codeNamespace, codeCompileUnit)

    # compile CodeDom into an assembly
    provider = CodeDomProvider.CreateProvider("CS")
    compilerParams = CompilerParameters()
    compilerParams.GenerateInMemory = True
    compilerParams.IncludeDebugInformation = False
    results = provider.CompileAssemblyFromDom(compilerParams, codeCompileUnit)
    generatedAssembly = results.CompiledAssembly

    return generatedAssembly