6.24.2011

Image Effect : Bluring - Fast with Graphics Drawing

one of the famous effects that we can apply to images is Blur. it is used to reduce "noise" and details.
you can read here about Gaussian blur in this wiki article.

one basic blurring consist in adding to the rgb values of a pixel, all rgb values of the pixels surrounding it.
another article explaining it well, and its implementation in Visual Basic on CodeProject.

the problem - for me - is the speed. this method is slow. so after a second thought, why treating pixel by pixel? let's try blurring the hole image at the same time.

Here is what i came up with :

Sub BlurBitmap(ByRef image As Bitmap, Optional ByVal BlurForce As Integer = 1)
        'We get a graphics object from the image
        Dim g As Graphics = Graphics.FromImage(image)
        'declare an ImageAttributes to use it when drawing
        Dim att As New ImageAttributes
        'declare a ColorMatrix
        Dim m As New ColorMatrix
        ' set Matrix33 to 0.5, which represents the opacity. so the drawing will be semi-trasparent.
        m.Matrix33 = 0.5F
        'Setting this ColorMatrix to the ImageAttributes.
        att.SetColorMatrix(m)
        'drawing the image on it self, but not in the same coordinates, in a way that every pixel will be drawn on the pixels arround it.
        For x = -BlurForce To BlurForce
            For y = -BlurForce To BlurForce
                'Drawing image on it self using out ImageAttributes to draw it semi-transparent.
                g.DrawImage(image, New Rectangle(x, y, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, att)
            Next
        Next
        'disposing ImageAttributes and Graphics. the effect is then applied. 
        att.Dispose()
        g.Dispose()
    End Sub





Testing :
I find this way faster than treating a it pixel per pixel. try changing the value of BlurForce (which should be an integer > 0) and check the effect. have fun with it!

Any comments are very welcome.

Handling Registry in DotNet - RegNotifyChangeKeyValue

In other programming languages, it is most likely a must to use the registry Api's, listed on msdn Here.
But using dotnet, thanks to the Microsoft.Win32.Registry Class, we have all methods needed to Open a key, enumerate keys, create or delete keys, or even enumerating values, reading names, values, adding, modifying and deleting. there are various examples on msdn for almost every method of this class, they could really show you the simplicity of handling registry.

Probably the function that i find important and "missing" in this class is the ability to monitor changes in the registry.
therefor, we are going to use the RegNotifyChangeKeyValue as we do in any other language.
but first, we are going to use RegOpenKeyEx to open the key with the KEY_NOTIFY.

Here is an exemple :

Private Declare Function RegNotifyChangeKeyValue Lib "advapi32.dll" (ByVal hKey As IntPtr, _
ByVal watchSubtree As Boolean, ByVal dwNotifyFilter As Integer, ByVal hEvent As IntPtr, _
ByVal fAsynchronous As Boolean) As Integer

Private Declare Auto Function RegOpenKeyEx Lib "advapi32.dll" ( _
ByVal hKey As IntPtr, _
ByVal lpSubKey As String, _
ByVal ulOptions As Integer, _
ByVal samDesired As Integer, _
ByRef phkResult As Integer) As Integer

Const REG_NOTIFY_CHANGE_LAST_SET As Integer = &H4L
Const HKEY_CURRENT_USER As Integer = &H80000001
Const KEY_NOTIFY As Integer = &H10 
Const ERROR_SUCCESS As Integer = 0


Sub RegNotifyChange()
        Dim regkey As IntPtr
        If RegOpenKeyEx(HKEY_CURRENT_USER, "Software\Microsoft\Windows", 0, KEY_NOTIFY, regkey) = ERROR_SUCCESS Then
            If RegNotifyChangeKeyValue(regkey, False, REG_NOTIFY_CHANGE_LAST_SET, Nothing, False) = ERROR_SUCCESS Then
                MsgBox("Change!")
            Else
                MsgBox("RegNotifyChangeKeyValue Failed.")
            End If
        Else
            MsgBox("RegOpenKeyEx Failed.")
        End If
    End Sub

Explaining the code :
we need to open a registry key with the notify access, so we can tell RegNotifyChangeKeyValue to "notify" us whenever something changed.
we call RegOpenKeyEx with HKEY_CURRENT_USER as the root key, which is already opened.
our subkey for exemple will be "Software\Microsoft\Windows". set 0 for the reserved parameter, KEY_NOTIFY for desired Access, and our variable regkey where the handle will be stored.
after that, we call RegNotifyChangeKeyValue with the specified opened key. we set true if want to monitor subkeys also, in this case we dont (for example). Then, when need to specify a filter, which can be a combination of REG_NOTIFY_CHANGE_NAME, REG_NOTIFY_CHANGE_ATTRIBUTES, REG_NOTIFY_CHANGE_LAST_SET and REG_NOTIFY_CHANGE_SECURITY, they are all described in the RegNotifyChangeKeyValue page. in our case, all we need is to monitor changes in values only.
in the next parameter, we need to specify whether we want to "fire" an event when a change occurs, so we set hEvent to a handle of an event, and fAsynchronous to True. in our case, where fAsynchronous is set to false, the calling thread will sleep after the call, and the function will only return when a change occurs. in this case hEvent is ignored.

Debugging :
When this method is called, the thread will be waiting for the function to return, in other words, will be waiting for a specific changes in the registry, a messagebox will pop up, and our sub will exit. if we want to continue to monitor changes, we can keep calling RegNotifyChangeKeyValue in a loop, but it is better to use another thread for the job, because this thread will be busy.

After Finishing using the key, it is best to call RegCloseKey to close the handle.

6.18.2011

Listing All Tcp connections on Local Computer

For this part of code, it will be based on this Api called GetExtendedTcpTable.
What we are going to do is, to try and retrieve every tcp connection, its state, its local and remote adresses and ports, and it's owning process. We could also use GetTcpTable to for the same job, but i noticed that it is only available in Vista, so we'll go with GetExtendedTcpTable for now, as it is working on both Vista and Xp Sp2.

Let's start with coding, here is a detailed module about what we need, so create a new module and paste this :

Imports System.Runtime.InteropServices
Imports System.Net.NetworkInformation
Imports System.Net

Public Module TCPGet
'Api to get table
Declare Auto Function GetExtendedTcpTable Lib "iphlpapi.dll" (ByVal pTCPTable As IntPtr, ByRef OutLen As Integer, ByVal Sort As Boolean, ByVal IpVersion As Integer, ByVal dwClass As Integer, ByVal Reserved As Integer) As Integer
'const : we are asking for connections with ProcessIDs', all of them.
Const TCP_TABLE_OWNER_PID_ALL As Integer = 5
'represents a full table
<StructLayout(LayoutKind.Sequential)> _
Public Structure MIB_TCPTABLE_OWNER_PID
Public NumberOfEntries As Integer 'number of rows
Public Table As IntPtr 'array of tables
End Structure
'represents a row
<StructLayout(LayoutKind.Sequential)> _
Public Structure MIB_TCPROW_OWNER_PID
Public state As Integer 'state of the connection
Public localAddress As UInteger
Public LocalPort As Integer
Public RemoteAddress As UInteger
Public remotePort As Integer
Public PID As Integer 'Process ID
End Structure
'this a structure that we made to store a connection after formatting it
Structure TcpConnection
Public State As TcpState
Public localAddress As String
Public LocalPort As Integer
Public RemoteAddress As String
Public remotePort As Integer
Public Proc As String
End Structure
'Main Function
Function GetAllTCPConnections() As MIB_TCPROW_OWNER_PID()
GetAllTCPConnections = Nothing
'we need to know how much memory we need to store all the connections
Dim cb As Integer
'so we call GetExtendedTcpTable without a pointer to a table to get the size
GetExtendedTcpTable(Nothing, cb, False, 2, TCP_TABLE_OWNER_PID_ALL, 0)
'after getting the size, we allocate memory
Dim tcptable As IntPtr = Marshal.AllocHGlobal(cb)
'the call where we store the connections in that memory
If GetExtendedTcpTable(tcptable, cb, False, 2, TCP_TABLE_OWNER_PID_ALL, 0) = 0 Then
'we convert it to a MIB_TCPTABLE_OWNER_PID variable
Dim tab As MIB_TCPTABLE_OWNER_PID = Marshal.PtrToStructure(tcptable, GetType(MIB_TCPTABLE_OWNER_PID))
'and we make an array with a size of number of connections
Dim Mibs(tab.NumberOfEntries - 1) As MIB_TCPROW_OWNER_PID
'row represents the adress of a MIB_TCPROW in memory
Dim row As IntPtr
'for each connection
For i As Integer = 0 To tab.NumberOfEntries - 1
'adress = adress of table + 4(int32) + (size of a MIB_TCPROW * i)
row = New IntPtr(tcptable.ToInt32 + Marshal.SizeOf(tab.NumberOfEntries) + Marshal.SizeOf(GetType(MIB_TCPROW_OWNER_PID)) * i)
'convert pointer to a MIB_TCPROW, and store it in the array
Mibs(i) = Marshal.PtrToStructure(row, GetType(MIB_TCPROW_OWNER_PID))
Next
'returning the array
GetAllTCPConnections = Mibs
End If
'just before leaving, clean up your memory!
Marshal.FreeHGlobal(tcptable)
End Function
'MIB_TCPROW_OWNER_PID is not well formatted, we need to format it.
Function MIB_ROW_To_TCP(ByVal row As MIB_TCPROW_OWNER_PID) As TcpConnection
Dim tcp As New TcpConnection
tcp.State = DirectCast(row.state, TcpState) 'a State enum is better than an int
'IP adresses are stored in long format, we can simply convert it this way
Dim ipad As New IPAddress(row.localAddress)
tcp.localAddress = ipad.ToString
'also the port is in network byte order,we need to convert it as well
tcp.LocalPort = row.LocalPort / 256 + (row.LocalPort Mod 256) * 256
'another ip
ipad = New IPAddress(row.RemoteAddress)
tcp.RemoteAddress = ipad.ToString
'another port
tcp.remotePort = row.remotePort / 256 + (row.remotePort Mod 256) * 256
'for the process, all we get is the ID. Let's get also the name.
Dim p As Process = Process.GetProcessById(row.PID)
tcp.Proc = p.ProcessName & " (" & row.PID.ToString & ")"
'just freeing this variable since we don't need it anymore.
p.Dispose()
'done.
Return tcp
End Function
End Module

Let's Create a Listview as the following to display connections :


Now let's call our function and add each connection to this listview :

'Clear Items
        ListView1.Items.Clear()
        'For Each MIB_TCPROW
        For Each Row In GetAllTCPConnections()
            'We Convert It
            Dim Tcp As TcpConnection = MIB_ROW_To_TCP(Row)
            'Add SubItems to a ListViewItem
            Dim l As New ListViewItem(New String() {Tcp.State.ToString, Tcp.localAddress, Tcp.LocalPort, Tcp.RemoteAddress, Tcp.remotePort, Tcp.Proc})
            'Add The Item
            ListView1.Items.Add(l)
        Next

That's about it, we can now see all tcp connections thanks to this great API.
As for UDP Connections, we can use the GetExtendedUdpTable Function with MIB_UDPTABLE_OWNER_PID and MIB_UDPROW_OWNER_PID Structures with a very similar piece of code to list them in an array, and show them in a listview if you like so.

6.17.2011

Recovering Google Chrome Passwords


It was a while when i was curious about how my favorite web browser saves passwords.
i started browsing Chrome files, watching files that changes when i save a password.

after a few tries i found the file that stores the passes called web data (updated later to login data) in the Local Application Data Folder, which is an SQLite Database, wasn't that hard to find out with any DB Software.
after finding the table called "logins" that stores passwords, all we need to do is to read the "origin_url", "username_value" and "password_value" for each entry, but we need to decrypt the "password_value" using the CryptUnprotectData Api, without any pOptionalEntropy (Optionnal password, read CryptUnprotectData for more info). The other two values are stored as plain-text and no need to decrypt them.

There is planty of exemples about reading from SQLite DB, and also about using the CryptUnprotectData Api.

PS : Msdn recommands freeing memory of the pDataOut by calling LocalFree to free the pDataOut.pbData handle.

if anyone is having problem with sqlite reading or using CryptUnprotectData , Please Leave me a Comment i would be happy to help.


Check the Downloads page for the demo that includes reading from the database and decrypting.
i also included system.data.sqlite releases incase it failed due to compatibility issues.
you can also find it here : http://sourceforge.net/projects/sqlite-dotnet2/

Textual Cue For TextBox Control

In this article, every thing is based on this : EM_SETCUEBANNER

this is a Windows Message that we can send to an edit control such as a textbox, so we can have something like this :
 
this tip "Enter your full name here" on the textbox is usally useful to the user and avoid some confusion.
All we need to do, is to send this message to the handle of the control, via SendMessage Api.

Declare Unicode Function SendMessageW Lib "User32.dll" (ByVal Hwnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Boolean, ByVal lParam As String) As Boolean
    Const EM_SETCUEBANNER = 5377
    Function SetCueText(ByRef Textbox1 As TextBox, ByVal CueText As String, Optional ByVal ShowOnFocus As Boolean = False) As Boolean
        Return SendMessageW(Textbox1.Handle, EM_SETCUEBANNER, ShowOnFocus, CueText)
    End Function

Usage :
Call SetCueText wih these parameters: :
Textbox1 : the textbox control that you want to add a cue text to it. (Textbox)
CueText : The Tip that will show on the textbox (String)
ShowOnFocus : Set to true if you want the cue text visible even if the textbox has the focus (boolean)
Return value : returns true if it succeeds, otherwise it returns false.
Even Better, we can extend the textbox control, and add a property Called "CueText", just like this :

Imports System.Windows.Forms

Public Class mTextBox
    Inherits TextBox
    Declare Unicode Function SendMessageW Lib "User32.dll" (ByVal Hwnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Boolean, ByVal lParam As String) As Boolean
    Const EM_SETCUEBANNER = 5377
    Private _CueText As String
    Private _CueFocus As Boolean
    Public Property CueText() As String
        Get
            Return _CueText
        End Get
        Set(ByVal value As String)
            _CueText = value
            If Me.Handle <> IntPtr.Zero Then SendMessageW(Me.Handle, EM_SETCUEBANNER, New IntPtr(CInt(_CueFocus)), _CueText)
        End Set
    End Property
    Property CueTextFocus() As Boolean
        Get
            Return _CueFocus
        End Get
        Set(ByVal value As Boolean)
            _CueFocus = value
            CueText = CueText
        End Set
    End Property
End Class

What we did, we created a control that inherits from the usual textbox, and added two properties that allow us to get and set the cue text, and also whether to show on focus or not.

OpenIconDialog

If you noticed in your tool box, you've got your OpenFileDialog, SaveFileDialog, ColorDialog, ect...
But There Is No OpenIconDialog.
What we are going to do, is to use the PickIconDlg Api to show a dialog to choose an embedded icon in a file,it will return the index of the selected icon in the file, and then we use the ExtractIconEx Api to load the icon of that index to memory, get its handle and return a variable of type System.Drawing.Icon.
So basically, we made an OpenIconDialog.

Declare Unicode Function PickIconDlg Lib "shell32.dll" (ByVal hwnd As IntPtr, ByVal pszIconPath As StringBuilder, ByVal cchIconPath As Integer, ByRef piIconIndex As Integer) As Integer
    <DllImport("shell32.dll", CharSet:=CharSet.Auto)> _
    Private Shared Function ExtractIconEx(ByVal stExeFileName As String, ByVal nIconIndex As Integer, ByVal phiconLarge As IntPtr(), ByVal phiconSmall As IntPtr(), ByVal nIcons As Integer) As Integer
    End Function
    Function OpenIconDialog(Optional ByVal IcoPath As String = "Shell32.dll") As Icon
        Dim buff As New StringBuilder(IcoPath, 500)
        Dim ind As Integer
        If PickIconDlg(Nothing, buff, buff.Capacity, ind) = 1 Then
            Dim bitm As New Bitmap(1, 1)
            Dim hIcon() As IntPtr = New IntPtr(0) {}
            If (ExtractIconEx(buff.ToString, ind, hIcon, Nothing, 1) = 1) AndAlso hIcon(0) <> IntPtr.Zero Then
                Return Icon.FromHandle(hIcon(0))
            End If
        End If
        Return Nothing
    End Function
It would look something like this :

Msdn recommends that we call DestroyIcon api after finishing of using the icon, but we don't need to add that api declaration to our code since the type System.Drawing.Icon has a method called Dispose, that will eventually cleanup and call the DestroyIcon api.

6.16.2011

Custom Encryption : Polymorphic Stairs

An Encryption is a process to make a plaintext unreadable to anyone unless they have the algorithm and the key to transform the data to it's orginal state. It is usally -in general- used to PROTECT data from being read/understood/stolen.
check out more on wiki : http://en.wikipedia.org/wiki/Encryption

A stronger encryption method is the one with less chance to reverse data to original plaintext without knowing the password, which is called cracking.

today we are going to make our own "Custom Encryption", even if dotnet provides us with a fine list of encryption routines, check them out on msdn : http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx

What is Polymorphic?
Polymorphic stands for "multiple forms". in our case, the output of the encryption is diffrent everytime we use it, which gives some confusion to the one who tries to "crack" it without the password.

here is an exemple, which i called "Polymorphic Stairs"

Imports System.Text
Public Class PolyMorphicStairs
    Overloads Shared Function PolyCrypt(ByVal Data As String, ByVal Key As String, Optional ByVal ExtraRounds As UInteger = 0) As String
        Dim buff() As Byte = PolyCrypt(Encoding.Default.GetBytes(Data), Encoding.Default.GetBytes(Key), ExtraRounds)
        PolyCrypt = Encoding.Default.GetString(buff)
        Erase buff
    End Function
    Overloads Shared Function PolyDeCrypt(ByVal Data As String, ByVal Key As String, Optional ByVal ExtraRounds As UInteger = 0) As String
        Dim buff() As Byte = PolyDeCrypt(Encoding.Default.GetBytes(Data), Encoding.Default.GetBytes(Key), ExtraRounds)
        PolyDeCrypt = Encoding.Default.GetString(buff)
        Erase buff
    End Function
    Overloads Shared Function PolyCrypt(ByRef Data() As Byte, ByVal Key() As Byte, Optional ByVal ExtraRounds As UInteger = 0) As Byte()
        Array.Resize(Data, Data.Length + 1)
        Data(Data.Length - 1) = Convert.ToByte(New Random().Next(1, 255))
        For i = (Data.Length - 1) * (ExtraRounds + 1) To 0 Step -1
            Data(i Mod Data.Length) = CByte(CInt((Data(i Mod Data.Length)) + CInt(Data((i + 1) Mod Data.Length))) Mod 256) Xor Key(i Mod Key.Length)
        Next
        Return Data
    End Function
    Overloads Shared Function PolyDeCrypt(ByRef Data() As Byte, ByVal Key() As Byte, Optional ByVal ExtraRounds As UInteger = 0) As Byte()
        For i = 0 To (Data.Length - 1) * (ExtraRounds + 1)
            Data(i Mod Data.Length) = CByte((CInt(Data(i Mod Data.Length) Xor Key(i Mod Key.Length)) - CInt(Data((i + 1) Mod Data.Length)) + 256) Mod 256)
        Next
        Array.Resize(Data, Data.Length - 1)
        Return Data
    End Function
End Class

Lets take a look at this Class :
First, we have two functions, one to encrypt data and the other to decrypt data.
there are two parameters, one is the data, the other is the key, and the return value is the data after the transformation. they are both overloaded to accept strings or byte arrays as parameters. there is also an optionnal parameter called ExtraRounds, which represents how many addtional times you want to encrypt your data. for exemple, you want to encrypt it twise, set ExtraRounds to 1 when calling the function.

Here is how it works :
We first generate a random byte, and add it the end of the bytearray of the plaintext. after that, we add the value of that byte to the previous one, and using the bitwise operator XOR with a byte from the key. we just loop and do the same with every byte in the array.

The Output :
With the random byte sticked to the end of the array, its value is gonna be added to the previous byte, which also be added to the one before it... in other words the random byte will affect the hole array : the output will be completely randomized each time.
Here is an exemple where the plain-text and key are pretty basic :
As you can see, outputs are random and scrambled each time.
But the more complex the key is, the better.

Decryption :
In the decryption routine, we do the exact same thing, but backwards. First, we Xor the byte, and then remove the value next to it. after the loop finishes, we just remove the random value in the end of the buffer and we get our plaintext back to normal.

Weakness :
Xor operator is a weak Cipher by it self, the password can be guessed by analysing the output. the addition of a value to another and the use of a random value covers xor weakness, but there is alot of cracking routines, such as bruteforcing for exemple.

Why the random value was added to the end of the array?
Good Quesion. Why? this would work also if we add it at the start of the array. it is simply added to the end for a faster performance, because i don't really want copy the full array to a new one, or push all values to give space for the random one. as simple as that.

Follow by Email