Blog Archives

Google Authenticator



As promised a while ago I am going to describe the Google Authenticator today. I do not use my own example source code this time. There is a really nice one here that I will explain. Download the source code and get some extra information from this post. This should be enough know-how to use the Google Authenticator in your own application afterwards.

What is the Google Authenticator?
The Google Authenticator is a program that allows time based passwords. It makes the online identification process much safer. You enter your Id, your password and an extra time based password. A third-party can hardly know the time based password. Even if there is a spy program on your PC that reads all your key inputs, then the hacker only has less than 30 seconds to exploit the opportunity. Otherwise he cannot use your credentials. The time component changes constantly. This is a pretty safe approach.
To steal your identity, the hacker needs to get access to the server database and decrypt your information. This is much more difficult than reading your password by using a key Trojan.

What is TOTP?

Once again our example program is using WPF.
The XAML is pretty much straight forward. Each element (TextBlock or Image) is using Binding to the underlying object. Just the Hmac TextBlock is less intuitive. The text consists of 3 TextBlocks, which in fact look like one. The green text is the second TextBlock. There is no method to write all text into one TextBlock and then color it. This would be far more complex than this 3 TextBlock solution.



property binding


Identity Identity string
Secret Secret string
QR code QRCodeUrl Image
Timestamp Timestamp string
Hmac HmacPart1, HmacPart2, HmacPart3 string
One-time password OneTimePassword string
Seconds to go SecondsToGo string


The C# source code has some hyperlinks. You should follow them in case you want to learn some detailed background information. You don’t have to do this. To apply the code in your program it should be enough to study and replicate the example source code. This code is really short and I appreciate this a lot. Many programmers make things far more complicated than needed. Are they trying to show off? I don’t know.

Let’s start from the top now.
The DispatcherTimer is the corresponding class for the good old System.Windows.Forms.Timer class. We are not using WinForms anymore. The idea behind the DispatcherTimer is that the timer fires on the Dispatcher thread. This thread is the same that your window is using. Any other thread could freeze your application.
Do not use the System.Threading.Timer class. This class is neither WPF nor WinForms related. It fires on any thread. You must not access WPF elements on arbitrary threads. On the other hand you should use the System.Threading.Timer class in case you do not want to access WPF. Don’t waste precious time of the Dispatcher thread.

The DispatcherTimer fires each 500 ms (=half second) and assigns the actual value of the 30 second countdown to the property SecondsToGo.

The properties Secret and Identity are initialized with arbitrary example data.
Then the DataContext is set. This enables the data binding between the (XAML) window and the (C#) code.

public MainWindow() {

   var timer = new DispatcherTimer();
   timer.Interval = TimeSpan.FromMilliseconds(500);
   timer.Tick += (s, e) => SecondsToGo = 30 - Convert.ToInt32(GetUnixTimestamp() % 30);
   timer.IsEnabled = true;

   Secret = new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x21, 0xDE, 0xAD, 0xBE, 0xEF };
   Identity = "";

   DataContext = this;

You may have noticed already that the MainWindow class implements the interface INotifyPropertyChanged. This exposes a WPF event called PropertyChanged, which is used to notify clients via binding that a property value has changed.

namespace System.ComponentModel {
  public interface INotifyPropertyChanged {
    // Occurs when a property value changes.
    event PropertyChangedEventHandler PropertyChanged;

You notify a client (UI) with the property name (string) rather than a delegate.
The standard WPF pattern looks like this:

public event PropertyChangedEventHandler PropertyChanged;  // INotifyPropertyChanged implementation

protected void OnPropertyChanged(string xPropertyName) {
   PropertyChangedEventHandler h = PropertyChanged;
   if (h == null) return;
   h(this, new PropertyChangedEventArgs(xPropertyName));
} //

private string _MyProperty;
public string  MyProperty { 
  get{ return _MyProperty; } 
  set { _MyProperty = value; OnPropertyChanged(“MyProperty”); } 
} //

And here is the source code from the GoogleAuthenticator example:

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName) {
 if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

private int _secondsToGo;
public int SecondsToGo {
   get { return _secondsToGo; }
   private set { _secondsToGo = value; OnPropertyChanged("SecondsToGo"); if (SecondsToGo == 30) CalculateOneTimePassword(); }

You can find that pattern many times in today’s example source code. Be aware that all properties use the same event, which is PropertyChanged. This makes your code look neat, but on the other hand you unfortunately start working with strings instead of delegates. It is part of the MVVM concept to separate code and GUI. For sure it makes debugging much more difficult and code execution slower.

Just to highlight it again. The Hmac consists of three elements. Therefore the property looks like this:

public byte[] Hmac {
  get { return _hmac; }
  private set { _hmac = value; OnPropertyChanged("Hmac"); OnPropertyChanged("HmacPart1"); OnPropertyChanged("HmacPart2"); OnPropertyChanged("HmacPart3"); }

What is an Hmac? To make complex interrelations easier, let’s reduce the Hmac description to “a long calculated key”, which is used to determine our time based password. Therefore to generate the key you need some kind of time input. The other component is a static password (=Secret). I added comments in the following code excerpt:

private void CalculateOneTimePassword() {
  // Get the number of seconds since 1/1/1970 and devide them by 30 seconds.
  // Thus one Timestamp unit is 30 seconds.
  Timestamp = Convert.ToInt64(GetUnixTimestamp() / 30);

  // Convert the 64 bit integer Timestamp to a byte array (8 bytes).
  // eg. ba d9 c7 02 00 00 00 00
  // Then reverse them (=> 00 00 00 00 02 c7 d9 ba) and write the result to the byte array "data".
   var data = BitConverter.GetBytes(Timestamp).Reverse().ToArray();

  // Generate the Hmac key from your password (byte array) and time (byte array).
  Hmac = new HMACSHA1(Secret).ComputeHash(data);

  // Bit-operation: Get the last 4 bits of the Hmac. The results are always equal to or between 0 and 15.
  // The offset determines the area of the Hmac that is used to generate the time based password.
  Offset = Hmac.Last() & 0x0F;

  // The Hmac is 20 bytes long. A block of 4 bytes is used for the OneTimePassword, which changes each 30 seconds.
  // 15 is the highest Offset. Therefore the last used byte is number 18 (first byte is zero based).
  // The 19th (=last) byte is the Offset. More precisely the <a href="" title="Wiki Nibble Byte" target="_blank">right nibble</a> of the 19th byte is the Offset value.
  // Bit masks are applied on the selected Hmac block to limit the number. The resulting bits are rotated to the left and added together.
  // Basically we are looking at a manual "bit to integer" conversion.
  // the result is then devided by 1,000,000 and only the remainder is taken. Consequently all results are less than 1,000,000.
  // (The bit mask 0xff is useless. I guess it was used to emphasize the technique for readability purposes. 0x7f does make sense.)
  OneTimePassword = (
         ((Hmac[Offset + 0] & 0x7f) << 24) |
         ((Hmac[Offset + 1] & 0xff) << 16) |
         ((Hmac[Offset + 2] & 0xff) << 8) |
         (Hmac[Offset + 3] & 0xff)) % 1000000;

When I looked at the program I was trying to find the bitmap for the QR code. You would expect a method somewhere to convert bytes to an image. But this is not the case.
The GetQRCodeUrl method generates a Url. Follow this Url and you will see that it opens an image in your browser. Google does the work for you.
The programmer of that example code has also added the Url to the description on how to generate such QR code Url. Well done! My advice is to have a quick look at it.

private string GetQRCodeUrl() {
  var base32Secret = Base32.Encode(Secret);
  return String.Format("|0&cht=qr&chl=otpauth://totp/{0}%3Fsecret%3D{1}", Identity, base32Secret);

Now we have all bits and pieces to use the Google Authenticator. But how?

1) Ask for a user identification and a password. For instance user “” and password “Strong5rThan$trong!”.
2) Convert the password to a byte array.
3) Generate the QR code.
4) The user can scan this QR code with his android cell phone. Press “Set up account” followed by “Scan a barcode” in the Google Authenticator app.
5) The new account appears and updates in the Authenticator app. The Identity and Secret were encoded in the QR code. This is why the app knows your name already.
6) From now on you can ask for the Id, the password and the time based password.
7) Make sure to have a plan B in place. The user might lose access to his Google Authenticator app. You have to provide a new login then.

Btw. I do know some people, who do not lock their tablet PC or cell phone. The Google Authenticator obviously is not for these kind of people. The problem is not behind the screen … it is in front of the screen.


WPF Datagrid formatting (part 2, advanced)


We stick to the previous DataGrid example and enhance it now.

The improvements/additions are:

  • Cells are vertically centered now.
  • Copy/paste includes the header text.
  • Templates cannot be copied/pasted. The DataGrid does not know what property it has to read. Therefore a ClipboardContentBinding was added.
    ClipboardContentBinding="{Binding Birthday}
  • A yellow smiley is drawn on a Canvas with ellipses and a Bézier curve.
  • The birthday string is formatted.
  • The DataGrid rows use alternating colors.
  • CheckBoxes are centered in the cells.
  • A bit closer to hardcore: DatePicker
    The method to remove all borders requires slightly more know-how. The required information was taken from my earlier post WPF Control Templates (part 1). Also the background color of the DatePickerTextBox is made transparent. This is done without defining a new template for the DatePicker.

    The XAML definition

    <DatePicker SelectedDate="{Binding Birthday, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"  BorderThickness="0" Loaded="DataGrid_DatePicker_Loaded" />


        private void DataGrid_DatePicker_Loaded(object sender, RoutedEventArgs e) {...}

    which in turn calls:

            private static void RemoveBorders(DependencyObject xDependencyObject) {...}
  • RowHeaders were added. On the internet you can find a lot of ToggleButton examples. You face the same code roots over and over again. To avoid coming up with a similar example I used a button with a +/- sign instead. This way you can easily change the code and replace the text by custom images.
  • My advice here is: Play with the FrozenColumnCount property. I am sure you will need it someday.
  • This example uses more templates than the last one.
  • RowDetailsTemplate was added. This enables expanding DataGrid rows to eg. show or enter additional information.
  • UpdateSourceTrigger makes sure you can see DataGridCell changes immediately on the RowDetailsTemplate.
    To achieve this, the class Person needs to inherit INotifyPropertyChanged.
<Window x:Class="WpfDatagrid.MainWindow"
        Title="MainWindow" Height="350" Width="525">


        <!-- DataGrid: header style -->
        <Style TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="VerticalContentAlignment" Value="Center" />
            <Setter Property="SeparatorBrush" Value="WhiteSmoke" />
            <Setter Property="FontWeight" Value="Bold" />

        <!--DataGrid: vertical/horizontal text alignment -->
        <Style x:Key="AlignRight" TargetType="{x:Type TextBlock}">
            <Setter Property="HorizontalAlignment" Value="Right" />
            <Setter	Property="VerticalAlignment" Value="Center" />
        <Style x:Key="AlignLeft" TargetType="{x:Type TextBlock}">
            <Setter Property="HorizontalAlignment" Value="Left" />
            <Setter	Property="VerticalAlignment" Value="Center" />

        <!--DataGrid: center the CheckBox -->
        <Style x:Key="AlignCheckBox" TargetType="{x:Type DataGridCell}">
            <Setter Property="Template">
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Grid Background="{TemplateBinding Background}">
                            <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" />

        <!-- DataGrid: template for expandable area -->
        <DataTemplate x:Key="TemplateRowDetails">
                <Canvas DockPanel.Dock="Left" Width="60">
                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                            <GradientStop Color="#FF061246" Offset="0.497"/>
                            <GradientStop Color="#FF7F7FC9" Offset="1"/>
                    <Ellipse Fill="Yellow" Height="50" Width="50" StrokeThickness="2" Stroke="Black" Canvas.Left="5" Canvas.Top="5" />
                    <Ellipse Fill="Black" Height="12" Width="8" Canvas.Left="17" Canvas.Top="20" />
                    <Ellipse Fill="Black" Height="12" Width="8" Canvas.Left="37" Canvas.Top="20" />
                    <Path Stroke="Black" StrokeThickness="3">
                                        <PathFigure StartPoint="15,37">
                                                    <QuadraticBezierSegment Point1="30,52" Point2="45,37" />
                <TextBlock DockPanel.Dock="Top" FontSize="12" FontWeight="Bold"	Text="{Binding FirstName}" />
                <TextBlock DockPanel.Dock="Top" FontSize="12" FontWeight="Bold"	Text="{Binding LastName}" />
                <TextBlock DockPanel.Dock="Top" FontSize="12" FontWeight="Bold"	Text="{Binding Birthday, StringFormat={}{0:dd MMMM yyyy}}" />
                <TextBlock DockPanel.Dock="Top" FontSize="12" FontWeight="Bold"	Text="{Binding Homepage}" />

        <!-- advice: play with the property FrozenColumnCount -->
        <DataGrid AlternatingRowBackground="PeachPuff" 
                  RowDetailsTemplate="{StaticResource TemplateRowDetails}"
                  ColumnHeaderHeight="{Binding RowHeight, RelativeSource={RelativeSource Self}}">

                <Style TargetType="DataGridRow">
                    <Setter Property="DetailsVisibility" Value="Collapsed" />

            <!-- DataGrid: RowHeader -->
                    <Button Click="DataGridRowHeader_Button_Click" Cursor="Hand" HorizontalAlignment="Center" >
                            <Style TargetType="Button">
                                    <Setter Property="VerticalAlignment" Value="Top" />
                                    <Setter Property="Content" Value="+" />
                                    <Setter Property="FontStretch" Value="UltraExpanded" />
                                    <Setter Property="FontWeight" Value="Bold" />
                                    <Setter Property="Height" Value="20" />
                                    <Setter Property= "Width" Value="20" />
                                    <!-- <Setter Property="Width" Value="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}" /> -->
                                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}},Path=DetailsVisibility}" Value="Visible">
                                        <Setter Property="Background" Value="Salmon" />
                                        <Setter Property="Content" Value="-" />
                                        <Setter Property="Height" Value="86" />

            <!-- DataGrid: Row color when selected -->
                        <Setter Property="DataGridCell.VerticalContentAlignment" Value="Center" />
                        <Trigger Property="DataGridCell.IsSelected" Value="True">
                            <Setter Property="DataGridCell.Background" Value="SteelBlue" />

                <!-- Column: Alive -->
                <DataGridCheckBoxColumn Header="Alive" Binding="{Binding Alive, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" CellStyle="{StaticResource AlignCheckBox}" />

                <!-- Column: Name -->
                <DataGridTextColumn Header="Name" Binding="{Binding FirstName, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" ElementStyle="{StaticResource AlignLeft}" />

                <!-- Column: LastName -->
                <DataGridTextColumn Header="LastName" Binding="{Binding LastName, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" ElementStyle="{StaticResource AlignLeft}" />

                <!-- Column: Birthday -->
                <DataGridTemplateColumn Header="Birthday" SortMemberPath="Birthday.Day" ClipboardContentBinding="{Binding Birthday}">
                            <DatePicker SelectedDate="{Binding Birthday, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"  BorderThickness="0" Loaded="DataGrid_DatePicker_Loaded" />

                <!-- Column: Age -->
                <DataGridTextColumn Header="Age" Binding="{Binding Age, StringFormat=N2}" ElementStyle="{StaticResource AlignRight}" IsReadOnly="True" />

                <!-- Column: Homepage -->
                <DataGridHyperlinkColumn Header="Homepage" Binding="{Binding Homepage}" IsReadOnly="True">
                            <EventSetter Event="Hyperlink.Click" Handler="Hyperlink_Clicked"/>
                            <Setter Property="TextBlock.HorizontalAlignment" Value="Left" />
                            <Setter Property="TextBlock.VerticalAlignment" Value="Center" />


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Media;

namespace WpfDatagrid {

  public partial class MainWindow : Window {

    public class Person : INotifyPropertyChanged {
      public event PropertyChangedEventHandler PropertyChanged;
      protected void OnPropertyChanged(string xName) {
        PropertyChangedEventHandler h = PropertyChanged;
        if (h == null) return;
        h(this, new PropertyChangedEventArgs(xName));
      } //

      private bool _Alive;
      public bool Alive { get { return _Alive; } set { _Alive = value; OnPropertyChanged("Alive"); } }

      private string _FirstName;
      public string FirstName { get { return _FirstName; } set { _FirstName = value; OnPropertyChanged("FirstName"); } }

      private string _LastName;
      public string LastName { get { return _LastName; } set { _LastName = value; OnPropertyChanged("LastName"); } }

      public double Age { get { return DateTime.Now.Subtract(Birthday).TotalDays / 365; } }
      public string Homepage { get; set; }

      private DateTime _Birthday;
      public DateTime Birthday { get { return _Birthday; } set { _Birthday = value; OnPropertyChanged("Birthday"); } }

    } // class

    public MainWindow() {
    } //

    // set the window DataContext
    private void Window_Loaded(object sender, RoutedEventArgs e) {
      List<Person> lPersons = new List<Person>();
      lPersons.Add(new Person() { FirstName = "Liza", LastName = "Minnelli", Birthday = new DateTime(1946, 03, 12), Alive = true, Homepage = "" });
      lPersons.Add(new Person() { FirstName = "Bastian", LastName = "Ohta", Birthday = new DateTime(1975, 03, 13), Alive = true, Homepage = "" });
      lPersons.Add(new Person() { FirstName = "Albert", LastName = "Einstein", Birthday = new DateTime(1879, 03, 14), Alive = false, Homepage = "" });
      lPersons.Add(new Person() { FirstName = "Coenraad", LastName = "van Houten", Birthday = new DateTime(1801, 03, 15), Alive = false, Homepage = "" });
      lPersons.Add(new Person() { FirstName = "Andrew", LastName = "Miller-Jones", Birthday = new DateTime(1910, 03, 16), Alive = false, Homepage = "dead as a Dodo" });
      lPersons.Add(new Person() { FirstName = "Gottlieb", LastName = "Daimler", Birthday = new DateTime(1834, 03, 17), Alive = false, Homepage = "" });
      lPersons.Add(new Person() { FirstName = "Rudolf", LastName = "Diesel", Birthday = new DateTime(1858, 03, 18), Alive = false, Homepage = "" });
      DataContext = lPersons;
    } //

    // exit the application
    private void Window_Closed(object sender, EventArgs e) {
    } //

    // open the hyperlink in a browser
    private void Hyperlink_Clicked(object sender, RoutedEventArgs e) {
      try {
        Hyperlink lHyperlink = e.OriginalSource as Hyperlink;
        string lUri = lHyperlink.NavigateUri.OriginalString;
      catch (Exception ex) { MessageBox.Show(ex.Message); }
    } //

    // find the correct DataGridRow and set the DetailsVisibility
    private void DataGridRowHeader_Button_Click(object sender, RoutedEventArgs e) {
      DependencyObject lDependencyObject = e.OriginalSource as DependencyObject;
      //Button lButton = lDependencyObject as Button;      
      //if (lButton == null) return;            
      while (!(lDependencyObject is DataGridRow) && lDependencyObject != null) lDependencyObject = VisualTreeHelper.GetParent(lDependencyObject);
      DataGridRow lRow = lDependencyObject as DataGridRow;
      if (lRow == null) return;
      //lRow.IsSelected = (lRow.DetailsVisibility != Visibility.Visible);            
      lRow.DetailsVisibility = lRow.DetailsVisibility == System.Windows.Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;
    } //

    private void DataGrid_DatePicker_Loaded(object sender, RoutedEventArgs e) {
      // get the DatePicker control
      DatePicker lDatePicker = sender as DatePicker;
      lDatePicker.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;

      // find the inner textbox and adjust the Background colour
      DatePickerTextBox lInnerTextBox = lDatePicker.Template.FindName("PART_TextBox", lDatePicker) as DatePickerTextBox;
      lInnerTextBox.Background = Brushes.Transparent;
      lInnerTextBox.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
      lInnerTextBox.Height = lDatePicker.ActualHeight - 2;

      // remove watermark
      ContentControl lWatermark = lInnerTextBox.Template.FindName("PART_Watermark", lInnerTextBox) as ContentControl;
      lWatermark.IsHitTestVisible = false;
      lWatermark.Focusable = false;
      lWatermark.Visibility = System.Windows.Visibility.Collapsed;
      lWatermark.Opacity = 0;

      // just as demo
      ContentControl lContentHost = lInnerTextBox.Template.FindName("PART_ContentHost", lInnerTextBox) as ContentControl;

      // remove ugly borders
      RemoveBorders(lInnerTextBox);  // hardcore 🙂      
    } //

    private static void RemoveBorders(DependencyObject xDependencyObject) {
      for (int i = 0, n = VisualTreeHelper.GetChildrenCount(xDependencyObject); i < n; i++) {
        DependencyObject lDependencyObject = VisualTreeHelper.GetChild(xDependencyObject, i);
        Border lBorder = lDependencyObject as Border;
        if (lBorder == null) continue;
        lBorder.BorderBrush = Brushes.Transparent;
    } //

  } // class
} // namespace