Validating Card Numbers with the Luhn Check Algorithm

In this article I want to discuss how to validate debit/credit card numbers. First I will talk about how the algorithm works on a theoretical level, and then I will present a C# implementation that you can use in your own code. Then I will show another implementation that allows you to generate multiple valid test card numbers.

The algorithm I want to discuss here is called the Luhn Algorithm. It is also known as the mod 10 check. The Luhn algorithm is a simple checksum formula used to validate a variety of identification numbers, but the most common use is credit card numbers. The algorithm was invented by an IBM scientist, Hans Peter Luhn.

I have had many requests for a Visual Studio solution project with the APR code and unit tests in. I have open sourced the code and put it onto Codeplex to make it easy for you to access.

In this article I want to discuss Annual Percentage Rates (APR) and how you calculate them including some sample code. APR is a term you will see on several different lending products including loans, overdrafts, credit cards and mortgages. It is a legal requirement to show the APR on products where you borrow money, (certainly in the UK). The APR is meant to make it easier to make fairer comparisons of different products. To make things even more confusing there are 2 types of APR, Personal APR and Typical APR.

The APR is essentially how much your borrowing will cost over the period of an average year, over the term of your debt. It takes into account interest charged as well as any additional fees (such as arrangement fees, or annual fees) youâ€™ll have to pay. It also considers the frequency with which interest is charged on your borrowing, as this as an impact on how much you will pay as well.

Cryptography in .NET : Hybrid Encryption Protocols

This is the 4th and final article in a series on cryptography with .NET. So far in this series we have looked at some of the built in cryptographic primitives build into .NET including, Symmetric Encryption with AES, Asymmetric encryption using RSA, Cryptographic random number generation and hashing.

What I want to do in this final part is talk about using these different cryptographic primitives to do what is called Hybrid Encryption.

What is Hybrid Encryption?

So, what is hybrid encryption? Letâ€™s start off with Wikipediaâ€™sÂ definition.

In cryptography, public-key cryptosystems are convenient in that they do not require the sender and receiver to share a common secret in order to communicate securely (among other useful properties). However, they often rely on complicated mathematical computations and are thus generally much more inefficient than comparable symmetric-key cryptosystems. In many applications, the high cost of encrypting long messages in a public-key cryptosystem can be prohibitive. A hybrid cryptosystem is one which combines the convenience of a public-key cryptosystem with the efficiency of a symmetric-key cryptosystem.

A hybrid cryptosystem can be constructed using any two separate cryptosystems:

• a key encapsulation scheme, which is a public-key cryptosystem, and
• a data encapsulation scheme, which is a symmetric-key cryptosystem.

The hybrid cryptosystem is itself a public-key system, whoâ€™s public and private keys are the same as in the key encapsulation scheme.

Note that for very long messages the bulk of the work in encryption/decryption is done by the more efficient symmetric-key scheme, while the inefficient public-key scheme is used only to encrypt/decrypt a short key value.

Cryptography in .NET : Random Numbers and Hashes

This is the 3rdÂ part in a short series on cryptography in .NET. In the previous 2 articles I covered using Symmetric algorithms like AES and Asymmetric algorithms like RSA. In this section I want to cover random number generation and hashing. This will lead into the final article which will be about combining cryptographic primitives to create hybrid encryption protocols.

The primitive I want to discuss is generating cryptographically strong random numbers. This is useful if you want to generate random session keys for AES for example. To generate a random number you use the RNGCryptoServiceProvider class in .NET. Once you have constructed the object you just call GetBytes() and pass in the length in bytes of the random number you want to generate.

In a previous article on Safe Pad I explained why I decided to write a little application called Safe Pad which I have open sourced on Code Plex under the GNU Public license.

This documentation is against the first Safe Pad release, version 1.0.

In this article I am going to cover how the code is structured. To demonstrate the code structure I will use the Architectural Dependency diagrams in Visual Studio 2012.

The main solution file is split into 3 projects. There is the SafePadClientLibrary which contains the code for encrypting the documents, compression, and the handling of the SafePad file format. The domain objects in this library contain all the important routines for making the project work.

Safe Pad: Secure Text Editor Open Source Project

Recently I have been doing a bit of travelling for work to visit vendors and this has involved some lengthy train journeys. On these journeys I decided to set about writing a small little application that I had a use for. Initially I wanted a password vault, but when I thought about it more, I realised I wanted a secure way to store all sorts of information, like passwords, license keys, financial data etc.

So, whilst whiling away the hours on the train I started developing Safe Pad. The application is a pretty typical Rich Text based editor, but when you save your documents they are compressed and then stored by encrypting it with AES 256 three times using 2 passwords. This is a similar theory as to when the DES algorithms life was extended by using it to triple encrypt.

I have developed the program enough to a stable 1.0 release. It is quite basic, but then again it doesn’t need to be complicated. I have released the source code on CodePlex under the GNU Public license and this marks my first foray into the world of open source software development. Feel free to download the application if you think it will be useful to you. It costs nothing. Â If you are not interested in messing around with the source code, then there is an installer you can use to install the application. If you feel like adding some features, then the source code is available for you to play around with.

I have also written a blog post explaining the solution and code structure of Safe Pad should anyone wish to contribute to it.

Compressing Data in .NET

I was writing some code the other night on a little pet project I am working on and I needed to persist some data to disc. The data was quite large so I needed to compress it first. I have not used any of the compression libraries in .NET before so I had a little investigation and wrote the static methods below.

They are very easy to use, just pass in aÂ  byte array to compress and recieve a compressed byte array back out, and visa versa to decompress the data.

I thought IÂ  would share these code snippets as they are quite useful. Enjoy.

```private static byte[] Compress(byte[] input)
{
byte[] compressesData;

using (var outputStream = new MemoryStream())
{
using (var zip = new GZipStream(outputStream, CompressionMode.Compress))
{
zip.Write(input, 0, input.Length);
}

compressesData = outputStream.ToArray();
}

return compressesData;
}

private static byte[] Decompress(byte[] input)
{
byte[] decompressedData;

using (var outputStream = new MemoryStream())
{
using (var inputStream = new MemoryStream(input))
{
using (var zip = new GZipStream(inputStream, CompressionMode.Decompress))
{
zip.CopyTo(outputStream);
}
}

decompressedData = outputStream.ToArray();
}

return decompressedData;
}
```

Cryptography in .NET : RSA

This is the 2nd part in a small series on using encryption primitives in .NET. In the first article I concentrated on symmetric cryptography and more specifically the AES algorithm. In this article I will take a brief look at Asymmetric cryptography using the RSA system.

RSA is an algorithm for public-key cryptography that is based on the presumed difficulty of factoring large integers, the factoring problem. Â RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman, who first publicly described the algorithm in 1977. Clifford Cocks, an English mathematician, had developed an equivalent system in 1973, but it was classified until 1997.

A user of RSA creates and then publishes the product of two large prime numbers, along with an auxiliary value, as their public key. The prime factors must be kept secret. Anyone can use the public key to encrypt a message, but with currently published methods, if the public key is large enough, only someone with knowledge of the prime factors can feasibly decode the message. Whether breaking RSA encryption is as hard as factoring is an open question known as the RSA problem.

The AES symmetric process is classed as an algorithm where the plain text goes through multiple computation rounds to produce the cipher text. RSA is different in that is it a mathematical process. I wonâ€™t go into too much detail of how the keys are generated, but as stated above it is all around the complexity of factoring large prime numbers. The actual encryption process is based around modular arithmetic. For more detailed information on how this works check out this very useful Wikipedia page.

Checking a User Exists in Active Directory

This isn’t a long post, but just a useful snippet of code. I was working on some code for a system this afternoon and I needed to check that a username was a valid user in ActiveDirectory using C#. This isn’t something I have had to code before, so I thought I would share this useful nugget of code. I hope you find it useful.

```using System;
using System.Collections.Generic;
using System.Linq;
using System.DirectoryServices.AccountManagement;

namespace ActiveDirectory
{
public static class ActiveDirectory
{
{
using (var domainContext = new PrincipalContext(ContextType.Domain, domain))
{
using (var user = new UserPrincipal(domainContext))
{

using (var pS = new PrincipalSearcher())
{
pS.QueryFilter = user;

using (PrincipalSearchResult<Principal> results = pS.FindAll())
{
if (results != null && results.Count() > 0)
{
return true;
}
}
}
}
}

return false;
}
}
}
```

Cryptography in .NET : Advanced Encryption Standard (AES)

I have released an Open Source libray under the GPL 3.0 license called Block Encrypter that builds on the code discussed in this article. If you need to do reliable and secure symmedtric encryption then this library would be very useful to you.

I thought I would start a little series on using some of the cryptography primitives in .NET. Cryptography and Encryption is something that most developers working on enterprise applications will come across, especially if you work in the financial services industry.

Whilst cryptography is a fascinating subject and the design of these algorithms is very interesting, I do not recommend using an algorithm that you have designed yourself. The standard algorithms in practice today have been through lots of analysis by experts both in private industry and governments all around the world trying to find faults and weaknesses, so you are much better off using these recommended systems.

The main algorithms fall into 2 categories, Symmetric encryption and Asymmetric encryption. Symmetric encryption contains algorithms that are based solely on an encryption key. For example, if you encrypt some plaintext with Key1 you get a cipher text out the other end. If you then decrypt the cipher text with the same key (Key1) you will get back to the original plaintext.

Asymmetric encryption works by having 2 keys, a public and private key. These keys are mathematically derived from each other. The public key can be used by anyone and the private key has to be kept secret. I will talk about asymmetric encryption and more specifically RSA in another post.

For this first article I am going to look at the AES symmetric algorithm. AES stands for the Advanced Encryption Standard. This was a competition winner when the National Institute of Standards and Technology ran a contest to replace the already broken DES algorithm.

What I will show in this article is a good practical implementation of AES in .NET. We will start with the following interface. The interface contains 2 methods, Encrypt and Decrypt. They methods take cipher text/plaintext and an encryption key.

```using System;

namespace CryptoLibrary
{
public interface IAES
{
string Decrypt(string ciphertext, string key);
string Encrypt(string plainText, string key);
}
}
```