Luhn algorithm’s usage in Credit Cards


The Luhn algorithm or Luhn formula, also known as the “modulus 10” or “mod 10” algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, Etc.¬†Most credit cards and many government identification numbers use the algorithm as a simple method of distinguishing valid numbers from mistyped or otherwise incorrect numbers.

Most credit cards contain a check digit, which is the digit at the end of the credit card number. The first part of the credit-card number identifies the type of credit card (Visa, MasterCard, American Express,Discover etc.), and the middle digits identify the bank and customer.

Visa – 4
MasterCard – 5
American Express – 3
Discover – 6

Most of the companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:

  • Here’s how the algorithm works for verifying credit cards;

The math is quite simple behind the algorithm.

1). Reverse the order of the digits in the number.
2). Take the first, third, … and every other odd digit in the reversed digits and sum them to form the partial sum s1.
3). Taking the second, fourth … and every other even digit in the reversed digits:
4).Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits
5).Sum the partial sums of the even digits to form s2

If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.

For example, if the trial number is 5105 1051 0510 5100 lets apply the luhn algorithm

Reverse the digits : 0 0 1 5 0 1 5 0 1 5 0 1 5 0 1 5
Sum the odd digits : 0 + 1 +0 +5+1+0+5+1 = 13 = s1

even digits : 0,5,1,0,5,1,0,5
twice the even digits : 0, 10 , 2, 0, 10,2,0,10

Since 10 is > 9 sum of the digit of 10 is 1+0 = 1

So the sum of the last = 0 + 1 + 2+0+1+2+0+1 = 7 = s2

s1 + s2 = 20 which ends in zero which means that 5105 1051 0510 5100 passes the Luhn test.

Moreover since starting digit is 5 this should be a MasterCard. ūüôā

The following sample code in c# illustrate particular credit card number whether itself pass the Luhn algorithm test or not.

public bool IsPassesLuhnTest(string cardNumber)
     //Clean the card number- remove dashes and spaces
     cardNumber = cardNumber.Replace("-", "").Replace(" ", "");

     //Convert card number into digits array
     int[] digits = new int[cardNumber.Length];
     for (int len = 0; len < cardNumber.Length; len++)
         digits[len] = Int32.Parse(cardNumber.Substring(len, 1));
     //Luhn Algorithm
     int sum = 0;
     bool alt = false;
     for (int i = digits.Length - 1; i >= 0; i--)
          int curDigit = digits[i];
          if (alt)
               curDigit *= 2;
              if (curDigit > 9)
                   curDigit -= 9;
           sum += curDigit;
           alt = !alt;
     //If Mod 10 equals 0, the test is ok and it will return true
     return sum % 10 == 0;


Dependency Injection using Unity with C#

Hello¬†guys, Today I will introduce you to the Microsoft Unity Framework and also take you through its dependency injection feature. First of all we will see “What is Dependency Injection.?”.In simply Dependency Injection is decouples the module dependencies in your application by creating and injecting the object at runtime.

The dependency of a class can be injected at runtime using the Dependency Injection mechanism. Unity will help us to handle those things very easily.

It is a two-step process.

  • Register the dependency
  • then resolve the concrete business module class.

RegisterType and RegisterInstance methods of the UnityContainer classes can be used to perform the Register operation. And Resolve method can be used for creating the concrete business class instance.

Today i will show you guys how should we use the NamedRegistration for the handling Dependency Injection. In the real world applications there might be situations like we want to dynamically create objects according to the requirements. When using Unity, Unity knows that which class object is need to be created.

Let’s suppose example like this. According the the user input we need to change the database which is going to save the data. Here i will use SQL and Oracle.

For the explanation we will create a console application and do dependency constructor injection using Unity. Then you need to add the Unity via NuGet.  So go to the NuGet package manager and search for the unity and install it.


Continue reading

Build Real time Instagram App with ionic and Firebase

Hello guys, Today I’m going to show how we will use the Firebase Real Time Database for implement Instagram like application.In order to do that i’m using Ionic2 with Firebase.

So first we will configure the Firebase. So navigate to Firebase developer Console.¬†¬† You can use your gmail account to login to the Firebase Console. Once login create a new project and you can give what ever name you want. Once you create the new project go to Database section and under “Rules” and set read and write permissions to “auth == null”.¬†This will allow to¬†unauthenticated clients to access to the our created database.



And the other thing you want to do is need to add the  Firebase sdk to your application.


Continue reading

Using Factories and Web Services for Get Dynamic Data in Ionic App

In a typical Ionic mobile app has a Data Layer which uses Factories or Services to provide data to the controllers of the mobile app.¬†Those data may come from an external web service in the form of JSON or XML. Or may be from another backend services written by your self. ūüôā

In this article, I will show how to build a Data Layer for an Ionic app, wired to a web service. First of all i will clear about what are the Services and Factories in ionic application.

Services vs Factory

 app.service('YourServiceName', function () {
     this.yourFunc= function () {
         console.log('hello service');

Actually Service is a method on our module that takes a name and a function. This will defines the our service.. Once you defined the Services, we can inject and use that particular service in other components, like controller or directives. This is same as you inject other directives to your controller.

 app.controller('YourControllerName', function (YourServiceName) {

So this will give the output as “hello service” in the console. So now we will consider the factory.

app.factory('YourFactoryName', function () {
  return {
    yourFunc: function () {
      console.log('hello factory');

Well, right off the bat I’ll say they’re pretty much equivalent. Why do we have them both, then? That’s for the gods of Angular to know. They both allow us to create an object that can then be used anywhere in our app.

Most important is to realize that both are singletons in your application. Essentially, factories are functions that return the object, while services are constructor functions of the object which are instantiated with the new keyword.

Continue reading

Get the Current location Using Cordova Geolocation in ionic app

In this post i’m going to show how the cordova geolocation plugin used for iOS and Android apps that reads your phone gps location and displays it on a map. This will save you time if you are going to make location based app in ionic.¬†Now lets see how to start a new project and use CordovaGeolocation in your mobile app.

1.ionic start myapp blank myapp

3.ionic platform add android

Now make a new folder and name it as templates and make a new html file. In here i named it as map.html. In map.html

<div id="map" data-tap-disabled="true"></div>

In here note that, i named id as “map” for load the map in the view.

Now in index.html

<body ng-app="starter">

      <ion-header-bar align-title="center" class="bar-dark">
<h1 class="title">Tracker</h1>
      <script src=""></script>


Note: If you dont know how to get the API key for your project then refer my post ¬†“Using ¬† ¬† ¬† ¬† ¬† ¬† ¬†google map API for web development

Now open your Terminal (In windows Command Prompt) and change the directory to your app.For add the cordova geolocation plugin :

cordova plugin add cordova-plugin-geolocation

Now all you have to do is , add folowing to your app.js

.config(function($stateProvider, $urlRouterProvider) {

  .state('map', {
     url: '/',
     templateUrl: 'templates/map.html',
     controller: 'MapCtrl'



To get the current location then you have to create a controller for your map, i named it as MapCtrl. Dont forget to inject $cordovaGeolocation in the function

.controller('MapCtrl', function($scope, $state, $cordovaGeolocation) {
    var options = {timeout: 10000, enableHighAccuracy: true};


        var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

        var mapOptions = {
            center: latLng,
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP

        $ = new google.maps.Map(document.getElementById("map"), mapOptions);

        google.maps.event.addListenerOnce($, 'idle', function(){

            var marker = new google.maps.Marker({
                 map: $,
                 animation: google.maps.Animation.DROP,
                 position: latLng,

            var infoWindow = new google.maps.InfoWindow({
                content: "Here You Are.!"

            google.maps.event.addListener(marker, 'click', function () {
      $, marker);
    }, function(error){
         console.log("Could not get location");









Encrypt and Decrypt photos in Ubuntu Terminal


Simple file encryption is probably better done using OpenSSL. All you want to have to remember is a password. It can nearly be that simple. Linux has plenty of powerful encryption software, but what can you use if you just want to secure a couple files quickly? The openSSL toolkit works well for this. It comes installed with Ubuntu and can provide stronger encryption than you would ever need.

OpenSSL is a cryptography toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) network protocols and related cryptography standards required by them.

The openssl program is a command line tool for using the various¬†cryptography functions of OpenSSL’s crypto library from the shell. It¬†can be used for

  • Creation and management of private keys, public keys and parameters
  • Public key cryptographic operations
  • Creation of X.509 certificates, CSRs and CRLs
  • Calculation of Message Digests
  • Encryption and Decryption with Ciphers
  • SSL/TLS Client and Server Tests
  • Handling of S/MIME signed or encrypted mail
  • Time Stamp requests, generation and verification

Encypt Code:

note: make sure to change the directory

 openssl enc -des-cbc -salt -in my.jpg -out sumi.enc

After type this code in terminal then it will asked you to give a  enter des-cbc encryption password.  Remember your password. because it will need when comes to decypt the file.

Decrypt Code: Continue reading

Use SQLite in ionic framework

Hello guys, today lets see how to use SQLite database in an ionic app. When thinking about native development local storage it might be tough for someone who starting use ionic framework. Dont worry. !!! This is not much harder you guys thinking. There is a plugin called Cordova SQLite for this.  Now lets see how to start a new project and use SQLite with simple form data submition.

Note- if you guys want to build a ios app using ionic then you have to use a mac. Otherwise it won’t work.

1.ionic start myapp blank myapp

3.ionic platform add android

Its recommend to through the official ionic site and have a better idea about this technology and how its work.

Now open your project in whatever text editor you using. go to the www folder then you can see index.html and js folder, css folder and lib folder.

Now we need to add cordova plugin to working with SQLite. For that simply u can use cordova plugin add cordova-sqlite-storage. Instead of that you can use:

cordova plugin add

Then you need to add the latest version of the ng-cordova.min.js file to www/js directory. Now we need to add it on the index.html file. Make sure to include it before the cordova.js

Continue reading