码迷,mamicode.com
首页 > 其他好文 > 详细

身份证验证合法性工具

时间:2017-09-16 13:33:44      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:static   integer   package   validate   public   length   date   sys   substr   

1.代码

 

package Utils.ValidateIdcard;


public class IDCard {
    final int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };
    final int[] vi = { 1, 0, ‘X‘, 9, 8, 7, 6, 5, 4, 3, 2 };
    private int[] ai = new int[18];

    public IDCard() {}

    public boolean Verify(String idcard) {
        if (idcard.length() == 15) {
            idcard = uptoeighteen(idcard);
        }
        if (idcard.length() != 18) {
            return false;
        }
        String verify = idcard.substring(17, 18);
        if (verify.equals(getVerify(idcard))) {
            return true;
        }
        return false;
    }

    public String getVerify(String eightcardid) {
        int remaining = 0;

        if (eightcardid.length() == 18) {
            eightcardid = eightcardid.substring(0, 17);
        }

        if (eightcardid.length() == 17) {
            int sum = 0;
            for (int i = 0; i < 17; i++) {
                String k = eightcardid.substring(i, i + 1);
                ai[i] = Integer.parseInt(k);
            }

            for (int i = 0; i < 17; i++) {
                sum = sum + wi[i] * ai[i];
            }
            remaining = sum % 11;
        }

        return remaining == 2 ? "X" : String.valueOf(vi[remaining]);
    }

    public String uptoeighteen(String fifteencardid) {
        String eightcardid = fifteencardid.substring(0, 6);
        eightcardid = eightcardid + "19";
        eightcardid = eightcardid + fifteencardid.substring(6, 15);
        eightcardid = eightcardid + getVerify(eightcardid);
        return eightcardid;
    }
    
    public static void main(String[] args) {
        
        String idcard1 = "140423199402153201"; 
        String idcard2 = "350211197607442059";
        
        IDCard idcard = new IDCard(); 
        System.out.println(idcard.Verify(idcard1)); 
        System.out.println(idcard.Verify(idcard2)); 
    }

}

 

 

 

 

true
false

 

身份证验证合法性工具

标签:static   integer   package   validate   public   length   date   sys   substr   

原文地址:http://www.cnblogs.com/qlqwjy/p/7530673.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!