Google+
Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, October 3, 2011

How to Create MD5 Hashed Code in Android

Dear Blog Viewer,


What is the MD5 hash?
The MD5 hash also known as checksum for a file is a 128-bit value, something like a fingerprint of the file. There is a very small possibility of getting two identical hashes of two different files. This feature can be useful both for comparing the files and their integrity control.
Let us imagine a situation that will help to understand how the MD5 hash works.
Alice and Bob have two similar huge files. How do we know that they are different without sending them to each other? We simply have to calculate the MD5 hashes of these files and compare them.
MD5 Hash Properties
The MD5 hash consists of a small amount of binary data, typically no more than 128 bits. All hash values share the following properties:
Hash length
The length of the hash value is determined by the type of the used algorithm, and its length does not depend on the size of the file. The most common hash value lengths are either 128 or 160 bits.
Non-discoverability
Every pair of nonidentical files will translate into a completely different hash value, even if the two files differ only by a single bit. Using today's technology, it is not possible to discover a pair of files that translate to the same hash value.
Repeatability
Each time a particular file is hashed using the same algorithm, the exact same hash value will be produced.
Irreversibility
All hashing algorithms are one-way. Given a checksum value, it is infeasible to discover the password. In fact, none of the properties of the original message can be determined given the checksum value alone.
The algorithm was invented by:
Professor Ronald L. Rivest (born 1947, Schenectady, New York) is a cryptographer, and is the Viterbi Professor of Computer Science at MIT's Department of Electrical Engineering and Computer Science. He is most celebrated for his work on public-key encryption with Len Adleman and Adi Shamir, specifically the RSA algorithm, for which they won the 2002 ACM Turing Award.
Simple Code for Android:

public static final String md5Digest(final String text)
{
     try
     {
           // Create MD5 Hash
           MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
           digest.update(text.getBytes());
           byte messageDigest[] = digest.digest();

           // Create Hex String
           StringBuffer hexString = new StringBuffer();
           int messageDigestLenght = messageDigest.length;
           for (int i = 0; i < messageDigestLenght; i++)
           {
                String hashedData = Integer.toHexString(0xFF & messageDigest[i]);
                while (hashedData.length() < 2)
                     hashedData = "0" + hashedData;
                hexString.append(hashedData);
           }
           return hexString.toString();

     } catch (NoSuchAlgorithmException e)
     {
           e.printStackTrace();
     }
     return ""; // if text is null then return nothing
}


Wednesday, September 14, 2011

How to Convert InputStream to String In Java

Here is the Simple method to convert InputStream Object to String Object.


Just Call this method and pass InputStream Object. it return the String






public static String convertStreamToString(InputStream is) throws Exception
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;

    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    is.close();

    return sb.toString();
}

Tuesday, July 19, 2011

Credit Card Number Validation

Informal explanation

The formula verifies a number against its included check digit, which is usually appended to a partial account number to generate the full account number. This account number must pass the following test:
  1. Counting from the check digit, which is the rightmost, and moving left, double the value of every second digit.
  2. Sum the digits of the products (eg, 10 = 1 + 0 = 1, 14 = 1 + 4 = 5) together with the undoubled digits from the original number.
  3. If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.
Assume an example of an account number "4992739871" that will have a check digit added, making it of the form 4992739871x:
Account number 4 9 9 2 7 3 9 8 7 1 x
Double every other 4 18 9 4 7 6 9 16 7 2 x
Sum together all numbers 64 + x

To make the sum divisible by 10, we set the check digit (x) to 6, making the full account number 49927398716.
The account number 49927398716 can be validated as follows:
  1. Double every second digit, from the rightmost: (1×2) = 2, (8×2) = 16, (3×2) = 6, (2×2) = 4, (9×2) = 18
  2. Sum all the individual digits (digits in parentheses are the products from Step 1): 6 + (2) + 7 + (1+6) + 9 + (6) + 7 + (4) + 9 + (1+8) + 4 = 70
  3. Take the sum modulo 10: 70 mod 10 = 0; the account number is probably valid.


 Sample Code to Check Card No.


public boolean luhnCardValidationMethod(String cardNumber) {
        char[] charArray = cardNumber.toCharArray();
        int[] number = new int[charArray.length];
        int total = 0;
        for (int i = 0; i < charArray.length; i++)
        {
            number[i] = Character.getNumericValue(charArray[i]);
        }

        for (int i = number.length - 2; i > -1; i -= 2)
        {
            number[i] *= 2;

            if (number[i] > 9)
                number[i] -= 9;
        }

        for (int i = 0; i < number.length; i++)
        {
            total += number[i];
        }

        if (total % 10 != 0)
        {
            //TODO if total%10 is not Equals to Zero the Card is Invalid
            return false;
        }

        //TODO Else Card is Valid
        return true;
    }

Source : http://en.wikipedia.org/wiki/Luhn_algorithm



Some More Tips to Check Card Number.

1. Prefix, Length, and Check Digit Criteria

Here is a table outlining the major credit cards that you might want to validate.

CARD TYPE Prefix Length Check digit algorithm
MASTERCARD51-5516 mod 10
VISA413, 16 mod 10
AMEX34
37
15 mod 10
Diners Club/
Carte Blanche
300-305
36
38
14mod 10
Discover601116 mod 10
enRoute2014
2149
15any
JCB316 mod 10
JCB2131
1800
15 mod 10

2. LUHN Formula (Mod 10) for Validation of Primary Account Number

The following steps are required to validate the primary account number:
 
Step 1:
Double the value of alternate digits of the primary account number beginning with the second digit from the right (the first right--hand digit is the check digit.) 

Step 2:
Add the individual digits comprising the products obtained in Step 1 to each of the unaffected digits in the original number. 

Step 3:
The total obtained in Step 2 must be a number ending in zero (30, 40, 50, etc.) for the account number to be validated.
For example
To validate the primary account number 49927398716:
Step 1:
        4     9     9     2     7     3     9     8     7     1     6
              x2           x2         x2          x2          x2 
-----------------------------------------------------------
             18            4            6           16            2




Step 2: 
4 +(1+8)+ 9 + (4) + 7 + (6) + 9 +(1+6) + 7 + (2) + 6
Step 3:
Sum = 70 : Card number is validated
Note: Card is valid because the 70/10 yields no remainder.


Source : http://www.beachnet.com/~hstiles/cardtype.html


Comments Always Welcome..... :)

    Thursday, June 9, 2011

    How To Remove Extra Spaces From String


    public static String LRTrim(String str) {

            str = str.replaceAll("  ", " ");         // replace all double spaces with single Space
            return str.trim();   // remove all LEFT side & Right Side Extra white spaces from the string
        }
    Google+