There are lots of implementations for validating Luhn checksums but very few for generating them. I've come across this one however in my tests it has revealed to be buggy and I don't understand the logic behind the delta variable.
I've made this function that supposedly should generated Luhn checksums but for some reason that I haven't yet understood the generated checksums are invalid half of the time.
function Luhn($number, $iterations = 1)
{
while ($iterations-- >= 1)
{
$stack = 0;
$parity = strlen($number) % 2;
$number = str_split($number, 1);
foreach ($number as $key => $value)
{
if ($key % 2 == $parity)
{
$value *= 2;
if ($value > 9)
{
$value -= 9;
}
}
$stack += $value;
}
$stack = 10 - $stack % 10;
if ($stack == 10)
{
$stack = 0;
}
$number[] = $stack;
}
return implode('', $number);
}
Some examples:
Luhn(3); // 37, invalid
Luhn(37); // 372, valid
Luhn(372); // 3728, invalid
Luhn(3728); // 37283, valid
Luhn(37283); // 372837, invalid
Luhn(372837); // 3728375, valid
I'm validating the generated checksums against this page, what am I doing wrong here?
For future reference, here is the working function.
function Luhn($number, $iterations = 1)
{
while ($iterations-- >= 1)
{
$stack = 0;
$number = str_split(strrev($number), 1);
foreach ($number as $key => $value)
{
if ($key % 2 == 0)
{
$value = array_sum(str_split($value * 2, 1));
}
$stack += $value;
}
$stack %= 10;
if ($stack != 0)
{
$stack -= 10;
}
$number = implode('', array_reverse($number)) . abs($stack);
}
return $number;
}
I dropped the $parity variable since we don't need it for this purpose, and to verify:
function Luhn_Verify($number, $iterations = 1)
{
$result = substr($number, 0, - $iterations);
if (Luhn($result, $iterations) == $number)
{
return $result;
}
return false;
}
Edit: Sorry, I realize now that you had almost my entire answer already, you had just incorrectly determined which factor to use for which digit.
My entire answer now can be summed up with this single sentence:
You have the factor reversed, you're multiplying the wrong digits by 2 depending on the length of the number.
Take a look at the Wikipedia article on the Luhn algorithm.
The reason your checksum is invalid half the time is that with your checks, half the time your number has an odd number of digits, and then you double the wrong digit.
For 37283, when counting from the right, you get this sequence of numbers:
3 * 1 = 3 3
8 * 2 = 16 --> 1 + 6 = 7
2 * 1 = 2 2
7 * 2 = 14 --> 1 + 4 = 5
+ 3 * 1 = 3 3
= 20
The algorithm requires you to sum the individual digits from the original number, and the individual digits of the product of those "every two digits from the right".
So from the right, you sum 3 + (1 + 6) + 2 + (1 + 4) + 3, which gives you 20.
If the number you end up with ends with a zero, which 20 does, the number is valid.
Now, your question hints at you wanting to know how to generate the checksum, well, that's easy, do the following:
Tack on an extra zero, so your number goes from xyxyxyxy to xyxyxyxy0
Calculate the luhn checksum sum for the new number
Take the sum, modulus 10, so you get a single digit from 0 to 10
If the digit is 0, then congratulations, your checksum digit was a zero
Otherwise, calculate 10-digit to get what you need for the last digit, instead of that zero
Example: Number is 12345
Tack on a zero: 123450
Calculate the luhn checksum for 123450, which results in
0 5 4 3 2 1
1 2 1 2 1 2 <-- factor
0 10 4 6 2 2 <-- product
0 1 0 4 6 2 2 <-- sum these to: 0+1+0+4+6+2+2=15
Take the sum (15), modulus 10, which gives you 5
Digit (5), is not zero
Calculate 10-5, which gives you 5, the last digit should be 5.
So the result is 123455.
your php is buggy, it leads into an infinite loop.
This is the working version that I'm using, modified from your code
function Luhn($number) {
$stack = 0;
$number = str_split(strrev($number));
foreach ($number as $key => $value)
{
if ($key % 2 == 0)
{
$value = array_sum(str_split($value * 2));
}
$stack += $value;
}
$stack %= 10;
if ($stack != 0)
{
$stack -= 10; $stack = abs($stack);
}
$number = implode('', array_reverse($number));
$number = $number . strval($stack);
return $number;
}
Create a php and run in your localhost Luhn(xxxxxxxx) to confirm.
BAD
I literally cannot believe how many crummy implementations there are out there.
IDAutomation has a .NET assembly with a MOD10() function to create but it just doesn't seem to work. In Reflector the code is way too long for what it's supposed to be doing anyway.
BAD
This mess of a page which is actually currently linked to from Wikipedia(!) for Javascript has several verification implementations that don't even return the same value when I call each one.
GOOD
The page linked to from Wikipedia's Luhn page has a Javascript encoder which seems to work :
// Javascript
String.prototype.luhnGet = function()
{
var luhnArr = [[0,1,2,3,4,5,6,7,8,9],[0,2,4,6,8,1,3,5,7,9]], sum = 0;
this.replace(/\D+/g,"").replace(/[\d]/g, function(c, p, o){
sum += luhnArr[ (o.length-p)&1 ][ parseInt(c,10) ]
});
return this + ((10 - sum%10)%10);
};
alert("54511187504546384725".luhnGet());
GOOD
This very useful EE4253 page verifies the check-digit and also shows the full calculation and explanation.
GOOD
I needed C# code and ended up using this code project code:
// C#
public static int GetMod10Digit(string data)
{
int sum = 0;
bool odd = true;
for (int i = data.Length - 1; i >= 0; i--)
{
if (odd == true)
{
int tSum = Convert.ToInt32(data[i].ToString()) * 2;
if (tSum >= 10)
{
string tData = tSum.ToString();
tSum = Convert.ToInt32(tData[0].ToString()) + Convert.ToInt32(tData[1].ToString());
}
sum += tSum;
}
else
sum += Convert.ToInt32(data[i].ToString());
odd = !odd;
}
int result = (((sum / 10) + 1) * 10) - sum;
return result % 10;
}
GOOD
This validation code in C# seems to work, if a little unwieldy. I just used it to check the above was correct.
There's now a github repo based on the original question/answer. See
https://github.com/xi-project/xi-algorithm
It's also available at packagist
This is a function that could help you, it's short and it works just fine.
function isLuhnValid($number)
{
if (empty($number))
return false;
$_j = 0;
$_base = str_split($number);
$_sum = array_pop($_base);
while (($_actual = array_pop($_base)) !== null) {
if ($_j % 2 == 0) {
$_actual *= 2;
if ($_actual > 9)
$_actual -= 9;
}
$_j++;
$_sum += $_actual;
}
return $_sum % 10 === 0;
}
Since the other answers that displayed or linked to C# weren't working, I've added a tested and more explanatory C# version:
/// <summary>
/// Calculates Luhn Check Digit based on
/// https://en.wikipedia.org/wiki/Luhn_algorithm
/// </summary>
/// <param name="digits">The digits EXCLUDING the check digit on the end.
/// The check digit should be compared against the result of this method.
/// </param>
/// <returns>The correct checkDigit</returns>
public static int CalculateLuhnCheckDigit(int[] digits)
{
int sum = 0;
bool isMultiplyByTwo = false;
//Start the summing going right to left
for (int index = digits.Length-1; index >= 0; --index)
{
int digit = digits[index];
//Every other digit should be multipled by two.
if (isMultiplyByTwo)
digit *= 2;
//When the digit becomes 2 digits (due to digit*2),
//we add the two digits together.
if (digit > 9)
digit = digit.ToString()
.Sum(character => (int)char.GetNumericValue(character));
sum += digit;
isMultiplyByTwo = !isMultiplyByTwo;
}
int remainder = sum % 10;
//If theres no remainder, the checkDigit is 0.
int checkDigit = 0;
//Otherwise, the checkDigit is the number that gets to the next 10
if (remainder != 0)
checkDigit = 10 - (sum % 10);
return checkDigit;
}
An example of its use:
public static bool IsValid(string userValue)
{
//Get the check digit from the end of the value
int checkDigit = (int)char.GetNumericValue(userValue[userValue.Length - 1]);
//Remove the checkDigit for the luhn calculation
userValue = userValue.Substring(0, userValue.Length - 1);
int[] userValueDigits = userValue.Select(ch => (int)char.GetNumericValue(ch))
.ToArray();
int originalLuhnDigit = CalculateLuhnCheckDigit(userValueDigits);
//If the user entered check digit matches the calcuated one,
//the number is valid.
return checkDigit == originalLuhnDigit;
}
The parity check must start from the right.
Try this:
<?php
function Luhn($digits) {
$sum = 0;
foreach (str_split(strrev($digits)) as $i => $digit) {
$sum += ($i % 2 == 0) ? array_sum(str_split($digit * 2)) : $digit;
}
return $digits . (10 - ($sum % 10)) % 10;
}
Add Luhn checksum to $input
$digits = Luhn($input);
Verify a number with Luhn checksum in it:
if ($digits == Luhn(substr($digits, 0, -1))) {
// ...
}
Get the checksum number:
$luhn_digit = substr(Luhn($digits), -1);
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int *LONT, n, TARF;
int SEGVT = 0;
int SEGVT2 = 0;
string TARJETA;
double VA;
cout << "cuantos digitos tiene la tarjeta: " << endl;
cin >> n;
LONT = new int[n];
do {
cout << "ingrese el # de la tarjeta: " << endl;
cin >> TARJETA;
VA = stod(TARJETA);
} while (VA < 0);
for (int POS = 0; POS < TARJETA.size(); POS++) {
LONT[POS] = TARJETA[POS] - '0';
}
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
LONT[i] = TARJETA[i] - '0';
LONT[i] = LONT[i] * 2;
if (LONT[i] >= 10) {
LONT[i] = LONT[i] - 9;
}
SEGVT2 = SEGVT2 + LONT[i];
}
else
{
LONT[i] = TARJETA[i] - '0';
SEGVT = SEGVT + LONT[i];
}
}
TARF = SEGVT + SEGVT2;
if (TARF % 10 == 0) {
cout << SEGVT2 << SEGVT;
cout << "El numero de tarjeta " << TARJETA << "; Es de una tarjeta valida (YA QUE SU MOD10 ES " << TARF << endl;
}
else
{
cout << SEGVT2 << SEGVT;
cout << "El numero de tarjeta" << TARJETA << "; No es de una tarjeta valida (YA QUE SU MOD10 ES " << TARF << endl;
}
delete[] LONT;
}
Related
The German Tax Id (Steueridentifikationsnummer) has the following properties:
It has 11 digits
First digit cannot be 0
In the first ten digits: one number occurs exactly twice or thrice, one or two digits appear zero times and the other digits appear exactly once
The last digit is a checksum Example Code for Checksum
The third bulletpoint is a little difficult for me to solve in an elegant way. I already have the code for the other three bulletpoints, but would love to get input for the last one, so that this could be a small little reference for other people.
# validate tax number
$taxNumber = $_POST['taxNumber'];
echo preg_replace("/[^0-9]/", "", $taxNumber);
if (strlen($taxNumber != 11)) {
# 11 digits
$taxNumberValid = false;
} else if ($taxNumber[0] == "0") {
# first digit != 0
$taxNumberValid = false;
} else {
# one digit two times, one digit zero times
# checksum
$numbers = str_split($taxNumber);
$sum = 0;
$product = 10;
for ($i = 0; $i <= 9; $i++) {
$sum = ($numbers[$i] + $product) % 10;
if ($sum == 0) {
$sum = 10;
}
$product = ($sum * 2) % 11;
}
$checksum = 11 - $product;
if ($checksum == 10) {
$checksum = 0;
}
if ($taxNumber[10] != $checksum) {
$taxNumberValid = false;
}
}
This code solves the problem:
// remove whitespaces, slashes & other unnecessary characters
$taxNumber = preg_replace("/[^0-9]/", "", $taxNumber);
// by default the taxnumber is correct
$taxNumberValid = true;
// taxnumber has to have exactly 11 digits
if (strlen($taxNumber) != 11) {
$taxNumberValid = false;
}
// first digit cannot be 0
if ($taxNumber[0] == "0") {
$taxNumberValid = false;
}
/*
make sure that within the first ten digits:
1.) one digit appears exactly twice or thrice
2.) one or two digits appear zero times
3.) and oll other digits appear exactly once once
*/
$digits = str_split($taxNumber);
$first10Digits = $digits;
array_pop($first10Digits);
$countDigits = array_count_values ($first10Digits);
if (count($countDigits) != 9 && count($countDigits) != 8) {
$taxNumberValid = false;
}
// last check: 11th digit has to be the correct checkums
// see http://de.wikipedia.org/wiki/Steueridentifikationsnummer#Aufbau_der_Identifikationsnummer
$sum = 0;
$product = 10;
for($i = 0; $i <= 9; $i++) {
$sum = ($digits[$i] + $product) % 10;
if ($sum == 0) {
$sum = 10;
}
$product = ($sum * 2) % 11;
}
$checksum = 11 - $product;
if ($checksum == 10) {
$checksum = 0;
}
if ($taxNumber[10] != $checksum) {
$taxNumberValid = false;
}
Update in 2017
Until 2016, the rule was, that within the first ten digits one number had to appear exactly twice.
Starting at 2017, the rule is, that within the first ten digits one number has to appear exactly twice or thrice.
And here is how you would write it in JS, based on #Pascal Klein's answer:
function countValues(arr) {
return arr.reduce((obj, item) => {
obj[item] = obj[item] ? ++obj[item] : 1;
return obj;
}, {});
}
function validateTIN(tin) {
const tinLength = 11;
// Taxnumber has to have exactly 11 digits.
if (tin.length !== tinLength) {
return false;
}
// First digit cannot be 0.
if (tin[0] === '0') {
return false;
}
/*
make sure that within the first ten digits:
1.) one digit appears exactly twice or thrice
2.) one or two digits appear zero times
3.) and all other digits appear exactly once
*/
const tinArray = tin.split('').slice(0, -1);
const valueCount = countValues(tinArray);
const valueCountLength = Object.keys(valueCount).length;
if (valueCountLength !== 8 && valueCountLength !== 9) {
return false;
}
// 11th digit has to match the checkum.
let sum = 0;
let product = 10;
for(let i = 0; i < tinLength - 1; i++) {
sum = (+tinArray[i] + product) % 10;
if (sum === 0) {
sum = 10;
}
product = (sum * 2) % 11;
}
let checksum = 11 - product;
if (checksum === 10) {
checksum = 0;
}
if (+tin[tinLength - 1] !== checksum) {
return false;
}
return true;
}
const tin1 = 'gbg';
const tin2 = '42344677908';
const tin3 = '12005078909';
const tin4 = '36574261809'; // valid
const tin5 = '10863924976'; // valid
console.log(tin1, validateTIN(tin1));
console.log(tin2, validateTIN(tin2));
console.log(tin3, validateTIN(tin3));
console.log(tin4, validateTIN(tin4));
console.log(tin5, validateTIN(tin5));
Here's a solution (in Javascript) that takes all the rules in consideration.
function validateTin(tin) {
// Allow space and slash (/) as number separators
tin = tin.replace(/ |\//g, "");
// 11 digits, the first is not allowed to be 0
if (!/^[1-9][0-9]{10}$/.test(tin)) {
return false;
}
const firstTen = tin.slice(0, 10);
// Count the number of occurrences of each digit
const occurrences = firstTen
.split("")
.reduce((acc, d) => acc.set(d, (acc.get(d) || 0) + 1), new Map());
const keys = [...occurrences.keys()];
const values = [...occurrences.values()];
// If one digit occurs twice, the length of keys will be 9
// If one digit occurs three times OR if two different digits occurs twice
// each, the length will be 8
if (keys.length !== 9 && keys.length !== 8) {
return false;
}
if (keys.length === 8) {
// Check how many times the digit that occurred the most times occurred
const maxOccurrences = values.reduce((max, num) => Math.max(max, num));
// If maxOccurrences is 2, we know two different numbers occurred twice
// each. This is not a valid tin.
// A final restriction is that a number can not occur three times in a row
if (maxOccurrences === 2 || /(\d)\1\1/.test(firstTen)) {
return false;
}
}
// Calculate the checksum digit
let m11 = 10;
let m10 = 0;
for (let i = 0; i < 10; i++) {
m10 = (parseInt(tin[i], 10) + m11) % 10;
if (m10 === 0) {
m10 = 10;
}
m11 = (2 * m10) % 11;
}
let digit = 11 - m11;
if (digit === 10) {
digit = 0;
}
return digit === parseInt(tin[10], 10);
}
How can I calculate the n-th root of an integer using PHP/GMP?
Although I found a function called gmp_root(a, nth) in the PHP source, it seems that this function has not been published in any release yet*: http://3v4l.org/8FjU7
*) 5.6.0alpha2 being the most recent one at the time of writing
Original source: Calculating Nth root with bcmath in PHP – thanks and credits to HamZa!
I've rewritten the code to use GMP instead of BCMath:
function gmp_nth_root($num, $n) {
if ($n < 1) return 0; // we want positive exponents
if ($num <= 0) return 0; // we want positive numbers
if ($num < 2) return 1; // n-th root of 1 or 2 give 1
// g is our guess number
$g = 2;
// while (g^n < num) g=g*2
while (gmp_cmp(gmp_pow($g, $n), $num) < 0) {
$g = gmp_mul($g, 2);
}
// if (g^n==num) num is a power of 2, we're lucky, end of job
if (gmp_cmp(gmp_pow($g, $n), $num) == 0) {
return $g;
}
// if we're here num wasn't a power of 2 :(
$og = $g; // og means original guess and here is our upper bound
$g = gmp_div($g, 2); // g is set to be our lower bound
$step = gmp_div(gmp_sub($og, $g), 2); // step is the half of upper bound - lower bound
$g = gmp_add($g, $step); // we start at lower bound + step , basically in the middle of our interval
// while step != 1
while (gmp_cmp($step, 1) > 0) {
$guess = gmp_pow($g, $n);
$step = gmp_div($step, 2);
$comp = gmp_cmp($guess, $num); // compare our guess with real number
if ($comp < 0) { // if guess is lower we add the new step
$g = gmp_add($g, $step);
} else if ($comp == 1) { // if guess is higher we sub the new step
$g = gmp_sub($g, $step);
} else { // if guess is exactly the num we're done, we return the value
return $g;
}
}
// whatever happened, g is the closest guess we can make so return it
return $g;
}
In C, Ruby or PHP, how can I get the offsets of all set bits in an bitarray. E.g.:
Bitarray: 1 0 0 1 0
Offset: 5 4 3 2 1
Yields 2 and 5.
10001 => {1,5}
11 => {1,2}
1001001 => {1,4,7}
The most obvious solution would be to first do a reversed Find first set to know the length and then loop through the bits, saving the offset/index. However this does not seem very smart. Something like FFSR multiple times with subtraction might be better.
I came up with this. I've used binary shift operation to find out if there is binary "1" or "0". Probably you could use this code as your starting point.
#include <stdio.h>
int main()
{
int number;
int counter = 1;
printf("Please input the number to get the offsets: ");
scanf("%d", &number);
printf("The required positions of ones: ");
while ((number != 0))
{
if ((number % 2) != 0)
{
number = number >> 1;
printf("%d", counter);
}
else
{
number = number >> 1;
}
counter++;
}
return 0;
}
Here is an extended version that prints binary representation as well:
#include <stdio.h>
#include <strings.h>
char* rev(char* str);
int main()
{
int number, temp;
int counter = 1;
char str[32] = "";
printf("Please input the number to get the offsets: ");
scanf("%d", &number);
temp = number;
printf("Binary representation: ");
while ((temp != 0))
{
if ((temp % 2) != 0)
{
temp = temp >> 1;
strncat(str, "1", 1);
}
else
{
temp = temp >> 1;
strncat(str, "0", 1);
}
}
printf("%s", rev(str));
printf("\nThe required positions of ones: ");
while ((number != 0))
{
if ((number % 2) != 0)
{
number = number >> 1;
printf("%d", counter);
}
else
{
number = number >> 1;
}
counter++;
}
getch();
getch();
return 0;
}
char* rev(char* str)
{
int end= strlen(str) - 1;
int start = 0;
while( start<end )
{
str[start] ^= str[end];
str[end] ^= str[start];
str[start]^= str[end];
++start;
--end;
}
return str;
}
I have a Visual Basic function and I am not that familiar with VB. I need to convert it to PHP and have made a start. There are a couple of functions I'm not sure how to replicate and am looking for some help with this and to see if I have got the nesting right etc. In the following code, there is the vb function and then my attempt at te php version. it is not complete and in the php version I have commented out the vb parts I am not sure about. Can anyone help put me on the right lines?
Public Function gfnCrypt(ByVal Expression As String, ByVal Password As String) As String
'RC4 Encryption
Dim rb(0 To 255) As Integer, X As Long, Y As Long, Z As Long, Key() As Byte, ByteArray() As Byte, temp As Byte
On Error Resume Next
If Len(Password) = 0 Then
Exit Function
End If
If Len(Expression) = 0 Then
Exit Function
End If
If Len(Password) > 256 Then
Key() = StrConv(Left$(Password, 256), vbFromUnicode)
Else
Key() = StrConv(Password, vbFromUnicode)
End If
For X = 0 To 255
rb(X) = X
Next X
X = 0
Y = 0
Z = 0
For X = 0 To 255
Y = (Y + rb(X) + Key(X Mod Len(Password))) Mod 256
temp = rb(X)
rb(X) = rb(Y)
rb(Y) = temp
Next X
X = 0
Y = 0
Z = 0
ByteArray() = StrConv(Expression, vbFromUnicode)
For X = 0 To Len(Expression)
Y = (Y + 1) Mod 256
Z = (Z + rb(Y)) Mod 256
temp = rb(Y)
rb(Y) = rb(Z)
rb(Z) = temp
ByteArray(X) = ByteArray(X) Xor (rb((rb(Y) + rb(Z)) Mod 256))
Next X
gfnCrypt = StrConv(ByteArray, vbUnicode)
End Function
And in PHP:
function gfnCrypt($mywebpassword, $mywebkey) {
//'RC4 Encryption
//Dim rb(0 To 255) As Integer, X As Long, Y As Long, Z As Long, Key() As Byte, ByteArray() As Byte, temp As Byte
if(strlen($mywebpassword) == 0){
return false;
}
if(strlen($mywebkey) == 0){
return false;
}
if(strlen($mywebpassword) > 256){
//Key() = StrConv(Left$(Password, 256), vbFromUnicode)
}else{
//Key() = StrConv(Password, vbFromUnicode)
}
$rb=array();
for($x=0;$x=255;$x++){
$rb['x'] = $x;
for($x=0;$x=255;$x++){
$y = ($y + $rb['x'];// + Key(X Mod Len(Password))) Mod 256
$temp = $rb['x'];
$rb['x'] = $rb[$y];
$rb[$y] = $temp;
//ByteArray() = StrConv(Expression, vbFromUnicode)
for($x=0;$x=strlen($mywebpassword), $x++){
$y = ($y + 1);// Mod 256
$z = ($z + $rb[$y]);// Mod 256
$temp = $rb[$y];
$rb[$y] = $rb[$z];
$rb[$z] = $temp;
//ByteArray(X) = ByteArray(X) Xor (rb((rb(Y) + rb(Z)) Mod 256))
}
}
}
//gfnCrypt = StrConv(ByteArray, vbUnicode)
return $gfnCrypt;
}
The arithmetic modulo can be used in php using % operator.
$modulus = $a % $b
I think you will get errors with your 3 embedded for (x…) loops by the way.
To access an element of the array (the $ith for instance) don't use $array['i'] but $array[$i].
The StrConv must be a ut8_encode and the left stuff can be done with substr($string, 0, 255).
References: utf8_encode substr
If you are trying to do RC4 encryption in PHP then you may wan't to take a look at the project at this link http://code.google.com/p/rc4crypt/
I really hope you have some unit tests to test that:
function gfnCrypt($mywebpassword, $mywebkey) {
//'RC4 Encryption
//Dim rb(0 To 255) As Integer, X As Long, Y As Long, Z As Long, Key() As Byte, ByteArray() As Byte, temp As Byte
rb = array();
Key = array();
ByteArray = array();
if(strlen($mywebpassword) == 0){
return false;
}
if(strlen($mywebkey) == 0){
return false;
}
if(strlen($mywebpassword) > 256){
//Key() = StrConv(Left$(Password, 256), vbFromUnicode)
Key[] = ut8_encodesubstr(Password, 0, 256));
}else{
//Key() = StrConv(Password, vbFromUnicode)
Key[] = ut8_encode(Password);
}
$rb=array();
for($x=0;$x=255;$x++){
$rb['x'] = $x;
for($x=0;$x=255;$x++){
$y = ($y + $rb['x'] + Key(X % strlen(Password))) % 256;
$temp = $rb['x'];
$rb['x'] = $rb[$y];
$rb[$y] = $temp;
//ByteArray() = StrConv(Expression, vbFromUnicode)
ByteArray[] = ut8_encode(Expression);
for($x=0;$x=strlen($mywebpassword), $x++){
$y = ($y + 1);// Mod 256
$z = ($z + $rb[$y]);// Mod 256
$temp = $rb[$y];
$rb[$y] = $rb[$z];
$rb[$z] = $temp;
//ByteArray(X) = ByteArray(X) Xor (rb((rb(Y) + rb(Z)) Mod 256))
ByteArray[X] = (ByteArray[X] ^= (rb[(rb[Y] + rb[Z]] % 256)]);
}
}
}
//gfnCrypt = StrConv(ByteArray, vbUnicode)
gfnCrypt = ut8_encode(ByteArray);
return $gfnCrypt;
}
I finished the code you started, but it seems really wrong (for example, why nest 3 for loops, using the same variable ?). It doesn't even seem to match the initial VB code...
Does anybody know a PHP function for IMEI validation?
Short solution
You can use this (witchcraft!) solution, and simply check the string length:
function is_luhn($n) {
$str = '';
foreach (str_split(strrev((string) $n)) as $i => $d) {
$str .= $i %2 !== 0 ? $d * 2 : $d;
}
return array_sum(str_split($str)) % 10 === 0;
}
function is_imei($n){
return is_luhn($n) && strlen($n) == 15;
}
Detailed solution
Here's my original function that explains each step:
function is_imei($imei){
// Should be 15 digits
if(strlen($imei) != 15 || !ctype_digit($imei))
return false;
// Get digits
$digits = str_split($imei);
// Remove last digit, and store it
$imei_last = array_pop($digits);
// Create log
$log = array();
// Loop through digits
foreach($digits as $key => $n){
// If key is odd, then count is even
if($key & 1){
// Get double digits
$double = str_split($n * 2);
// Sum double digits
$n = array_sum($double);
}
// Append log
$log[] = $n;
}
// Sum log & multiply by 9
$sum = array_sum($log) * 9;
// Compare the last digit with $imei_last
return substr($sum, -1) == $imei_last;
}
Maybe can help you :
This IMEI number is something like this: ABCDEF-GH-IJKLMNO-X (without “-” characters)
For example: 350077523237513
In our example ABCDEF-GH-IJKLMNO-X:
AB is Reporting Body Identifier such as 35 = “British Approvals Board of Telecommunications (BABT)”
ABCDEF is Type Approval Code
GH is Final Assembly Code
IJKLMNO is Serial Number
X is Check Digit
Also this can help you : http://en.wikipedia.org/wiki/IMEI#Check_digit_computation
If i don't misunderstood, IMEI numbers using Luhn algorithm . So you can google this :) Or you can search IMEI algorithm
Maybe your good with the imei validator in the comments here:
http://www.php.net/manual/en/function.ctype-digit.php#77718
But I haven't tested it
Check this solution
<?php
function validate_imei($imei)
{
if (!preg_match('/^[0-9]{15}$/', $imei)) return false;
$sum = 0;
for ($i = 0; $i < 14; $i++)
{
$num = $imei[$i];
if (($i % 2) != 0)
{
$num = $imei[$i] * 2;
if ($num > 9)
{
$num = (string) $num;
$num = $num[0] + $num[1];
}
}
$sum += $num;
}
if ((($sum + $imei[14]) % 10) != 0) return false;
return true;
}
$imei = '868932036356090';
var_dump(validate_imei($imei));
?>
IMEI validation uses Luhn check algorithm. I found a link to a page where you can validate your IMEI. Furthermore, at the bottom of this page is a piece of code written in JavaScript to show how to calculate the 15th digit of IMEI and to valid IMEI. I might give you some ideas. You can check it out here http://imei.sms.eu.sk/index.html
Here is a jQuery solution which may be of use: https://github.com/madeinstefano/imei-validator
good fun from kasperhartwich
function validateImei($imei, $use_checksum = true) {
if (is_string($imei)) {
if (ereg('^[0-9]{15}$', $imei)) {
if (!$use_checksum) return true;
for ($i = 0, $sum = 0; $i < 14; $i++) {
$tmp = $imei[$i] * (($i%2) + 1 );
$sum += ($tmp%10) + intval($tmp/10);
}
return (((10 - ($sum%10)) %10) == $imei[14]);
}
}
return false;
}