Java Q&A
by David Wincelberg

Listing One
public class CCNumber {
    public static String removeSpaces (String ccNum) {
        if (ccNum == null) return "";
        int length = ccNum.length();
        StringBuffer sbuf = new StringBuffer();
        char c;
        for (int i = 0;  i < length;  i++) {
            c = ccNum.charAt (i);
            if (c != ' ')
                sbuf.append (c);
        }
        return sbuf.toString();
    }

    // Also useful for phone and Social Security numbers
    public static String keepDigits (String ccNum) {
        if (ccNum == null) return "";
        int length = ccNum.length();
        StringBuffer sbuf = new StringBuffer();
        char c;
        for (int i = 0;  i < length;  i++) {
            c = ccNum.charAt (i);
            if (Character.isDigit (c))
                sbuf.append (c);
        }
        return sbuf.toString();
    }

    public static String keepPhoneDigits (String ccNum) {
        String text = keepDigits (ccNum);
        if (text.length() < 10)
            return "** Missing area code: " + text;
        if (!text.startsWith ("1"))
            text = "1" + text;
        if (text.length() != 11)
            return "** Error in phone number: " + text;
        return text;
    }
}


Listing Two
import javax.crypto.*;
import javax.crypto.spec.*;

public class CCNumber {
    // Same as in Listing One
    public static byte[] encrypt (String ccNum, String password) {
        if (ccNum == null || password == null) return null;
        // Uses triple DES; password is up to 24 bytes long
        SecretKey key = new SecretKeySpec (password.getBytes(), "DESede");
        Cipher cipher = Cipher.getInstance ("DESede");
        cipher.init (Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal (ccNum.getBytes());
    }

    public static String decrypt (byte[] codedNum, String password) {
        if (codedNum == null || password == null) return null;
        // Uses triple DES; password is up to 24 bytes long
        SecretKey key = new SecretKeySpec (password.getBytes(), "DESede");
        Cipher cipher = Cipher.getInstance ("DESede");
        cipher.init (Cipher.DECRYPT_MODE, key);
        return cipher.doFinal (codedNum.getBytes());
    }
}



