    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 *      https://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 * <strong>IBAN</strong> (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 <em>check digit</em> calculation/validation the first four characters are moved
    028 * to the end of the code.
    029 *  So {@code CCDDnnnnnnn} becomes {@code nnnnnnnCCDD} (where
    030 *  {@code CC} is the country code and {@code DD} is the check digit). For
    031 *  check digit calculation the check digit value should be set to zero (such as
    032 *  {@code CC00nnnnnnn} 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="https://en.wikipedia.org/wiki/International_Bank_Account_Number">Wikipedia -
    038 *  IBAN number</a>.
    039 *
    040 * @since 1.4
    041 */
    042public final class IBANCheckDigit extends AbstractCheckDigit implements Serializable {
    043
    044    private static final int MIN_CODE_LEN = 5;
    045
    046    private static final long serialVersionUID = -3600191725934382801L;
    047
    048    /**
    049     * Singleton IBAN Number Check Digit instance.
    050     */
    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 <em>Check Digit</em> for an IBAN code.
    065     * <p>
    066     * <strong>Note:</strong> The check digit is the third and fourth characters and is set to the value "{@code 00}".
    067     * </p>
    068     *
    069     * @param code The code to calculate the Check Digit for,
    070     * @return The calculated Check Digit as 2 numeric decimal characters, for example, "42",
    071     * @throws CheckDigitException if an error occurs calculating the check digit for the specified code,
    072     */
    073    @Override
    074    public String calculate(String code) throws CheckDigitException {
    075        if (code == null || code.length() < MIN_CODE_LEN) {
    076            throw new CheckDigitException("Invalid Code length=%,d", code == null ? 0 : code.length());
    077        }
    078        code = code.substring(0, 2) + "00" + code.substring(4); // CHECKSTYLE IGNORE MagicNumber
    079        final int modulusResult = calculateModulus(code);
    080        final int charValue = 98 - modulusResult; // CHECKSTYLE IGNORE MagicNumber
    081        final String checkDigit = Integer.toString(charValue);
    082        return charValue > 9 ? checkDigit : "0" + checkDigit; // CHECKSTYLE IGNORE MagicNumber
    083    }
    084
    085    /**
    086     * Calculate the modulus for a code.
    087     *
    088     * @param code The code to calculate the modulus for.
    089     * @return The modulus value,
    090     * @throws CheckDigitException if an error occurs calculating the modulus for the specified code,
    091     */
    092    private int calculateModulus(final String code) throws CheckDigitException {
    093        final String reformattedCode = code.substring(4) + code.substring(0, 4); // CHECKSTYLE IGNORE MagicNumber
    094        long total = 0;
    095        for (int i = 0; i < reformattedCode.length(); i++) {
    096            final char ch = reformattedCode.charAt(i);
    097            final int charValue = Character.getNumericValue(ch);
    098            if (!isAsciiAlphaNum(reformattedCode.charAt(i))) {
    099                throw new CheckDigitException("Invalid Character[%d] = '%d'", i, charValue);
    100            }
    101            total = (charValue > 9 ? total * 100 : total * 10) + charValue; // CHECKSTYLE IGNORE MagicNumber
    102            if (total > MAX) {
    103                total %= MODULUS;
    104            }
    105        }
    106        return (int) (total % MODULUS);
    107    }
    108
    109    /**
    110     * Validate the check digit of an IBAN code.
    111     *
    112     * @param code The code to validate.
    113     * @return {@code true} if the check digit is valid, otherwise {@code false}.
    114     */
    115    @Override
    116    public boolean isValid(final String code) {
    117        if (code == null || code.length() < MIN_CODE_LEN) {
    118            return false;
    119        }
    120        final String check = code.substring(2, 4); // CHECKSTYLE IGNORE MagicNumber
    121        if ("00".equals(check) || "01".equals(check) || "99".equals(check)) {
    122            return false;
    123        }
    124        try {
    125            return calculateModulus(code) == 1;
    126        } catch (final CheckDigitException ex) {
    127            return false;
    128        }
    129    }
    130}