vrijdag 26 september 2008

Simple encryption in VB

This is an simple introduction on write your own encryption functions, but as stated these function are very simple, so do NOT use this function for encrypting any important data.

The first and very simple encryption:
The following function adds the code number to the ascii value of the text, which all characters change to something else.
An output of this function could be:
Rovvy8*^ro*}zkwwo|*lovy�*s}*os~ro|*}sxq*ƒy|*|o}y|mo}*~y*}oxn*y~*lvu
x}yvsms~on*mywwo|mskv*o7wksv*2,}zkw,3*y|*s}*nomoz~s€ovƒ*~|ƒsxq*~y*wkuo*s~
vyyu*vsuo*ro*s}8*Sx*os~ro|*mk}o6*k*voqs~swk~o*mywzkxƒ*vsuo*ƒy|}
*z|ylklvƒ�yvn*xy~*kzz|y€
o8*^ro*sxpy|wk~syx*lovy�*}ryvn*lo*kvv*ƒy*xoon8
Quite hard to read, isn't it?

Public Function Encrypt1(Txt As String, CodeNr As Integer) As String
Dim i As Long
Dim Out As String

'Inital output value is empty string
Out = ""

'Change ASCII codes
For i = 1 To Len(Txt)
Out = Out & Chr(Asc(Mid$(Txt, i, 1)) + CodeNr)
Next i

Encrypt1 = Out
End Function

As encryption en decryption are not that different we just call Encrypt1 from the decryption function:

Public Function Decrypt1(Txt As String, CodeNr As Integer) As String
'Decryption is the same as encryption with CodeNr*-1
Decrypt1 = Encrypt1(Txt, CodeNr * -1)

End Function

Now you may be wondering why this code is so extremely weak. But it's actually quite simple, as the most commonly used character would normally be the space. Below the code to break this code easily:

Function BreakCode(CText as String) as String
Dim a(0 To 255) As Long
Dim Txt As String
Dim ascii As Byte
Dim l As Byte
Dim q As Long
Dim SugCodeNr As Integer

'Count how often characters occur
Txt = CText
l = 0
For q = 1 To Len(Txt)
ascii = Asc(Mid$(Txt, q, 1))
a(ascii) = a(ascii) + 1
If a(ascii) > a(l) Then l = ascii
Next q

Debug.Print "Most used character: '" & Chr(l) & "'"

'Space (ascii 32) is most often used in texts
'As we now this we can calculate the CodeNr...
SugCodeNr = l - 32
BreakCode = Decrypt1(Txt, SugCodeNr)

Debug.Print "Code number = " & CStr(SugCodeNr)
End function