基于python+PyQt5的Google身份驗(yàn)證器

致謝聲明

1.本文學(xué)習(xí)nanhuier的博客《Python計(jì)算谷歌身份驗(yàn)證器的驗(yàn)證碼》并優(yōu)化其中代碼。
原博客鏈接:https://blog.csdn.net/nanhuier/article/details/77679200
2.本文學(xué)習(xí)莫水千流的博客《程序員之路:python3+PyQt5+pycharm桌面GUI開發(fā)》,
成功搭建PyQt5+Pycharm的開發(fā)環(huán)境,建議讀者先按照此文配置好環(huán)境。
原博客鏈接:https://www.cnblogs.com/zhoug2020/p/9039993.html
3.本文學(xué)習(xí)maicss的github工程《PyQt5-Chinese-tutorial》
github鏈接:https://github.com/maicss/PyQt5-Chinese-tutorial
4.本文學(xué)習(xí)晴空行的博客《Python打包方法》,
原博客鏈接:https://www.cnblogs.com/gopythoner/p/6337543.html

0.完整代碼

讀者安裝PyQt5庫后可以直接運(yùn)行此段代碼查看程序效果。
安裝PyQt5庫命令:pip install pyqt5
本文的第1節(jié)《定義函數(shù)getGoogleCode》、第2節(jié)《定義類Ui_Form》、第3節(jié)《定義程序入口,即主函數(shù)main》是本節(jié)《完整代碼》的分段講解。

import base64, time, struct, hmac, hashlib
def getGoogleCode(secretKey):
    decoded_secretKey = base64.b32decode(secretKey, True)
    interval_number = int(time.time() // 30)
    message = struct.pack(">Q", interval_number)
    digest = hmac.new(decoded_secretKey, message, hashlib.sha1).digest()
    index = ord(chr(digest[19])) % 16
    googleCode = (struct.unpack(">I", digest[index:index+4])[0] & 0x7fffffff) % 1000000
    return "%06d" %googleCode

from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton
from PyQt5.QtCore import QCoreApplication, QTimer, QRect, QMetaObject
class Ui_Form(object):
    def setupUi(self, Form):
        #Form setting
        Form.setObjectName("googleAuthenticator")
        Form.resize(450, 350)
        #lineEdit_secretKey setting
        self.lineEdit_secretKey = QLineEdit(Form)
        self.lineEdit_secretKey.setGeometry(QRect(180, 40, 190, 40))
        font = QFont()
        font.setFamily("Agency FB")
        font.setPointSize(16)
        self.lineEdit_secretKey.setFont(font)
        self.lineEdit_secretKey.setObjectName("lineEdit_secretKey")
        #label setting
        self.label = QLabel(Form)
        self.label.setGeometry(QRect(40, 40, 70, 40))
        font = QFont()
        font.setFamily("Agency FB")
        font.setPointSize(22)
        self.label.setFont(font)
        self.label.setObjectName("label")
        #label_2 setting
        self.label_2 = QLabel(Form)
        self.label_2.setGeometry(QRect(20, 100, 170, 40))
        font = QFont()
        font.setFamily("Agency FB")
        font.setPointSize(24)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        #label_googleCode setting
        self.label_googleCode = QLabel(Form)
        self.label_googleCode.setGeometry(QRect(260, 100, 140, 40))
        font = QFont()
        font.setFamily("Agency FB")
        font.setPointSize(24)
        self.label_googleCode.setFont(font)
        self.label_googleCode.setText("")
        self.label_googleCode.setObjectName("label_googleCode")
        #lable_3 setting
        self.label_3 = QLabel(Form)
        self.label_3.setGeometry(QRect(30, 160, 140, 40))
        font = QFont()
        font.setFamily("Agency FB")
        font.setPointSize(24)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        #label_validTime setting
        self.label_validTime = QLabel(Form)
        self.label_validTime.setGeometry(QRect(260, 160, 140, 40))
        font = QFont()
        font.setFamily("Agency FB")
        font.setPointSize(24)
        self.label_validTime.setFont(font)
        self.label_validTime.setText("")
        self.label_validTime.setObjectName("label_validTime")
        #pushButton setting
        self.pushButton = QPushButton(Form)
        self.pushButton.setGeometry(QRect(50, 240, 140, 50))
        font = QFont()
        font.setFamily("Agency FB")
        font.setPointSize(24)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        #pushButton_2 setting
        self.pushButton_2 = QPushButton(Form)
        self.pushButton_2.setGeometry(QRect(230, 240, 140, 50))
        font = QFont()
        font.setFamily("Agency FB")
        font.setPointSize(24)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setObjectName("pushButton_2")
        #other settings
        self.retranslateUi(Form)
        QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(QCoreApplication.translate("Form", "GoogleAuthenticator"))
        self.lineEdit_secretKey.setText(QCoreApplication.translate("Form", "DHNJH6Y6FZJUUB32"))
        self.label.setText(QCoreApplication.translate("Form", "密鑰:"))
        self.label_2.setText(QCoreApplication.translate("Form", "谷歌驗(yàn)證碼:"))
        self.label_3.setText(QCoreApplication.translate("Form", "有效時(shí)間:"))
        self.pushButton.setText(QCoreApplication.translate("Form", "開始轉(zhuǎn)換"))
        self.pushButton_2.setText(QCoreApplication.translate("Form", "暫停轉(zhuǎn)換"))
        self.pushButton.clicked.connect(self.init_refresh)
        self.pushButton_2.clicked.connect(self.disable)

    #backstage function code
    def init_refresh(self):
        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.start()
        self.timer.timeout.connect(self.refresh)

    def refresh(self):
        secretKey = self.lineEdit_secretKey.text()
        googleCode = getGoogleCode(secretKey)
        self.label_googleCode.setText(googleCode)
        nowTime = time.time()
        validTime = 30 - (int(nowTime) % 30)
        self.label_validTime.setText(str(validTime) + '秒')
        self.is_disable = False

    def disable(self):
        if not self.is_disable:
            self.timer.disconnect()
            self.is_disable = True
            
from sys import argv, exit
if __name__ == "__main__":
    application = QApplication(argv)
    mainWindow = QMainWindow()
    userInterface = Ui_Form()
    userInterface.setupUi(mainWindow)
    userInterface.init_refresh()
    mainWindow.show()
    exit(application.exec_())

1.定義函數(shù)getGoogleCode

函數(shù)getGoogleCode的功能是將密鑰轉(zhuǎn)換為谷歌驗(yàn)證器的驗(yàn)證碼。
下面一段代碼中:
第1行是導(dǎo)入需要引用的庫。
第2行是定義函數(shù)getGoogleCode,指明此函數(shù)需要1個(gè)參數(shù)secretKey。
第3行是調(diào)用base64.b32decode方法將密鑰secretKey做解碼,得到的結(jié)果賦值個(gè)變量decoded_secretKey。
第4行是調(diào)用time.time方法得出當(dāng)前時(shí)間距離1970年1月1日0時(shí)0分的秒數(shù),此秒數(shù)除以30得出的商,賦值給變量interval_number。
第5行是調(diào)用struct.pack方法將數(shù)據(jù)打包為長整型數(shù)據(jù),賦值給變量message。
本文作者也未完全理解struct.pack方法,講解struct.pack方法的博客:
1.《Python學(xué)習(xí)——struct模塊的pack、unpack示例》,鏈接:https://www.cnblogs.com/hushaojun/p/6489350.html
2.《python中struct.pack()函數(shù)和struct.unpack()函數(shù)》,鏈接:https://www.cnblogs.com/litaozijin/p/6506354.html
第6行調(diào)用hmac.new方法,方法需要3個(gè)參數(shù),方法結(jié)果得到1個(gè)對象,此對象的digest方法的結(jié)果賦值給變量digest。
第7行chr方法是將0-255范圍的數(shù)字轉(zhuǎn)換為字符,ord方法是將字符轉(zhuǎn)換為0-255范圍的數(shù)字。
經(jīng)過2次轉(zhuǎn)換得到的結(jié)果除以16得出的余數(shù)賦值給變量index。
第8行根據(jù)變量index從變量digest中取出長度為4的字符串,此字符串作為struct.unpack方法的第2個(gè)參數(shù),struct.unpack方法得出的結(jié)果與0x7fffffff做按位取與運(yùn)算,位運(yùn)算的結(jié)果除以1000000的余數(shù)為谷歌驗(yàn)證碼。
第9行返回谷歌驗(yàn)證碼googleCode,%06d表示如果數(shù)字不滿6位則前面補(bǔ)零。
第11-12行是本文作者的1個(gè)谷歌驗(yàn)證碼做測試,運(yùn)行本段代碼即可查看結(jié)果。
因?yàn)楣雀栩?yàn)證碼和密鑰、時(shí)間這2者相關(guān),所以每次運(yùn)行可能結(jié)果不同。
讀者可以使用自己谷歌驗(yàn)證碼嘗試。

import base64, time, struct, hmac, hashlib
def getGoogleCode(secretKey):
    decoded_secretKey = base64.b32decode(secretKey, True)
    interval_number = int(time.time() // 30)
    message = struct.pack(">Q", interval_number)
    digest = hmac.new(decoded_secretKey, message, hashlib.sha1).digest()
    index = ord(chr(digest[19])) % 16
    googleCode = (struct.unpack(">I", digest[index:index+4])[0] & 0x7fffffff) % 1000000
    return "%06d" %googleCode

secretKey = "DHNJH6Y6FZJUUb32"
print(getGoogleCode(secretKey))

2.定義類Ui_Form

UI是user interface的簡寫,中文叫做用戶界面。
本節(jié)中的內(nèi)容主要是與PyQt5開發(fā)相關(guān)。
因?yàn)轭怳i_Form的代碼較長,并且已經(jīng)在第0節(jié)《完整代碼》中給出,本節(jié)中不再復(fù)制。
在類Ui_Form中共有5個(gè)方法:setupUi、retranslateUi、init_refresh、refresh、disable
setupUi方法的作用是初始化用戶界面,在其中定義了8個(gè)小部件的位置、字體、字大小、對象名。
retranslate中文叫做重譯,retranslateUi方法的作用是設(shè)置用戶界面各小部件的文本內(nèi)容和按鈕的連接函數(shù)。
init_refresh方法的作用是初始化刷新谷歌驗(yàn)證碼,即開始刷新谷歌驗(yàn)證碼。
refresh方法的作用是刷新谷歌驗(yàn)證碼,配合init_refresh方法編寫。
QTimer對象可以通過setInterval方法設(shè)置間隔,即過指定的時(shí)間調(diào)用指定的refresh方法。
disable方法的作用是停止轉(zhuǎn)換,只有停止轉(zhuǎn)換后才可以在密鑰輸入框中改變密鑰的值,否則程序會(huì)報(bào)錯(cuò)并退出。

3.定義程序入口,即主函數(shù)main

下面一段代碼中:
第1行從sys庫中引入argv和exit。
第2行是python程序入口的標(biāo)準(zhǔn)寫法。
第3行調(diào)用QApplication類實(shí)例化對象,賦值給變量application,此方法需要參數(shù)argv。
第4行調(diào)用QMainWindow類實(shí)例化對象,賦值給變量mainWindow。
第5行調(diào)用Ui_Form類實(shí)例化對象,賦值給變量userInterface。
第6行調(diào)用變量userInterface的SetupUi方法設(shè)置界面程序的界面。
第7行調(diào)用變量userInterface的init_refresh方法初始化界面程序的刷新功能。
第8行調(diào)用變量mainWindow的show方法,是界面程序能夠顯示。
第9行是PyQt5程序的固定寫法。

from sys import argv, exit
if __name__ == "__main__":
    application = QApplication(argv)
    mainWindow = QMainWindow()
    userInterface = Ui_Form()
    userInterface.setupUi(mainWindow)
    userInterface.init_refresh()
    mainWindow.show()
    exit(application.exec_())

4.用PyInstaller封裝代碼為exe可執(zhí)行文件

使用pip命令安裝PyInstaller:pip install PyInstaller
在代碼文件同級(jí)目錄中打開cmd。
打開cmd方法如下圖所示:在資源管理器中輸入cmd,并按Enter鍵運(yùn)行。

image.png

讀者先將自己的代碼文件名改為googleAuthenticator.py
然后在cmd中輸入并運(yùn)行命令:PyInstaller -F -w googleAuthenticator.py
如下圖紅色箭頭標(biāo)注處所示,則成功生成exe可執(zhí)行文件:
image.png

如下圖紅色箭頭標(biāo)注處所示,exe可執(zhí)行文件在dist文件夾中。
image.png

5.程序效果圖展示

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容