一個Rsa混合Ascill的編碼方案

一個以Rsa加密算法爲核心,以acill碼爲外層封裝的簡單混合編碼方案:
加密思路:

  • 1.將輸入的明文,按字節轉化成對應的acill碼,形成數據源
  • 2.遍歷數據源,生成密文組
  • 3.將密文組進行0位填充(代碼是3位數,不足三位數前置對應數量的0),使之長度一致,拼接形成密文
    解密思路:
  • 1.密文分解成密文數組(代碼裏是按3位)
  • 2.遍歷密文數組,解碼,獲得明文數據源
  • 3.遍歷明文數據源,轉化成ascill,拼接形成明文

說明:

  • 1.代碼裏面的p和q是隨便定下的,如果這個數值有發生變化的話,注意調整0位填充的個數,避免數據丟失
  • 2.代碼結構可能會顯得很混亂,畢竟一開始只是想順着思路寫個Rsa的Demo,沒想到後面想到一點補充一點,就。。。你懂的
  • 3.有個新信仰,叫CTF,有個新稱號,叫菜雞,所以,代碼有需要反饋的地方,煩請指出,畢竟新手上路,這車翻不翻,不在人,在車~
  • 4.命名垃圾,結構一般,辛苦各位看官的眼睛了~~

廢話完畢,翠花,上代碼:

#獲取N
def getN(p,q):
    return p*q
    pass
#獲取最大值
def getM(p,q):
    if p>q:
        return p
    return q
#獲取最大公倍數
def getLcm(p,q):
    a=getM(p,q)
    b=p+q-a;
    while b!=0:
        c=a
        a=b
        b=int(c%b)
        pass
    return int(p*q/a)
    pass
#判斷兩數是否互質
def checkGcd(p,q):
    a=getM(p,q)
    b=p+q-a;
    while int(a%b):
        c=b
        b=int(a%b)
        a=c
        pass
    return b==1
    pass
#獲取加密E值
def getE(lcm):
    for i in range(2,lcm):
        if checkGcd(i,lcm):
            return i
            pass
        pass
    pass
#獲取解密D值
def getD(e,lcm):
    for d in range(2,lcm):
        if d*e%lcm==1:
            return d
            pass
        pass
    pass
#核心:加密
def encrypto(p,q,pwd):
    L=getLcm(p-1,q-1)
    return pwd ** getE(L) % getN(p,q)
#核心:解密
def decrypto(p,q,enc):
    L=getLcm(p-1,q-1)
    E=getE(L)
    return enc ** getD(E,L) % getN(p,q)
#字符串轉數組
def sToI(s):
    num=[]
    for n in s:
        num.append(ord(n))
        pass
    return num
    pass
#數組轉字符串    
def iToS(num):
    s=""
    for n in num:
        s+=chr(n)
        pass
    return s
    pass
#0位前置填充
def getZero(num):
    if num >=100:
        return ""
    elif num >=10:
        return "0"
    else:
        return "00"
#處理加密後的數據並返回
def Doenc(p,q,pwds):
    encs=[]
    s=""
    for pwd in pwds:
        encs.append(encrypto(p,q,pwd))
        pass
    for enc in encs:
        s+=(getZero(enc)+str(enc))
        pass
    return s;
#處理需要解密的數據並返回數據源
def Dodec(enc):
    encs=[]
    step=3
    start=0
    end=step
    while end <=len(enc):
        encs.append(int(enc[start:end]))
        start=end
        end+=3
        pass
    return encs
def main():
    #p,q,採用的是acill混合rsa的方式,17*19的乘積已經大於acill的範圍,可以更改
    p=17
    q=19
    type=input("加密輸入0,解密輸入1:")
    if type == "0":
        pwd=input("輸入明文:")
        pwds = sToI(pwd)
        enc = Doenc(p,q,pwds)
        print("密文是:",enc)
        pass 
    else:
        enc=input("輸入密文:")
        encs = Dodec(enc.strip())
        decs=[]
        for enc in encs:
            decs.append(decrypto(p,q,enc))
            pass
        print("明文是",iToS(decs))
        pass
    pass

if __name__ == "__main__":
    main()
    pass
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章