HMAC functions in Delphi (HMAC_SHA256, HMAC_SHA1)

I came across HMAC (Hash-based message authentication code) functions when developing a RESTful client application in Delphi. The RESTful Web Service API required me to send HMAC_SHA256 signatures (Base64 encoded) with each HTTP request.

HMAC functions take two parameters: a key and a message. The purpose of the HMAC function is to authenticate the message and guarantee the data integrity of the message.

The cryptographic strength of the HMAC function lies on the underlying hashing function that it uses: MD5, SHA1, SHA256, etc.

So, these functions are usually are termed HMAC_SHA256, HMAC_SHA1, HMAC_MD5 to connote the core hashing function being used.

The outcome of a HMAC function is basically an array of bytes, but it is usually represented as a hexadecimal string or encoded as a Base64 string. (The RESTful Web Service API needed the Base64 encoded output).

I Googled around for a bit, but I didn’t get a clean implementation of HMAC_SHA256 in Delphi (encoded as Base64). I glued together the pieces from some questions on StackOverflow and coded an Indy based implementation that uses generics to specify the core hashing function.

Brief description: I created a helper class called THMACUtils. Note that this class uses generics to indicate the hashing algorithm (TIdHMACSHA256, TIdHMACSHA1). Three functions are provided:  the main thing happens in the HMAC(...) function; HMAC_HexStr(...) and HMAC_Base64(...) are simply decorations of the output.

unit HMAC;



  THMACUtils<T: TIdHMAC, constructor> = class
    class function HMAC(aKey, aMessage: RawByteString): TBytes;
    class function HMAC_HexStr(aKey, aMessage: RawByteString): RawByteString;
    class function HMAC_Base64(aKey, aMessage: RawByteString): RawByteString;


class function THMACUtils<T>.HMAC(aKey, aMessage: RawByteString): TBytes;
  _HMAC: T;
  if not IdSSLOpenSSL.LoadOpenSSLLibrary then Exit;
  _HMAC:= T.Create;
    _HMAC.Key := BytesOf(aKey);
    Result:= _HMAC.HashValue(BytesOf(aMessage));

class function THMACUtils<T>.HMAC_HexStr(aKey, aMessage: RawByteString): RawByteString;
  I: Byte;
  Result:= '0x';
  for I in HMAC(aKey, aMessage) do
    Result:= Result + IntToHex(I, 2);

class function THMACUtils<T>.HMAC_Base64(aKey, aMessage: RawByteString): RawByteString;
  _HMAC: TBytes;
  _HMAC:= HMAC(aKey, aMessage);
  Result:= EncodeBase64(_HMAC, Length(_HMAC));


Below there’s an example of how to use the THMACUtils class.

program HMACSample;


{$R *.res}


    Write('HMAC_SHA1("key", "message")'#9#9'= ');
    Writeln(THMACUtils<TIdHMACSHA1>.HMAC_HexStr('key', 'message' ));

    Write('HMAC_SHA256("key", "message")'#9#9'= ');
    Writeln(THMACUtils<TIdHMACSHA256>.HMAC_HexStr('key', 'message' ));

    Write('HMAC_SHA1_Base64("key", "message")'#9'= ');
    Writeln(THMACUtils<TIdHMACSHA1>.HMAC_Base64('key', 'message' ));

    Write('HMAC_SHA256_Base64("key", "message")'#9'= ');
    Writeln(THMACUtils<TIdHMACSHA256>.HMAC_Base64('key', 'message' ));


    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);

The console application above looks like this:

HMAC Sample Application Delphi
HMAC Sample Application Delphi

How to obtain an “Option C Printout” for the most recent taxation year?

When you are sponsoring a family member to come to Canada, you are required to provide an Option C Printout of your last Notice of Assessment for the most recent taxation year.

An Option C Printout is not a Notice of Assessment. An Option C Printout is a document that summarizes your income and deductions for a particular taxation year.

How to obtain an Option C Printout?

Call Canada Revenue Agency (CRA) at this number: 1 (800) 959-8281. Sometimes the number is busy; in which case try again a few minutes later until you get connected.

You will be listening to an interactive recorded message; hence, a computer will be doing the talking...

Listen carefully and select the option that allows you to get the Option C Printout.

You will need to type these three pieces of information over the phone:
  1. Social Insurance Number. 
  2. Date of Birth.
  3. Amount of Income you reported on Line 150 of your most recent taxation year.
Make sure you have the information above otherwise the computer won’t be able to authenticate you.

Once you finally enter the info, the automatic system (computer) will tell you that you have succeeded, in which case the Option C Printout will be mailed by postal mail to the address you have on record with the CRA.

For instructions about how to update (change) your address with the CRA refer to the following link:

If you think this information might be useful to others, please, click the Google Plus (G+) button at the beginning of this post. 

Coin collection - 100th Anniversary of the Canadian Arctic Expedition (year 2013)

I got the 14k Gold Coin as a wedding gift from a friend. I loved that coin immediately. Later on I bought the remaining silver coins in this collection from the Royal Canadian Mint. I must say the quality of the images below is not really good. The real coins are impeccably beautiful.

Coins from left to right, top to bottom:
  • Brilliant Fine Silver Dollar  (Mintage: 02610/20000 )
  • 14k Gold Coin (Mintage: 0218/2500)
  • Proof Fine Silver Dollar (Mintage: 12866/40000)
  • Fine Silver Proof Set (Mintage: 21285/25000)
Coin collection - 100th Anniversary of the Canadian Arctic Expedition (year 2013) - [Reverse]
Coin collection - 100th Anniversary of the Canadian Arctic Expedition (year 2013) - [Reverse]

Coin collection - 100th Anniversary of the Canadian Arctic Expedition (year 2013) - [Obverse]
Coin collection - 100th Anniversary of the Canadian Arctic Expedition (year 2013) - [Obverse]

The Canadian Arctic  Expedition 1913-1916

On the antique celluloid, the light flickers. Sled dogs move silently across the Arctic tundra. A man perched on an ice floe surveys the horizon as teams of men and dogs prepare for ice-bound travel behind him. In the distance snow-capped mountains rise into the sky like jagged shards of ice.

In grainy photos, men stand alongside makeshift fences, before shelters made of skins and furs, in open ice fields, atop sleds packed with gear. Some smile; others stare silently into the lens, arms crossed, thoughts unfathomable.

These are only a few of the approximately 4,000 photographs and more than 2,700 metres of film capturing one of the twentieth century’s most exciting moments in exploration: the Canadian Arctic  Expedition.

In 1913, Canadian Prime Minister Sir Robert Borden commissioned an expedition, led by Manitoba-born ethnologist Vilhjalmur Stefansson, to explore and map the western Canadian Arctic. Stefansson and zoologist Rudolph Anderson had travelled through the Far North the previous decade. Knowing that there was a great deal of unexplored potential in the region, Stefansson planned to continue his earlier journey, but the Government of Canada, recognizing the importance of new sovereign territory, hosted the Expedition and broadened its mission significantly. A Northern Party led by Stefansson would undertake the mapping exercise while a Southern Party led by Anderson would explorer the geology, resources, and native inhabitants of the northern mainland.

Traveling by sea and despite significant hardships, the Northern Party covered thousands of kilometres, mapping land that even the local inhabitants had never seen. The Northern Party discovered four new islands and proved that some of the geography proposed by nineteenth century expeditions was erroneous.

The Southern Party completed the full mapping of the mainland and produced 14 volumes of scientific data as well as thousands of specimens and artefacts, opening up a new world of wonder for Canadians. Their findings included information about flora and fauna never before recorded, fossil samples, and more. Their cultural research familiarized the world for the first time with the culture and way of life of the Copper Inuit and the aboriginal peoples of the Northwest Territories, Yukon Territory, Alaska and Siberia. From these Aboriginal peoples – some of whom participated in the Expedition as guides and other assistants- they collected artistic artefacts, tools, knowledge, and thousands of photographs as well as extensive film footage.

The Expedition’s artefacts, photos, and recordings enabled researchers to introduce to the rest of the world cultures that had been virtually inaccessible until that time. The artefacts have also had a broad educational legacy, forming the basis of numerous educational programs and museum exhibits, and are an important pillar of the permanent National collections of the Canadian Museum of Nature and the Canadian Museum of Civilization.

14k Gold Coin - 100th Anniversary of the Canadian Arctic Expedition

This 100-dollar coin is certified to be 14-karat gold with a metal content of 12 grams and a diameter of 27 millimetres. In this design, Canadian artist Bonnie Ross depicts several key images representative of the Canadian Arctic Expedition, including a survey team atop an ice floe taking research measurements and, in the background a stylized map of the Canadian Arctic. The obverse features the effigy of Her Majesty Queen Elizabeth II by Susanna Blunt.

Brilliant Fine Silver Dollar / Proof Fine Silver Dollar - 100th Anniversary of the Canadian Arctic Expedition

Both the brilliant uncirculated  silver dollar and the proof silver dollar in this collection  are certified to be 99.99% pure silver with a diameter of 36.07 millimetres and a weight of 23.17 grams. Designated by Canadian artist Bonnie Ross, the reverse image draws on photography from the Canadian Arctic Expedition, depicting a group of three men aboard  a dogsled, the waiting dog team before them listening for the command to move across the Arctic tundra. The skyline and horizon behind this portrait are filled with a stylized image of a compass. The obverse features the effigy of Her Majesty Queen Elizabeth II by Susana Blunt.

Fine Silver Proof Set - 100th Anniversary of the Canadian Arctic Expedition

This is the 2013 fine silver proof set of Canadian coinage. This is the only set that features the commemorative silver dollar selectively gold-plated and the gold-plated one-dollar coin depicting the common loon.

The chart below shows the characteristics of each coin in the 2013 Fine Silver Proof Set of Canadian Coinage.

Characteristics of each coin in the 2013 Fine Silver Proof Set of Canadian Coinage

Economical phone calls to Cuba

I am a Cuban immigrant living in Toronto, Canada. The most cost-effective option that I have found so far to call my family and friends in the island is Rebtel.

Your first call with Rebtel is free: once you register an account you will be given a 3 minutes free phone call. You can use these 3 minutes to call anywhere in the world for free. I used mine to call to Cuba, but you can use them to call to any international destination, including Cuba, of course.

This free call will allow you to test the quality of the service without spending any money. You are not required to enter any credit card information in order to get your 3 free minutes. So, free is free, with no compromises.

Rebtel calls to Cuba have a decent quality. It’s unusual to hear noise, broken speech or other undesirable artifacts during the call.

What about the paid calls?

Once you have exhausted your initial 3 minutes (the free ones), then you will have to pay for further calls to Cuba.

There are several options to choose from:
  • Pay as you go: this option allows you to call to mobile (cell) phones at a rate of 79.9¢ /min and fixed (land) phones at a rate of 74.9¢ /min. I really don’t use this option since it’s too expensive.
  • Cuba - Big Saver 50 minutes - 30 days: this option will allow you to buy 50 minutes for $29.90. Make the math: the rate will be 59.8¢/min. The catch here is that you will have to use these minutes within one month (30 days) of the purchase. This option is better in price, but still it is not the one I use.
  • Cuba - Max Saver 50 minutes - 7 days: this option will allow you to buy 50 minutes for $24.90. This is the best rate you will get, as low as 49.8¢/min. The only problem is that you have to consume all the minutes within one week (7 days) of the purchase. This is the option I personally use.
Choose the option that suits you best depending on how often you call to Cuba, and how long your calls are. One tip, you could buy a 50 minutes package with a friend and then split the minutes and the cost. This way you and your friend will get 25 minutes for half the price. Get it?

If you think this post might be useful to others, click the Google plus (G+) button at the beginning of this post. Thanks.

Related articles:

Proof of medical examination - Medical Report: Client Biodata and Summary (IMM 1017 Form)

As part of the Application to Sponsor a Member of the Family Class, the sponsored person and their family members are required to provide “proof” that they have undergone a medical examination.

I am sponsoring my wife to come to Canada, she lives currently in Cuba and I have been living in Toronto for the last 4 years.

When I first heard about this “proof of medical examination”, I asked myself:
  • What do they mean by “proof”?
  • How can I obtain this “proof”?
  • How does this “proof” look like?
For the purpose of sponsoring a Member of the Family Class, Citizenship and Immigration Canada (CIC) requires you to mail the IMM 1017 Form as proof that the medical examination took place with an authorized Panel Physician.

In other words, the IMM 1017 Form, also known as Medical Report: Client Biodata and Summary, is the "proof" you are looking for. This form is one page long and you will have to mail the corresponding IMM 1017 Forms not only for the sponsored person, but also for their family members (dependants), if any.

We obtained this form directly from the Panel Physician that examined my wife. We didn’t have to provide a blank form for the doctors to fill. They handled this form to my wife at the end of the medical examination.

This form does not contain the results of the medical results; it’s merely a confirmation that the person in question was examined by an authorized Panel Physician.

Below I have added for reference the IMM 1017 Form that my wife received. I erased all personal data from the form and I also scrambled the barcode. 
I wanted to share this knowledge because the information provided about this topic in the CIC website is quite slim. You should know that I am not a legal or immigration expert. I just want this information to be useful, but you use it at your own risk.

If you think this information was useful, please, consider clicking the Google plus button (G+) at the beginning of this post. Thanks!

Related article: 

How does the I-94 Arrival / Departure Record look like?

Many people incorrectly think that getting a US visa gives you a bullet proof authorization to enter the US. Wrong!

The visa gives you permission to APPLY to enter the United States.  Notice that there is a difference between “permission to apply to enter” and “permission to enter”.

With a visa you can present yourself at a US Point of Entry (like an airport) asking to enter the country. At the point of entry, you will be either allowed or denied into the country.

(You should not be denied without a proper reason. In most cases, if your visa and immigration status are in order, you will be permitted to enter the US)

Now, if you are allowed to enter the US, then an I-94 will be issue for you and stapled into your passport.

The I-94 is the Arrival / Departure Record and it says for how long you can lawfully stay in the US. You have to leave the US before the indicated time in the I-94.

So, the validity of the visa DOES NOT tell for how long you will be able to stay in the country. Instead, it indicates for how long you might appear at a point of entry asking for permission to enter the States.

The time indicated in the I-94 DOES indicate for how long you will be allowed to stay in the US.

You should return your I-94 when you leave the US. Failure to do so could mislead authorities into thinking that you remained illegally in the US. This might bring problems for you when you want to re-visit the country at a later time. So, make sure you don’t leave the US with the I-94.

The I-94 is the size of a passport’s page. I am enclosing a snapshot of the I-94 (front and back) for illustration purposes.

I-94 Form - Arrival / Departure Record (Front Side)
I-94 Form - Arrival / Departure Record (Front Side)

I-94 Form - Arrival / Departure Record (Back Side)
I-94 Form - Arrival / Departure Record (Back Side)
If you think this article was helpful, please, click the Google plus (G+) button at the beginning of this post.  Thanks!

Ah, the articles below gather some of the things I have learned in my previous visits to the US. Hopefully you will find them valuable:

Sponsorship Evaluation [IMM 5481] - Net personal income

The third question of the Sponsorship Evaluation [IMM 5481] form requires the sponsor net personal income for the 12-month period preceding the date of the application.

First, what is net personal income?

Net personal income is the money that you keep after the taxes have been deducted. Let’s say you make $80 000 a year. That’s your gross income.

After paying your taxes you end up with $57000 ( this number is just an example). This is your net income.

This question is tricky because you have to calculate the net income in the last 12 month: from the current month going back one year.

I’ll put an example: let’s say you want to send your sponsorship application on October 1st, 2013. Let’s also consider that you were paid bi-weekly. The table below lists all the payments (after taxes) made to you by your employer in the last year.

Month Number
1st Biweekly Payment
2nd Biweekly Payment
3rd Biweekly Payment
October 2012
November 2012
December 2012
January 2013
February 2013
March 2013
April 2013
May 2013
June 2013
July 2013
August 2013
September 2013

Total: $57,457.92

You will have to sum all the individual payments received in the last year. That is your net personal income.

Finally, the answer to question 3 of the Sponsorship Evaluation looks like this.

Sponsorship Evaluation [IMM 5481] - Net personal income

Sponsorship Evaluation [IMM 5481] - Net personal income
Note that some people have more than one source of income. Some other people are paid monthly (not bi-weekly). What I am trying to say is that the example above is just that: an example. You will need to adjust things depending on your own situation.

I think this post might give you an idea. If so, please, consider clicking Google+ button at the beginning of this entry.

Related Article: