working on it ...

Filters

Explore Public Snippets

Sort by

Found 733 snippets matching: bytes

    public by lbottaro modified Nov 6, 2012  311078  2  6  0

    Get MAC address of current interface in Python

    This python uses uuid.getnode to get current mac address as an integer. It formats the number in a standard mac address form (i.e. bytes splitted by :)
    import uuid
    print ':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1])
    

    public by Geometry modified Jul 31, 2016  148153  0  3  0

    GetCommandBuffer: Gets the bytes representing the specified command. returned buffer can be used to streamline multiple writes into one Write on the Socket using the <see cref="M:Enyim.Caching.Memcached.PooledSocket.Write(IList&lt;ArraySegment&lt;b...

    Gets the bytes representing the specified command. returned buffer can be used to streamline multiple writes into one Write on the Socket using the The command to be converted. The buffer containing the bytes representing the command. The command must be terminated by \r\n. The Nagle algorithm is disabled on the socket to speed things up, so it's
    C#
    using System;
    using System.IO;
    using System.Text;
    using System.Collections.Generic;
    
    /// <summary>
    /// Gets the bytes representing the specified command. returned buffer can be used to streamline multiple writes into one Write on the Socket
    /// using the <see cref="M:Enyim.Caching.Memcached.PooledSocket.Write(IList&lt;ArraySegment&lt;byte&gt;&gt;)"/>
    /// </summary>
    /// <param name="value">The command to be converted.</param>
    /// <returns>The buffer containing the bytes representing the command. The command must be terminated by \r\n.</returns>
    /// <remarks>The Nagle algorithm is disabled on the socket to speed things up, so it's recommended to convert a command into a buffer
    /// and use the <see cref="M:Enyim.Caching.Memcached.PooledSocket.Write(IList&lt;ArraySegment&lt;byte&gt;&gt;)"/> to send the command and the additional buffers in one transaction.</remarks>
    public unsafe static IList<ArraySegment<byte>> GetCommandBuffer(string value)
    {
    	var data = new ArraySegment<byte>(Encoding.ASCII.GetBytes(value));
    
    	return new ArraySegment<byte>[] { data };
    }

    public by cghersi modified Jan 29, 2016  101327  273  12  10

    Java: read from USB using RXTX library

    This is a well-tested class to read from USB device using RXTX library. First of all place rxtxSerial.so (or rxtxSerial.dll) in the classpath. The received bytes are stored in a queue called "receivedBytes". This queue is filled by the serialEvent() callback called by RXTX framework. Users of this class should retrieve the ready data from "receiv
    import gnu.io.*;
    import java.io.*;
    
    import java.util.Enumeration;
    import java.io.IOException;
    
    /**
     * This class provides the utilities to read the data exchanged via USB port.
     */
    public class USBComm implements SerialPortEventListener {
    
    	/**
    	 * Stream for the storage of incoming data
    	 */
    	private InputStream inputStream;
    	/**
    	 * Stream for the dispatching of data
    	 */
    	private OutputStream outputStream;
    	/**
    	 * Timeout of the USB port
    	 */
    	private final int PORT_TIMEOUT = 2000;
    	/**
    	 * Representation of the serial port used for the communication
    	 */
    	private SerialPort serialPort;
    	/**
    	 * Buffer that stores the received bytes from the media
    	 */
    	protected LinkedBlockingQueue<Byte> receivedBytes;
    
    	/**
    	 * Builds a new manager for the communication via USB port.
    	 * @exception IOException if an error occurred during the opening of the USB port
    	 */
    	public USBComm() throws IOException {
    	  receivedBytes = new LinkedBlockingQueue<Byte>(100000);
    		String port = "COM1"; //place the right COM port here, OS dependent
    	
    		//Check that the USB port exists and is recognized:
    		Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
    		boolean portFound = false;
    		CommPortIdentifier portId = null;
    		while (portList.hasMoreElements()) {
    			portId = (CommPortIdentifier) portList.nextElement();
    		    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    		    	System.out.println.info(portId.getName());
    				if (portId.getName().equals(port)) {
    					System.out.println("Found port: " + port);
    				    portFound = true;
    				    break;
    				} 
    		    } 
    		} 
    	
    		if (!portFound) 
    		    throw new IOException("port " + port + " not found.");
    	
    		try {
    			System.out.println("USB port opening...");
    		    serialPort = (SerialPort) portId.open("USBCommunicator", PORT_TIMEOUT);
    		    System.out.println("USB port opened");
    		    inputStream = serialPort.getInputStream();
    		    outputStream = serialPort.getOutputStream();
    		    serialPort.addEventListener(this);
    			    	serialPort.notifyOnDataAvailable(true);
    			//#==================================================================#
    			// WARNING! - DO NOT SET THE FOLLOWING PROPERTY WITH RXTX LIBRARY, IT
    			// 			  CAUSES A PROGRAM LOCK:
    			// 	serialPort.notifyOnOutputEmpty(true);
    			//#==================================================================#
    			    	
    		    //wait for a while to leave the time to javax.comm to
    		    //correctly configure the port:
    		    Thread.sleep(1000);
    		    
    			int baudRate = 115200; //set propertly
    	    	serialPort.setSerialPortParams(baudRate, 
    	    		SerialPort.DATABITS_8, 
    	    		SerialPort.STOPBITS_1, 
    				SerialPort.PARITY_NONE);
    		    
    	    	serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
    	    		
    		    System.out.println("setted SerialPortParams");
    		} catch (Exception e) {
    			System.err.println(e.getMessage());
    			throw new IOException(e.getMessage());
    		}
    	}
    
    	
    	public void closeUSB(){
    		//close the streams for serial port:
    		try {
    			inputStream.close();
    			outputStream.close();
    		} catch (IOException e) {
    			System.err.println("Cannot close streams:" + e.getMessage(), e);
    		}
    	}
    
    	/**
    	 * Listener for USB events
    	 * 
    	 * @param event new event occurred on the USB port
    	 */
    	public void serialEvent(SerialPortEvent event){
    		switch (event.getEventType()) {
    	
    			case SerialPortEvent.BI:
    			case SerialPortEvent.OE:
    			case SerialPortEvent.FE:
    			case SerialPortEvent.PE:
    			case SerialPortEvent.CD:
    			case SerialPortEvent.CTS:
    			case SerialPortEvent.DSR:
    			case SerialPortEvent.RI:
    			case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
    				//nothing to do...
    			    break;
    	
    			case SerialPortEvent.DATA_AVAILABLE:
    				byte received = -1;
    				do {
    					try {
    						received = (byte)inputStream.read();
    					} catch (IOException e) {
    						System.err.println("Error reading USB:" + e.getMessage());
    					}
    				
    					synchronized (receivedBytes) {
    						try {
    							receivedBytes.add(received);
    						} catch (IllegalStateException ew) {
    							System.err.println(ew.getMessage());
    							receivedBytes.poll();
    							receivedBytes.add(received);
    						}
    					}
    				} while(received != -1);
    
    			    break;
    		}
    	}
    
    	protected void write(byte[] buffer){
    	    try {
    	    	outputStream.write(buffer);
    	    	outputStream.flush();
    	    } catch (IOException e) {
    	    	System.err.println("Cannot write:" + e.getMessage());
    	    }
    	}
    }            

    public by cghersi modified Jan 10, 2017  2069  10  5  3

    How to write bytes into file in Java

    Efficient way to write strings or bytes onto a file.
      import java.nio.file.Files;
      import java.nio.file.Paths;
    
      public static void writeFile(String path, String content) throws Exception {
    		if (isNullOrEmpty(path) || isNullOrEmpty(content)) {
    			return;
    		}
    		Files.write(Paths.get(path), content.getBytes());
    	}                     

    public by Geometry modified Jul 31, 2016  1185  0  4  0

    GetCommandBuffer: Gets the bytes representing the specified command. returned buffer can be used to streamline multiple writes into one Write on the Socket using the <see cref="M:Enyim.Caching.Memcached.PooledSocket.Write(IList&lt;ArraySegment&lt;b...

    Gets the bytes representing the specified command. returned buffer can be used to streamline multiple writes into one Write on the Socket using the The command to be converted. The buffer containing the bytes representing the command. The command must be terminated by \r\n. The Nagle algorithm is disabled on the socket to speed things up, so it's
    using System;
    using System.IO;
    using System.Text;
    using System.Collections.Generic;
    
    /// <summary>
    /// Gets the bytes representing the specified command. returned buffer can be used to streamline multiple writes into one Write on the Socket
    /// using the <see cref="M:Enyim.Caching.Memcached.PooledSocket.Write(IList&lt;ArraySegment&lt;byte&gt;&gt;)"/>
    /// </summary>
    /// <param name="value">The command to be converted.</param>
    /// <returns>The buffer containing the bytes representing the command. The command must be terminated by \r\n.</returns>
    /// <remarks>The Nagle algorithm is disabled on the socket to speed things up, so it's recommended to convert a command into a buffer
    /// and use the <see cref="M:Enyim.Caching.Memcached.PooledSocket.Write(IList&lt;ArraySegment&lt;byte&gt;&gt;)"/> to send the command and the additional buffers in one transaction.</remarks>
    public unsafe static IList<ArraySegment<byte>> GetCommandBuffer(string value)
    {
    	var data = new ArraySegment<byte>(Encoding.ASCII.GetBytes(value));
    
    	return new ArraySegment<byte>[] { data };
    }

    public by Geometry modified Jul 31, 2016  993  0  4  0

    DecodeChecked: Uses the checksum in the last 4 bytes of the decoded data to verify the rest are correct. The checksum is removed from the returned data.

    Uses the checksum in the last 4 bytes of the decoded data to verify the rest are correct. The checksum is removed from the returned data. If the input is not base 58 or the checksum does not validate.
    using System;
    using System.Linq;
    using System.Text;
    using CoiniumServ.Coin.Address.Exceptions;
    using CoiniumServ.Cryptology;
    using Org.BouncyCastle.Math;
    
    /// <summary>
    /// Uses the checksum in the last 4 bytes of the decoded data to verify the rest are correct. The checksum is
    /// removed from the returned data.
    /// </summary>
    /// <exception cref="AddressFormatException">If the input is not base 58 or the checksum does not validate.</exception>
    public static byte[] DecodeChecked(string input)
    {
        var tmp = Decode(input);
        if (tmp.Length < 4)
            throw new AddressFormatException("Input too short");
        var checksum = new byte[4];
        Array.Copy(tmp, tmp.Length - 4, checksum, 0, 4);
        var bytes = new byte[tmp.Length - 4];
        Array.Copy(tmp, 0, bytes, 0, tmp.Length - 4);
        tmp = bytes.DoubleDigest();
        var hash = new byte[4];
        Array.Copy(tmp, 0, hash, 0, 4);
        if (!hash.SequenceEqual(checksum))
            throw new AddressFormatException("Checksum does not validate");
        return bytes;
    }

    public by Geometry modified Aug 7, 2016  905  0  4  0

    Read stream until space is found (space, new line, tab or comment). Returns number of bytes read. Stream's position will point to the next

    Read stream until space is found (space, new line, tab or comment). Returns number of bytes read. Stream's position will point to the next byte coming after the first found space byte.
    // Read stream until space is found (space, new line, tab or comment). Returns
    // number of bytes read. Stream's position will point to the next
    // byte coming after the first found space byte.
    private static int ReadUntilSpace(Stream stream, byte[] buffer, int start)
    {
        byte nextByte = (byte)stream.ReadByte();
        int bytesRead = 0;
    
        while ((nextByte != ' ') && (nextByte != '\n') && (nextByte != '\r') && (nextByte != '\t') && (nextByte != '#'))
        {
            buffer[start + bytesRead] = nextByte;
            bytesRead++;
            nextByte = (byte)stream.ReadByte();
        }
    
        return bytesRead;
    }

    public by Geometry modified Aug 7, 2016  828  0  5  0

    ReadStream: Read specified amount of bytes from the specified stream.

    Read specified amount of bytes from the specified stream. Source sream to read data from. Buffer to read data into. Offset in buffer to put data into. Number of bytes to read. Returns total number of bytes read. It may be smaller than requested amount only in the case if end of stream was reached. This tool function guarantees that requested
    /// <summary>
    /// Read specified amount of bytes from the specified stream.
    /// </summary>
    /// 
    /// <param name="stream">Source sream to read data from.</param>
    /// <param name="buffer">Buffer to read data into.</param>
    /// <param name="offset">Offset in buffer to put data into.</param>
    /// <param name="count">Number of bytes to read.</param>
    /// 
    /// <returns>Returns total number of bytes read. It may be smaller than requested amount only
    /// in the case if end of stream was reached.</returns>
    /// 
    /// <remarks><para>This tool function guarantees that requested number of bytes
    /// was read from the source stream (.NET streams don't guarantee this and may return less bytes
    /// than it was requested). Only in the case if end of stream was reached, the function
    /// may return with less bytes read.</para>
    /// </remarks>
    /// 
    public static int ReadStream( Stream stream, byte[] buffer, int offset, int count )
    {
        int totalBytesRead = 0, bytesRead = 0;
    
        while ( totalBytesRead != count )
        {
            bytesRead = stream.Read( buffer, offset + totalBytesRead, count - totalBytesRead );
    
            if ( bytesRead == 0 )
            {
                break;
            }
    
            totalBytesRead += bytesRead;
        }
    
        return totalBytesRead;
    }

    public by zonaro modified Nov 10, 2015  2727  1  7  0

    Easy Write Bytes to File

    This snnipet write (or overwrite) a ByteArray to file on specific path and return a FileInfo of the created file
    public static FileInfo ToFile(this byte[] ByteArray, string FilePath)
            { 
                if (File.Exists(FilePath)) { File.Delete(FilePath); }
                System.IO.FileStream fs = new System.IO.FileStream(FilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                fs.Write(ByteArray, 0, ByteArray.Length);
                fs.Close();
                return new FileInfo(System.IO.Path.GetFileName(FilePath)); 
            }

    public by Charles Grunwald modified Aug 22, 2015  652  0  3  1

    Using 7 bytes of preassembled shellcode, determine if the current 32-bit process is running in the WOW64 subsystem (as is the case when running 32-bit Python on 64-bit Windows) or if it's running from a 32-bit Windows OS.

    Using 7 bytes of preassembled shellcode, determine if the current 32-bit process is running in the WOW64 subsystem (as is the case when running 32-bit Python on 64-bit Windows) or if it's running from a 32-bit Windows OS.: iswow64.py
    # encoding: utf-8
    """
    iswow64.py
    Using 7 bytes of preassembled shellcode, determine if the current
    32-bit process is running in the WOW64 subsystem (as is the case
    when running 32-bit Python on 64-bit Windows) or if it's running
    from a 32-bit Windows OS.
    
    This program is free software. It comes without any warranty, to
    the extent permitted by applicable law. You can redistribute it
    and/or modify it under the terms of the Do What The Fuck You Want
    To Public License, Version 2, as published by Sam Hocevar. See
    http://sam.zoy.org/wtfpl/COPYING for more details.
    """
    from _ctypes import _SimpleCData as _SimpleCData
    from ctypes.wintypes import LPVOID, DWORD, INT, BOOLEAN, HANDLE
    from ctypes import WinDLL, POINTER, WinError, c_size_t as SIZE_T, sizeof as SIZEOF, \
                       cast as CAST, byref as BYREF, create_string_buffer as STRALLOC, \
                       WINFUNCTYPE as WINAPI, CFUNCTYPE as CDECL
    
    # Verify we're working on a 32-bit version of Python
    assert(SIZEOF(LPVOID) == SIZEOF(DWORD))
    
    # Kernel32 DLL
    _kernel32 = WinDLL('kernel32.dll')
    
    # Custom Types
    class BOOL(INT):
        """ Just a 32-bit integer interpreted as a boolean. """
    
        def from_param(self, value):
            if value is None:
                return INT(0)
            elif isinstance(value, _SimpleCData):
                return value
            else:
                return INT(value)
    
        def __eq__(self, other):
            value = self.value
            if isinstance(other, bool):
                return value == other
            elif isinstance(other, _SimpleCData):
                return value == bool(other.value)
            else:
                return value == bool(other)
    
        def __hash__(self):
            return hash(self._as_parameter_)
    
    
    # Typedefs
    LPCVOID = LPVOID
    PDWORD = POINTER(DWORD)
    PSIZE_T = POINTER(SIZE_T)
    
    # Constants
    NULL = LPVOID(0)
    NULL_PDWORD = CAST(NULL, PDWORD)
    NULL_PSIZE_T = CAST(NULL, PSIZE_T)
    
    ## Param values for flAllocationType & dwFreeType
    MEM_RESERVE = DWORD(0x00002000)
    MEM_COMMIT = DWORD(0x00001000)
    MEM_RELEASE = DWORD(0x8000)
    
    ## Param values for flProtect & flNewProtect
    PAGE_READWRITE = DWORD(0x04)
    PAGE_EXECUTE_READWRITE = DWORD(0x40)
    
    ## Param flags Constants
    _In = 1
    _Out = 2
    _InOpt = 3
    _InOutOpt = _InOpt | _Out
    
    # Win32 API Function Prototypes
    
    """ HANDLE WINAPI GetCurrentProcess(void); """
    GetCurrentProcess = WINAPI(HANDLE)(('GetCurrentProcess', _kernel32))
    hCurrentProcess = GetCurrentProcess()
    
    """ LPVOID WINAPI VirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) """
    VirtualAlloc = WINAPI(LPVOID, LPVOID, SIZE_T, DWORD, DWORD)(
        _kernel32.VirtualAlloc
    )
    
    """ BOOL VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) """
    VirtualFree = WINAPI(BOOL, LPVOID, SIZE_T, DWORD)(
        _kernel32.VirtualFree
    )
    
    """ BOOL VirtualProtect(LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect) """
    VirtualProtect = WINAPI(BOOL, LPVOID, SIZE_T, DWORD, PDWORD)(
        _kernel32.VirtualProtect
    )
    
    """ BOOL WINAPI WriteProcessMemory(HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumofBytesWritten) """
    WriteProcessMemory = WINAPI(BOOL, HANDLE, LPVOID, LPCVOID, SIZE_T, PSIZE_T)(
        _kernel32.WriteProcessMemory
    )
    
    """ BOOL WINAPI FlushInstructionCache(HANDLE hProcess, LPCVOID lpBaseAddress, SIZE_T dwSize) """
    FlushInstructionCache = WINAPI(BOOL, HANDLE, LPCVOID, SIZE_T)(
        _kernel32.FlushInstructionCache
    )
    
    def destroy_cfunc(cfuncproc):
        """
    
        :param cfuncproc:Stuff
        :type cfuncproc:ctypes.CFUNCTYPE
        :return:Success
        :rtype:bool
        """
        if isinstance(cfuncproc, LPVOID):
            cptr = cfuncproc
            csize = cfuncproc._allocsize
        else:
            cptr = cfuncproc._cptr
            csize = cfuncproc._procsize
        return bool(VirtualFree(cptr, csize, MEM_RELEASE))
    
    def create_cfunc(cfunctype, shellcode):
        """
    
        :param cfunctype: The function prototype to use for creation.
        :type cfunctype: ctypes.CFUNCTYPE
        :param shellcode: List of bytes forming the shellcode
        :type shellcode: list
        :return:The callable function in memory.
        :rtype:ctypes.CFUNCTYPE
        """
        # Grab the size of the shellcode
        shellcode_size = len(shellcode)
    
        # Reserve memory for our shellcode bytes
        lpAllocated = LPVOID(VirtualAlloc(NULL, shellcode_size, MEM_RESERVE, PAGE_EXECUTE_READWRITE))
        if not lpAllocated or (hasattr(lpAllocated, 'value') and lpAllocated.value is None):
            raise WinError()
    
        # Commit our allocation to obtain our allocated memory.
        lpRes = VirtualAlloc(lpAllocated.value, shellcode_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE)
        lpAllocated._allocsize = shellcode_size
    
        # Alter protection flags on the memory region that will contain our code.
        # if not VirtualProtect(lpAllocated.value, shellcode_size, PAGE_EXECUTE_READWRITE, NULL_PDWORD):
        #     destroy_cfunc(lpAllocated)
        #     raise WinError()
    
        # Assemble our shellcode buffer, then copy it over to our allocated memory.
        shellcode_buffer = STRALLOC(''.join(map(chr, shellcode)), shellcode_size)
        WriteProcessMemory(hCurrentProcess, lpAllocated, CAST(shellcode_buffer, LPVOID).value, shellcode_size, NULL_PSIZE_T)
    
        # Flush our instruction cache, and apply our prototype, then return the result.
        FlushInstructionCache(hCurrentProcess, lpAllocated, shellcode_size)
        cfuncproc = cfunctype(lpAllocated.value)
        cfuncproc._cptr = lpAllocated
        cfuncproc._procsize = shellcode_size
        return cfuncproc
    
    IsWow64ShellCode = [  # _IsWow64:
        0x66, 0x8C, 0xC8,    #     mov ax, cs
        0xC1, 0xE8, 0x05,    #     shr eax, 5
        0xC3                 #     ret
    ]
    
    ISWOW64FUNCTYPE = CDECL(BOOLEAN)
    IsWow64 = create_cfunc(ISWOW64FUNCTYPE, IsWow64ShellCode)
    if IsWow64():
        print 'IsWow64 = True'
    else:
        print 'IsWow64 = False'
    destroy_cfunc(IsWow64)
    
    
    
    • Public Snippets
    • Channels Snippets