Python實現的rsa密碼編譯演算法詳解,pythonrsa密碼編譯演算法

來源:互聯網
上載者:User

Python實現的rsa密碼編譯演算法詳解,pythonrsa密碼編譯演算法

本文執行個體講述了Python實現的rsa密碼編譯演算法。分享給大家供大家參考,具體如下:

演算法過程

1. 隨意選擇兩個大的質數p和q,p不等於q,計算N=pq。
2. 根據歐拉函數,不大於N且與N互質的整數個數為(p-1)(q-1)。
3. 選擇一個整數e與(p-1)(q-1)互質,並且e小於(p-1)(q-1)。
4. 用以下這個公式計算d:d× e ≡ 1 (mod (p-1)(q-1))。
5. 將p和q的記錄銷毀。

(N,e)是公開金鑰,(N,d)是私密金鑰。

python代碼

# -*- coding: utf-8 -*-#!/usr/bin/env pythondef 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 ldef 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") #Python3中改為BaseException 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) % Cdecrypt = encryptif __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 "幫客之家測試結果:" print "keys:", pub, pri print "message:", L print "encrypt:", C print "decrypt:", D

運行結果:

其實用什麼語言實現這個過程都不是很麻煩,只是我們老師要求產生1024的隨機數,用c語言寫就有點噁心了,所以用python或者java實現要更加方便一點。

PS:關於加密解密感興趣的朋友還可以參考本站線上工具:

文字線上加密解密工具(包含AES、DES、RC4等):
http://tools.jb51.net/password/txt_encode

MD5線上加密工具:
http://tools.jb51.net/password/CreateMD5Password

線上散列/雜湊演算法加密工具:
http://tools.jb51.net/password/hash_encrypt

線上MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.jb51.net/password/hash_md5_sha

線上sha1/sha224/sha256/sha384/sha512加密工具:
http://tools.jb51.net/password/sha_encode

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.