使用python實現rsa演算法代碼

來源:互聯網
上載者:User
RSA演算法是一種非對稱式加密演算法,是現在廣泛使用的公開金鑰加密演算法,主要應用是加密資訊和數位簽章。

維基百科給出的RSA演算法簡介如下:

假設Alice想要通過一個不可靠的媒體接收Bob的一條私人訊息。她可以用以下的方式來產生一個公開金鑰和一個私密金鑰:

隨意選擇兩個大的質數p和q,p不等於q,計算N=pq。

根據歐拉函數,不大於N且與N互質的整數個數為(p-1)(q-1)

選擇一個整數e與(p-1)(q-1)互質,並且e小於(p-1)(q-1)

用以下這個公式計算d:d × e ≡ 1 (mod (p-1)(q-1))

將p和q的記錄銷毀。

(N,e)是公開金鑰,(N,d)是私密金鑰。(N,d)是秘密的。Alice將她的公開金鑰(N,e)傳給Bob,而將她的私密金鑰(N,d)藏起來。

#!/usr/bin/env python def range_prime(start, end): l = list() for i in range(start, end+1): flag = True for j in range(2, i): if i % j == 0: flag = False break if flag: l.append(i) return l def generate_keys(p, q): #numbers = (11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47) numbers =range_prime(10, 100) N = p * q C = (p-1) * (q-1) e = 0 for n in numbers: if n < C and C % n > 0: e = n break if e==0: raise StandardError("e not found") d = 0 for n in range(2, C): if(e * n) % C == 1: d = n break if d==0: raise StandardError("d not found") return ((N, e), (N, d)) def encrypt(m, key): C, x = key return (m ** x) % C decrypt = encrypt if __name__ == '__main__': pub, pri = generate_keys(47, 79) L = range(20, 30) C = map(lambda x: encrypt(x, pub), L) D = map(lambda x: decrypt(x, pri), C) print "keys:", pub, pri print "message:", L print "encrypt:", C print "decrypt:", D keys: (3713, 11) (3713, 1631) message: [20, 21, 22, 23, 24, 25, 26, 27, 28, 29] encrypt: [406, 3622, 3168, 134, 3532, 263, 1313, 2743, 2603, 1025] decrypt: [20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L] 

以上所述是小編給大家介紹的使用python實現rsa演算法代碼,希望對大家有所協助!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.