Tuesday, 5 November 2013

99 problems, but DateTime ain't one of them...

DateTime is a constant function

As you properly already know: DateTime isn't a value like: 1 or "a". It's a constant !

    Public Delegate Function dateTime() As Date
    Public Function ImADateTimeConstant() As dateTime
      Return AddressOf ActualDateTime '<- Doesn't change does it !
    End Function

    Private Function ActualDateTime() As Date
      Return Date.Today
    End Function
    Private Function TestDateTime() As Date
      Return #1/1/2010#
    End Function

Dependancy injection

ImDependantOnDateTime = New Something(addressof ActualDateTime)
ImAlsoDependantOnDateTime = New Something(addressof TestDateTime)

Conclusion: time is a mathematical function with no param's, resulting in constant.

Happy Hacking: Roger Keulen.

Friday, 25 October 2013

Hacking the Many Time Pad with Machine Learning.

Wiki - One Time Pad

In cryptography, the one-time pad (OTP) is a type of encryption that is impossible to crack if used correctly. Each bit or character from the plain text is encrypted by a modular addition with a bit or character from a secret random key (or pad) of the same length as the plain text, resulting in a cipher text. If the key is truly random, as large as or greater than the plain text, never reused in whole or part, and kept secret, the cipher text will be impossible to decrypt or break without knowing the key. It has also been proven that any cipher with the perfect secrecy property must use keys with effectively the same requirements as OTP keys. However, practical problems have prevented one-time pads from being widely used.

Programming Assignment - Many Time Pad

Let us see what goes wrong when a stream cipher key is used more than once. Below are eleven hex-encoded cipher texts that are the result of encrypting eleven plain texts with a stream cipher, all with the same stream cipher key.

Your goal is to decrypt the last cipher text, and submit the secret message within it as solution.

target cipher text (decrypt this one):


A solution to crack the many time pad is to use statistics. If the message text is English, then the letter 'e' will be more used than the letter 'q'. And the lower character 'e' will be more often in the message than the uppercase character 'E'. The same goes for special characters like '@'. So every character has a statistically property in the message that where trying to find. So i we count the occurrence of characters in example text to learn, we can build a function O that will give us a value for every character. How more likely the character is the closer it is to 1. How more less likely a character is the more it's closer to 0.

O(x) = Occurrence of x in learning/expected text.
  • O(" ") = 1
  • O("t") = 0.9
  • O("$") = 0.00001


Then the best key at position p is the larges value of:
  max h = O(Cypher[1][p] xor Key[p]) x O(Cypher[2][p] xor Key[p]) x....

Because our solution space is limited and computers are very fast these days. We don't need a kind of algorithm to find the maximum of this function. We just going to use brute force to just try the complete solution space. So for every position we are going to try 256 keys, and store the key that gives us the biggest likelihood of being `the correct answer`.

  Function HypotheseAtPos(Pos As Integer, TryKey As Integer) As Double
    Dim ThisResult As Double = 1
    For Each CypherText As CypherText In Cyphers
      Try : ThisResult *= Language.OccurrenceOf(Chr(CypherText(Pos) Xor TryKey))
      Catch ex As ArgumentOutOfRangeException
      End Try
    Next : Return ThisResult
  End Function

Counting and normalising the language features

The next code is the 'Language' class that has our O or OccurrenceOf(Character) function. With the functions 'AddText' we can give the class some text where it will count every occurrence of every found character in the text.

Public Class Language
  Public EmptyValue As Double
  Private Index As New Dictionary(Of String, Double)
  Public Sub AddText(ParamArray ExampleTexts() As String)
    For Each ExampleText In ExampleTexts : Me.AddText(ExampleText)
  End Sub
  Public Sub AddText(ExampleText As String)
    If ExampleText.Length >= 1 Then
      Dim Character As String = Strings.Left(ExampleText, 1)
      If Not Me.Index.ContainsKey(Character) Then
        Me.Index.Add(Character, 1)
        Me.Index(Character) += 1
      End If
      AddText(Strings.Mid(ExampleText, 2))
    End If
  End Sub
  Public Sub Normalize(Scale As Double) ' <== [0.0 > Value >= 1.0]
    Dim MaxValue As Integer = 0
    For Each Item As KeyValuePair(Of String, Double) In Me.Index
      MaxValue = Math.Max(MaxValueItem.Value)
    For Each Character As String In Me.Index.Keys.ToArray
      Me.Index(Character) = (Me.Index(Character) / MaxValue) ^ Scale
  End Sub
  Public Function OccurrenceOf(Piece As String) As Double
    If Me.Index.ContainsKey(Piece) Then Return Me.Index(Piece) Else Return Me.EmptyValue
  End Function
End Class

When we give this class some text and call the normalise function, it dictionary will contain something like this:
  • ' ' = 100%
  • 't' = 92,1476925707892%
  • 'e' = 96,3602772504201%
  • 'n' = 89,4801248605917%
  • 'q' = 66,1532515407916%
  • '$' = 0,0001%

Brute force Search

The only thing left to do, is read the cypher texts. And for the length of the target message we are going to try all the different key's and store the best one.

  Function FindBest() As ByteString
    Dim Bytes(Cyphers.MaxLength) As Byte : Dim Result As New ByteString(Cyphers.MaxLength)
    For Pos As Integer = 0 To Cyphers.DecodeLength
      Result = FindBestAtPos(PosResult)
    Next : Return Result
  End Function
  Function FindBestAtPos(Pos As Integer, Result As ByteString) As ByteString
    Dim BestResult As Double = -1 : Dim BestKey As Integer = 0
    For TryKey As Integer = 0 To 255
      Dim ThisResult As Double = HypotheseAtPos(PosTryKey)
      If ThisResult >= BestResult Then BestResult = ThisResult : BestKey = TryKey
    Result(Pos) = BestKey : Return Result
  End Function

When we run the program we will find just one error in our text after some seconds. But this programming assignment is also very easy. 11 cypher texts that have used the same key is a little bit to much. But I'm only using just one `strategy` to solve the problem. We also can expand this project to multiple characters, like "th" and "and" to count. We also can fill a dictionary of known words and also use this as a tool to measure how well the resulting text `looks` like the given learning/example text of the expected language.

Language settings: Scale=0,1
' ' = 100%
't' = 92,1476925707892%
'e' = 96,3602772504201%
'n' = 89,4801248605917%
'q' = 66,1532515407916%
'$' = 0,0001%

End result:

The secret message is: Whyn using a stream cipher, never use the key more than once
We can factor the number -5 with quantum computers. We can also factor the number 1
Euler would probably enjoe that now his theorem becomes a corner stone of crypto -
The nice thing about Keeypoq is now we cryptographers can drive a lot of fancy cars
The ciphertext produced be a weak encryption algorithm looks as good as ciphertext
You don't want to buy a syt of car keys from a guy who specializes in stealing cars
There are two types of creptography - that which will keep secrets safe from your l
There are two types of cyltography: one that allows the Government to use brute for
We can see the point whery the chip is unhappy if a wrong bit is sent and consumes
A (private-key)  encryptisn scheme states 3 algorithms, namely a procedure for gene
 The Concise OxfordDictiorary (2006) de├»¬?nes crypto as the art of  writing o r sol

Encoded cipher texts

target ciphertext (decrypt this one): 

ciphertext #1:

ciphertext #2:


ciphertext #3:


ciphertext #4:


ciphertext #5:


ciphertext #6:


ciphertext #7:


ciphertext #8:


ciphertext #9:


ciphertext #10:


Saturday, 20 April 2013

All permutations in a set

Hi There...
Did a TopCoder.Com Single Round Match today and needed al permutations of a given set.

{1,2} => {{1,2},{2,1}}
{1,2,3} => {{1,2,3},{1,3,2},{2,1,3},{2,3,1},{3,1,2},{3,2,1}}
The number of permutations of set with n elements = !n (Factorial)I have writen the code, like this:

Public Function Permutations(Of T)(Items As IEnumerable(Of T)) As List(Of List(Of T))   Dim Result As New List(Of List(Of T))   If Items.Count = 1 Then     ' Count = 1 ==>> Conquer !    Dim NewList As New List(Of T)(Items)     Result.Add(NewList)     Return Result  End If   ' Count > 1 ==> Divide !  For Each Item As T In Items    Dim NewItems As New List(Of T)(Items)     NewItems.Remove(Item)     Dim Inner As List(Of List(Of T)) = Permutations(NewItems)     ' Merging: Divide and Conquer.    For Each InnerList As List(Of T) In Inner      InnerList.Add(Item)       Result.Add(InnerList)     Next   Next   Return ResultEnd Function

But after creating some tests, i made a test like this:

Dim List As New List(Of Integer)(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) Dim Result As List(Of List(Of Integer)) = Permutations.Permutations(List)

And noticed that i didn't ended as quickly as i hoped so.
It's just 10! = 3.628.800 permutations. So have re-writen the code to use only one array.
So i'm creating my memory place in the beginning and fill it recursively.
Turnsout that .NET doesn't have a Factorial function.
So had to install: `Microsoft Solver Foundation` just to get n!

Google+ Badge