Python3.7實(shí)現(xiàn)RC4加密解密(超詳細(xì))

在密碼學(xué)中,RC4(來(lái)自Rivest Cipher 4的縮寫(xiě))是一種流加密算法,密鑰長(zhǎng)度可變。它加解密使用相同的密鑰,因此也屬于對(duì)稱(chēng)加密算法。RC4是有線等效加密(WEP)中采用的加密算法,也曾經(jīng)是TLS可采用的算法之一。本文直接給出加密解密代碼,看圖,看注釋?zhuān)?/h6>

運(yùn)行結(jié)果:


捕獲.PNG

加密源碼:

import base64
def rc4_main(key = "init_key", message = "init_message"):
    # print("RC4加密主函數(shù)")
    s_box = rc4_init_sbox(key)
    crypt = str(rc4_excrypt(message, s_box))
    return  crypt
def rc4_init_sbox(key):
    s_box = list(range(256))  # 我這里沒(méi)管秘鑰小于256的情況,小于256不斷重復(fù)填充即可
    # print("原來(lái)的 s 盒:%s" % s_box)
    j = 0
    for i in range(256):
        j = (j + s_box[i] + ord(key[i % len(key)])) % 256
        s_box[i], s_box[j] = s_box[j], s_box[i]
    # print("混亂后的 s 盒:%s"% s_box)
    return s_box
def rc4_excrypt(plain, box):
    # print("調(diào)用加密程序成功。")
    res = []
    i = j = 0
    for s in plain:
        i = (i + 1) % 256
        j = (j + box[i]) % 256
        box[i], box[j] = box[j], box[i]
        t = (box[i] + box[j]) % 256
        k = box[t]
        res.append(chr(ord(s) ^ k))
    # print("res用于加密字符串,加密后是:%res" %res)
    cipher = "".join(res)
    # print("加密后的字符串是:%s" %cipher)
    # print("加密后的輸出(經(jīng)過(guò)編碼):")
    # print(str(base64.b64encode(cipher.encode('utf-8')), 'utf-8'))
    return (str(base64.b64encode(cipher.encode('utf-8')), 'utf-8'))
# rc4_main("123456sh","123456sh")

解密源碼:

import base64
def rc4_main(key = "init_key", message = "init_message"):
    # print("RC4解密主函數(shù)調(diào)用成功")
    s_box = rc4_init_sbox(key)
    crypt = rc4_excrypt(message, s_box)
    return crypt
def rc4_init_sbox(key):
    s_box = list(range(256))  # 我這里沒(méi)管秘鑰小于256的情況,小于256不斷重復(fù)填充即可
    # print("原來(lái)的 s 盒:%s" % s_box)
    j = 0
    for i in range(256):
        j = (j + s_box[i] + ord(key[i % len(key)])) % 256
        s_box[i], s_box[j] = s_box[j], s_box[i]
    # print("混亂后的 s 盒:%s"% s_box)
    return s_box
def rc4_excrypt(plain, box):
    # print("調(diào)用解密程序成功。")
    plain = base64.b64decode(plain.encode('utf-8'))
    plain = bytes.decode(plain)
    res = []
    i = j = 0
    for s in plain:
        i = (i + 1) % 256
        j = (j + box[i]) % 256
        box[i], box[j] = box[j], box[i]
        t = (box[i] + box[j]) % 256
        k = box[t]
        res.append(chr(ord(s) ^ k))
    # print("res用于解密字符串,解密后是:%res" %res)
    cipher = "".join(res)
    # print("解密后的字符串是:%s" %cipher)
    # print("解密后的輸出(沒(méi)經(jīng)過(guò)任何編碼):")
    return  cipher
# rc4_main("123456sh", "ABHCum92PMOXwqI=")
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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