Share this page 

Validate a Social Security Number (canadian)Tag(s): Varia


import java.util.*;
import java.io.*;

public class SSNUtils {
  /** 
   * Validate a SSN number  nnn nnn nnn
   */
   public static boolean validSSN(String ssn) {   
    if (isNumber(ssn)) {
      try {
        int checksum = 0;
        int j = ssn.length();
        int  [] digit = new int[j];
        for (int i=0; i < ssn.length(); i++) 
           digit[i] = Integer.valueOf("" + ssn.charAt(i)).intValue();
        // Add odd digits except the last one
        int total_odd = 0; 
        for (int i=0; i < digit.length-1; i+=2) 
          checksum += digit[i];
        // Multiply by 2 even digits, 
        //   if result > 9 then div and mod  by 10, 
        //       add the results to the checksum
        //   else 
        //       add result to the checksum
        int k = 0; 
        for (int i=0; i < digit.length; i+= 2) {
          if (i < digit.length-1) {
             k = digit[i+1] * 2;
             if (k>9) k = (k-10) + 1;
             // total_even += k;
             checksum += k;
             }
           }

        // perform a modulo 10  on the total_odd_even 
        //   then add the last digit
        int mod = checksum % 10;
        checksum = digit[digit.length-1] + mod;

        // if the checksum is divisible by 10 then it's valid
        return ((checksum % 10) == 0);
        }
       catch (Exception e) {
          e.printStackTrace();
          return false;
          }
       }
    else {
      return false;
      }
  }
  
  /**
   * Check if number is valid
   */
  public static boolean isNumber(String n) {
    try {
      double d = Double.valueOf(n).doubleValue();
      return true;
      }
    catch (NumberFormatException e) {
      e.printStackTrace();
      return false;
      }
  }

  /*
  ** For testing purpose
  **
  **   java SSNUtils  or java SSNUtils
  **
  */
  public static void main(String args[]) throws Exception {
    String aSSN = "";
    
    if (args.length > 0) 
      aSSN = args[0];
    else {
      BufferedReader input = 
        new BufferedReader(new InputStreamReader(System.in));
      System.out.print("SSN number : ");
      aSSN = input.readLine();
      }
    System.out.println
       ("The SSN " + aSSN + " is " +(validSSN(aSSN)?" good.":" bad."));
    }
}