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 * @since 1.4
041 */
042public final class IBANCheckDigit implements CheckDigit, Serializable {
043
044    private static final int MIN_CODE_LEN = 5;
045
046    private static final long serialVersionUID = -3600191725934382801L;
047
048    private static final int MAX_ALPHANUMERIC_VALUE = 35; // Character.getNumericValue('Z')
049
050    /** Singleton IBAN Number Check Digit instance */
051    public static final CheckDigit IBAN_CHECK_DIGIT = new IBANCheckDigit();
052
053    private static final long MAX = 999999999;
054
055    private static final long MODULUS = 97;
056
057    /**
058     * Constructs Check Digit routine for IBAN Numbers.
059     */
060    public IBANCheckDigit() {
061    }
062
063    /**
064     * Calculate the <i>Check Digit</i> for an IBAN code.
065     * <p>
066     * <b>Note:</b> The check digit is the third and fourth
067     * characters and is set to the value "<code>00</code>".
068     *
069     * @param code The code to calculate the Check Digit for
070     * @return The calculated Check Digit as 2 numeric decimal characters, e.g. "42"
071     * @throws CheckDigitException if an error occurs calculating
072     * the check digit for the specified code
073     */
074    @Override
075    public String calculate(String code) throws CheckDigitException {
076        if (code == null || code.length() < MIN_CODE_LEN) {
077            throw new CheckDigitException("Invalid Code length=" + (code == null ? 0 : code.length()));
078        }
079        code = code.substring(0, 2) + "00" + code.substring(4); // CHECKSTYLE IGNORE MagicNumber
080        final int modulusResult = calculateModulus(code);
081        final int charValue = 98 - modulusResult; // CHECKSTYLE IGNORE MagicNumber
082        final String checkDigit = Integer.toString(charValue);
083        return charValue > 9 ? checkDigit : "0" + checkDigit; // CHECKSTYLE IGNORE MagicNumber
084    }
085
086    /**
087     * Calculate the modulus for a code.
088     *
089     * @param code The code to calculate the modulus for.
090     * @return The modulus value
091     * @throws CheckDigitException if an error occurs calculating the modulus
092     * for the specified code
093     */
094    private int calculateModulus(final String code) throws CheckDigitException {
095        final String reformattedCode = code.substring(4) + code.substring(0, 4); // CHECKSTYLE IGNORE MagicNumber
096        long total = 0;
097        for (int i = 0; i < reformattedCode.length(); i++) {
098            final int charValue = Character.getNumericValue(reformattedCode.charAt(i));
099            if (charValue < 0 || charValue > MAX_ALPHANUMERIC_VALUE) {
100                throw new CheckDigitException("Invalid Character[" + i + "] = '" + charValue + "'");
101            }
102            total = (charValue > 9 ? total * 100 : total * 10) + charValue; // CHECKSTYLE IGNORE MagicNumber
103            if (total > MAX) {
104                total = total % MODULUS;
105            }
106        }
107        return (int) (total % MODULUS);
108    }
109
110    /**
111     * Validate the check digit of an IBAN code.
112     *
113     * @param code The code to validate
114     * @return {@code true} if the check digit is valid, otherwise
115     * {@code false}
116     */
117    @Override
118    public boolean isValid(final String code) {
119        if (code == null || code.length() < MIN_CODE_LEN) {
120            return false;
121        }
122        final String check = code.substring(2, 4); // CHECKSTYLE IGNORE MagicNumber
123        if ("00".equals(check) || "01".equals(check) || "99".equals(check)) {
124            return false;
125        }
126        try {
127            return calculateModulus(code) == 1;
128        } catch (final CheckDigitException ex) {
129            return false;
130        }
131    }
132
133}