001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.validator.routines.checkdigit;
018
019import java.io.Serializable;
020
021/**
022 * <b>IBAN</b> (International Bank Account Number) Check Digit calculation/validation.
023 * <p>
024 * This routine is based on the ISO 7064 Mod 97,10 check digit calculation routine.
025 * <p>
026 * The two check digit characters in a IBAN number are the third and fourth characters
027 * in the code. For <i>check digit</i> calculation/validation the first four characters are moved
028 * to the end of the code.
029 *  So <code>CCDDnnnnnnn</code> becomes <code>nnnnnnnCCDD</code> (where
030 *  <code>CC</code> is the country code and <code>DD</code> is the check digit). For
031 *  check digit calculation the check digit value should be set to zero (i.e.
032 *  <code>CC00nnnnnnn</code> in this example.
033 * <p>
034 * Note: the class does not check the format of the IBAN number, only the check digits.
035 * <p>
036 * For further information see
037 *  <a href="http://en.wikipedia.org/wiki/International_Bank_Account_Number">Wikipedia -
038 *  IBAN number</a>.
039 *
040 * @version $Revision$
041 * @since Validator 1.4
042 */
043public final class IBANCheckDigit implements CheckDigit, Serializable {
044
045    private static final int MIN_CODE_LEN = 5;
046
047    private static final long serialVersionUID = -3600191725934382801L;
048
049    private static final int MAX_ALPHANUMERIC_VALUE = 35; // Character.getNumericValue('Z')
050
051    /** Singleton IBAN Number Check Digit instance */
052    public static final CheckDigit IBAN_CHECK_DIGIT = new IBANCheckDigit();
053
054    private static final long MAX = 999999999;
055
056    private static final long MODULUS = 97;
057
058    /**
059     * Construct Check Digit routine for IBAN Numbers.
060     */
061    public IBANCheckDigit() {
062    }
063
064    /**
065     * Validate the check digit of an IBAN code.
066     *
067     * @param code The code to validate
068     * @return <code>true</code> if the check digit is valid, otherwise
069     * <code>false</code>
070     */
071    @Override
072    public boolean isValid(String code) {
073        if (code == null || code.length() < MIN_CODE_LEN) {
074            return false;
075        }
076        String check = code.substring(2,4); // CHECKSTYLE IGNORE MagicNumber
077        if ("00".equals(check) || "01".equals(check) || "99".equals(check)) {
078            return false;
079        }
080        try {
081            int modulusResult = calculateModulus(code);
082            return (modulusResult == 1);
083        } catch (CheckDigitException  ex) {
084            return false;
085        }
086    }
087
088    /**
089     * Calculate the <i>Check Digit</i> for an IBAN code.
090     * <p>
091     * <b>Note:</b> The check digit is the third and fourth
092     * characters and is set to the value "<code>00</code>".
093     *
094     * @param code The code to calculate the Check Digit for
095     * @return The calculated Check Digit as 2 numeric decimal characters, e.g. "42"
096     * @throws CheckDigitException if an error occurs calculating
097     * the check digit for the specified code
098     */
099    @Override
100    public String calculate(String code) throws CheckDigitException {
101        if (code == null || code.length() < MIN_CODE_LEN) {
102            throw new CheckDigitException("Invalid Code length=" +
103                    (code == null ? 0 : code.length()));
104        }
105        code = code.substring(0, 2) + "00" + code.substring(4); // CHECKSTYLE IGNORE MagicNumber
106        int modulusResult = calculateModulus(code);
107        int charValue = (98 - modulusResult); // CHECKSTYLE IGNORE MagicNumber
108        String checkDigit = Integer.toString(charValue);
109        return (charValue > 9 ? checkDigit : "0" + checkDigit); // CHECKSTYLE IGNORE MagicNumber
110    }
111
112    /**
113     * Calculate the modulus for a code.
114     *
115     * @param code The code to calculate the modulus for.
116     * @return The modulus value
117     * @throws CheckDigitException if an error occurs calculating the modulus
118     * for the specified code
119     */
120    private int calculateModulus(String code) throws CheckDigitException {
121        String reformattedCode = code.substring(4) + code.substring(0, 4); // CHECKSTYLE IGNORE MagicNumber
122        long total = 0;
123        for (int i = 0; i < reformattedCode.length(); i++) {
124            int charValue = Character.getNumericValue(reformattedCode.charAt(i));
125            if (charValue < 0 || charValue > MAX_ALPHANUMERIC_VALUE) {
126                throw new CheckDigitException("Invalid Character[" +
127                        i + "] = '" + charValue + "'");
128            }
129            total = (charValue > 9 ? total * 100 : total * 10) + charValue; // CHECKSTYLE IGNORE MagicNumber
130            if (total > MAX) {
131                total = total % MODULUS;
132            }
133        }
134        return (int)(total % MODULUS);
135    }
136
137}