最近在公司有一個 fakedata 的項目,用來生成各類假資料,在各種測試環境,其中就有銀行卡卡号的生成,中國這方面是有自己的标準的,詳細的介紹可以參考 這篇文章
,寫的很清楚。
簡單來說,就是國内的銀行卡卡号,主要都是銀聯标準,然後前面的4-8位稱之為卡 bin,這個卡 bin 是可以區分是具體哪個銀行,以及是否是借記卡還是貸記卡(信用卡),關鍵是最後一位校驗位。
從校驗卡号的角度來說,可以在應用的盡量前端進行判斷,如果卡号校驗錯誤,就不用去進行四要素判斷,更不能進行實際的賬戶交易了。校驗碼對了,再根據卡 bin 判斷是什麼銀行和什麼性質的銀行卡(這個下次再說)。
這裡隻讨論銀行卡号碼本身的合法性,并不是通常意義說的三要素四要素銀行卡和身份證的校驗。
def get_bankcard_checkcode(card_number_str):
"""
計算銀行卡校驗位;
:param:
* card_number_str: (string) 要查詢的銀行卡号
:returns:
checkcode: (string) 銀行卡的校驗位
舉例如下::
from fishbase.fish_data import *
print('--- fish_data get_bankcard_checkcode demo ---')
# 不能放真的卡資訊,有風險
print(get_bankcard_checkcode('439188000699010'))
print('---')
輸出結果::
--- fish_data get_bankcard_checkcode demo ---
9
---
"""
total = 0
even = True
for item in card_number_str[-1::-1]:
item = int(item)
if even:
item <<= 1
if item > 9:
item -= 9
total += item
even = not even
checkcode = (10 - (total % 10)) % 10
return str(checkcode)
實際算法部分不算複雜,參考了一些網上看到的資料。需要的朋友可以借鑒。
代碼還在不斷優化中,可以參考我們的 Python 工具函數包 fishbase :
源代碼:
https://github.com/chinapnr/fishbase文檔:
https://fishbase.readthedocs.io/en/latest/pypi :
https://pypi.org/project/fishbase/