    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
    021import org.apache.commons.validator.GenericValidator;
    022
    023/**
    024 * <strong>Verhoeff</strong> (Dihedral) Check Digit calculation/validation.
    025 * <p>
    026 * Check digit calculation for numeric codes using a
    027 * <a href="https://en.wikipedia.org/wiki/Dihedral_group">Dihedral Group</a>
    028 * of order 10.
    029 * <p>
    030 * See <a href="https://en.wikipedia.org/wiki/Verhoeff_algorithm">Wikipedia
    031 *  - Verhoeff algorithm</a> for more details.
    032 *
    033 * @since 1.4
    034 */
    035public final class VerhoeffCheckDigit extends AbstractCheckDigit implements Serializable {
    036
    037    private static final long serialVersionUID = 4138993995483695178L;
    038
    039    /** Singleton Verhoeff Check Digit instance */
    040    public static final CheckDigit VERHOEFF_CHECK_DIGIT = new VerhoeffCheckDigit();
    041
    042    /** D - multiplication table */
    043    private static final int[][] D_TABLE = {
    044        {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
    045        {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},
    046        {2, 3, 4, 0, 1, 7, 8, 9, 5, 6},
    047        {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},
    048        {4, 0, 1, 2, 3, 9, 5, 6, 7, 8},
    049        {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},
    050        {6, 5, 9, 8, 7, 1, 0, 4, 3, 2},
    051        {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},
    052        {8, 7, 6, 5, 9, 3, 2, 1, 0, 4},
    053        {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}};
    054
    055    /** P - permutation table */
    056    private static final int[][] P_TABLE = {
    057        {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
    058        {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},
    059        {5, 8, 0, 3, 7, 9, 6, 1, 4, 2},
    060        {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},
    061        {9, 4, 5, 3, 1, 2, 6, 8, 7, 0},
    062        {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},
    063        {2, 7, 9, 3, 8, 0, 6, 4, 1, 5},
    064        {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}};
    065
    066    /** Inverse table */
    067    private static final int[] INV_TABLE = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9};
    068
    069    /**
    070     * Constructs a new instance.
    071     */
    072    public VerhoeffCheckDigit() {
    073        // empty
    074    }
    075
    076    /**
    077     * Calculate a Verhoeff <em>Check Digit</em> for a code.
    078     *
    079     * @param code The code to calculate the Check Digit for
    080     * @return The calculated Check Digit
    081     * @throws CheckDigitException if an error occurs calculating
    082     * the check digit for the specified code
    083     */
    084    @Override
    085    public String calculate(final String code) throws CheckDigitException {
    086        if (GenericValidator.isBlankOrNull(code)) {
    087            throw new CheckDigitException("Code is missing");
    088        }
    089        final int checksum = calculateChecksum(code, false);
    090        return Integer.toString(INV_TABLE[checksum]);
    091    }
    092
    093    /**
    094     * Calculate the checksum.
    095     *
    096     * @param code The code to calculate the checksum for.
    097     * @param includesCheckDigit Whether the code includes the Check Digit or not.
    098     * @return The checksum value
    099     * @throws CheckDigitException if the code contains an invalid character (that is, a non-numeric character)
    100     */
    101    private int calculateChecksum(final String code, final boolean includesCheckDigit) throws CheckDigitException {
    102        int checksum = 0;
    103        for (int i = 0; i < code.length(); i++) {
    104            final int idx = code.length() - (i + 1);
    105            final int num = Character.getNumericValue(code.charAt(idx));
    106            if (num < 0 || num > 9) { // CHECKSTYLE IGNORE MagicNumber
    107                throw new CheckDigitException("Invalid Character[" +
    108                        i + "] = '" + (int) code.charAt(idx) + "'");
    109            }
    110            final int pos = includesCheckDigit ? i : i + 1;
    111            checksum = D_TABLE[checksum][P_TABLE[pos % 8][num]]; // CHECKSTYLE IGNORE MagicNumber
    112        }
    113        return checksum;
    114    }
    115
    116    /**
    117     * Validate the Verhoeff <em>Check Digit</em> for a code.
    118     *
    119     * @param code The code to validate
    120     * @return {@code true} if the check digit is valid,
    121     * otherwise {@code false}
    122     */
    123    @Override
    124    public boolean isValid(final String code) {
    125        if (GenericValidator.isBlankOrNull(code)) {
    126            return false;
    127        }
    128        try {
    129            return calculateChecksum(code, true) == 0;
    130        } catch (final CheckDigitException e) {
    131            return false;
    132        }
    133    }
    134
    135}