Checksums are blocks of data generated from another block of data you want to store or transfer to ensure that correct data is transmitted during the process of moving data around. This is useful for data correction and security purposes. For example you could use a checksum algorithm to check if the data you download is the correct one ensuring that you do not download malicious data. Checksums can be implemented using hashes, cryptography, randomization, parity bits etc.
Another application of checksum if validating data before submitting them to the database. An example of this is when you try to submit your credit card details and any error is flagged before submission to the database. A checksum algorithm checks the validity and correctness of the credit card number you are entering, this prevent the application from having to do a search for incorrect numbers therefore reducing the load the system has to bear.
A checksum algorithm that stood out for me is Luhn’s Algorithm, and I will be making a PHP implementation of it below:
<?php
// Script to check if a number is valid using Luhn's Algorithm
$cardnumber = "4890486808";
$sum = 0;
$numlength = strlen($cardnumber);
$parity = $numlength%2 ;
for($i=0;$i<$numlength-1;$i++){
if($i%2 != $parity)
$sum=$sum + $cardnumber[$i];
elseif ($cardnumber[$i] > 4)
$sum=$sum+ 2*$cardnumber[$i] -9;
else
$sum=$sum+ 2*$cardnumber[$i];
}
echo (10 - ($sum % 10))." is the checksum digit \n";
echo $cardnumber[$numlength-1] == (10 - ($sum % 10)) ? "Correct Number":"Incorrect Number" ;
?>
In the second part, I will be testing this algorithm with a database on Docker and comparing it with an application without a checksum.
Leave a Reply