Hướng dẫn rsa python library - thư viện python rsa

Mật mã khóa công cộng thường chỉ được sử dụng cho một lượng nhỏ dữ liệu. Nó là chậm, và có thể khó sử dụng đúng. Thực tiễn thông thường là sử dụng các phương pháp khác để giảm vấn đề không đối xứng xuống một trong đó bảo mật được cung cấp bởi khóa chung, sau đó sử dụng mật mã khóa công cộng để bảo vệ khóa chia sẻ đó. Ví dụ:

  • Để mã hóa một tệp, ngẫu nhiên tạo khóa bí mật cho một khối hoặc mật mã phát (ví dụ: AES). Lưu trữ dữ liệu được mã hóa bằng mật mã này và lưu trữ khóa bí mật được mã hóa bằng khóa công khai cùng với tải trọng được mã hóa.
  • Để ký một tệp, hãy tính toán một bản ghi âm mật mã hóa (ví dụ: SHA-256). Ký vào tiêu hóa của tệp với khóa riêng và lưu trữ cùng với tệp.

Vì vậy, đây là một bản phác thảo về cách mã hóa có thể trông giống như (cảnh báo, mã chưa được kiểm tra, được nhập trực tiếp vào trình duyệt):

import os
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
import Crypto.Util.number
def encrypt_file(rsa, input, output):
    # Generate secret key
    secret_key = os.urandom(16)
    # Padding (see explanations below)
    plaintext_length = (Crypto.Util.number.size(rsa.n) - 2) / 8
    padding = '\xff' + os.urandom(16)
    padding += '\0' * (plaintext_length - len(padding) - len(secret_key))
    # Encrypt the secret key with RSA
    encrypted_secret_key = rsa.encrypt(padding + secret_key, None)
    # Write out the encrypted secret key, preceded by a length indication
    output.write(str(len(encrypted_secret_key)) + '\n')
    output.write(encrypted_secret_key)
    # Encrypt the file (see below regarding iv)
    iv = '\x00' * 16
    aes_engine = AES.new(secret_key, AES.MODE_CBC, iv)
    output.write(aes_engine.encrypt(input.read()))

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate public and private keys

publickey = key.publickey # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext

f = open ('encryption.txt', 'w'w)
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open ('encryption.txt', 'r')
message = f.read()

decrypted = key.decrypt(message)

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
2 là một vectơ khởi tạo cho chế độ hoạt động CBC. Nó cần phải là duy nhất cho mỗi khóa cho mỗi tin nhắn. Thông thường, nó được gửi cùng với dữ liệu trong Cleartext. Ở đây, vì chìa khóa chỉ được sử dụng một lần, bạn có thể sử dụng IV đã biết.initialization vector for the CBC mode of operation. It needs to be unique per key per message. Normally, it's sent alongside the data in cleartext. Here, since the key is only ever used once, you can use a known IV.initialization vector for the CBC mode of operation. It needs to be unique per key per message. Normally, it's sent alongside the data in cleartext. Here, since the key is only ever used once, you can use a known IV.

API của mật mã khối được mô tả trong PEP 272. Thật không may, nó chỉ hỗ trợ mã hóa tất cả tại một hoạt động. Đối với các tệp lớn, sẽ tốt hơn nếu mã hóa chunk bằng chunk; Bạn có thể mã hóa ít như một khối tại một thời điểm (16 byte cho AES), nhưng bạn cần một thư viện tiền điện tử tốt hơn cho điều đó.

Lưu ý rằng nói chung, bạn không nên mã hóa dữ liệu trực tiếp với RSA. Mối quan tâm rõ ràng nhất là kẻ tấn công biết khóa công khai và do đó có thể cố gắng đoán bản rõ (nếu kẻ tấn công nghĩ rằng bản rõ có thể là

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate public and private keys

publickey = key.publickey # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext

f = open ('encryption.txt', 'w'w)
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open ('encryption.txt', 'r')
message = f.read()

decrypted = key.decrypt(message)

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
3, thì kẻ tấn công có thể mã hóa
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate public and private keys

publickey = key.publickey # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext

f = open ('encryption.txt', 'w'w)
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open ('encryption.txt', 'r')
message = f.read()

decrypted = key.decrypt(message)

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
3 với khóa công khai RSA và so sánh kết quả với đầu ra của mã hóa RSA). Một mối quan tâm khác sẽ phát sinh nếu bạn muốn gửi tệp cho nhiều người nhận là nếu bước mã hóa RSA là xác định, thì kẻ tấn công có thể nói rằng các bản rõ là như nhau vì các mã hóa là như nhau. Bảo vệ bình thường chống lại các vấn đề này là sử dụng sơ đồ đệm, bao gồm việc thêm một số dữ liệu bí mật ngẫu nhiên vào bản rõ; Dữ liệu này được gọi là đệm. Kẻ tấn công sau đó không thể đoán được dữ liệu ngẫu nhiên và nhìn thấy các kết quả khác nhau cho mỗi mã hóa vì cùng một bản rõ không bao giờ được mã hóa hai lần; Theo như người nhận hợp pháp có liên quan, phần đệm chỉ là dữ liệu có thể bị vứt đi.padding scheme, which consists of adding some random secret data to the plaintext; this data is called padding. The attacker then cannot guess the random data, and sees different outcomes for every encryption because the same plaintext is never encrypted twice; as far as the legitimate recipient is concerned, the padding is just data that can be thrown away.padding scheme, which consists of adding some random secret data to the plaintext; this data is called padding. The attacker then cannot guess the random data, and sees different outcomes for every encryption because the same plaintext is never encrypted twice; as far as the legitimate recipient is concerned, the padding is just data that can be thrown away.

Ở đây, có vẻ như các mối quan tâm trên không áp dụng trong kịch bản này. Tuy nhiên, có những điểm yếu khác có thể phát sinh từ việc sử dụng RSA không được bảo vệ. Cụ thể, nếu số mũ công cộng rất nhỏ (không phải là trường hợp ở đây vì pycrypto sử dụng 65537) hoặc bạn mã hóa cùng một tài liệu cho nhiều người nhận khác nhau (một lần nữa, có lẽ không phải là trường hợp ở đây vì mỗi tin nhắn có khóa bí mật riêng), sau đó Tính toán toán học đơn giản sẽ cho phép kẻ tấn công phục hồi bản rõ RSA. Để tránh cuộc tấn công này, giá trị được mã hóa bằng RSA cần phải có đủ gần với mô đun RSA, do đó, hoạt động mã hóa thực sự thực hiện một số ít mô -đun. Phần đệm tôi đề xuất đảm bảo rằng bằng cách tạo byte bậc cao nhất phù hợp với 0xFF; Điều này được cho là an toàn, mặc dù trong thế giới thực, bạn nên sử dụng chế độ đệm được phê duyệt (OAEP).

Hãy coi chừng bằng cách sử dụng Crypto !!! Nó là một thư viện tuyệt vời nhưng nó có vấn đề trong python3.8 'vì thời gian thư viện đã bị xóa đồng hồ thuộc tính (). Để khắc phục nó chỉ cần sửa đổi nguồn ở

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate public and private keys

publickey = key.publickey # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext

f = open ('encryption.txt', 'w'w)
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open ('encryption.txt', 'r')
message = f.read()

decrypted = key.decrypt(message)

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
2dòng 77 thay đổi
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate public and private keys

publickey = key.publickey # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext

f = open ('encryption.txt', 'w'w)
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open ('encryption.txt', 'r')
message = f.read()

decrypted = key.decrypt(message)

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
3int
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate public and private keys

publickey = key.publickey # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext

f = open ('encryption.txt', 'w'w)
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open ('encryption.txt', 'r')
message = f.read()

decrypted = key.decrypt(message)

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
4VietcomBank, BIDV, VietinBank, SacomBank, TechcomBank, Á Châu, TPbank, MBbank, AgriBank, VPbank, SHB, MaritimeBank, DongAbank, VIB, EximBank, HDbank, NCB, Việt Á, OceanBank, PGbank, BacAbank...
VietcomBank, BIDV, VietinBank, SacomBank, TechcomBank, Á Châu, TPbank,
MBbank, AgriBank, VPbank, SHB, MaritimeBank, DongAbank, VIB, EximBank,
HDbank, NCB, Việt Á, OceanBank, PGbank, BacAbank...

0 hữu ích 0 bình luận chia sẻ

Đăng nhập để trả lời câu hỏi

Có thể bạn quan tâmVietcomBank, BIDV, VietinBank, SacomBank, TechcomBank, Á Châu, TPbank, MBbank, AgriBank, VPbank, SHB, MaritimeBank
VietcomBank, BIDV, VietinBank, SacomBank, TechcomBank, Á Châu, TPbank,
MBbank, AgriBank, VPbank, SHB, MaritimeBank

0 hữu ích 0 bình luận chia sẻ

Đăng nhập để trả lời câu hỏi

Có thể bạn quan tâmVietcomBank, BIDV, VietinBank, SacomBank, TechcomBank, Á Châu, TPbank, MBbank, AgriBank, VPbank, SHB, MaritimeBank

Có thể bạn quan tâm

Bạn cần đăng nhập để tải code qua chức năng này!

  ĐĂNG NHẬP NGAY

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate public and private keys

publickey = key.publickey # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext

f = open ('encryption.txt', 'w'w)
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open ('encryption.txt', 'r')
message = f.read()

decrypted = key.decrypt(message)

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
  • Hỗ trợ CHUYỂN KHOẢN TRỰC TIẾP qua các số tài khoản ngân hàng:VietcomBank, BIDV, VietinBank, SacomBank, TechcomBank, Á Châu, TPbank, MBbank, AgriBank, VPbank, SHB, MaritimeBank
  • Tôi cần trợ giúp bằng cách sử dụng mã hóa và giải mã RSA bằng Python.
  • Tôi đang tạo cặp khóa riêng tư / công khai, mã hóa tin nhắn bằng các khóa và ghi tin nhắn vào tệp. Sau đó, tôi đang đọc bản mã từ tệp và giải mã văn bản bằng cách sử dụng khóa.
  • Tôi đang gặp sự cố với phần giải mã. Như bạn có thể thấy trong đoạn mã của tôi bên dưới, khi tôi đưa vào
    import Crypto
    from Crypto.PublicKey import RSA
    from Crypto import Random
    
    random_generator = Random.new().read
    key = RSA.generate(1024, random_generator) #generate public and private keys
    
    publickey = key.publickey # pub key export for exchange
    
    encrypted = publickey.encrypt('encrypt this message', 32)
    #message to encrypt is in the above line 'encrypt this message'
    
    print 'encrypted message:', encrypted #ciphertext
    
    f = open ('encryption.txt', 'w'w)
    f.write(str(encrypted)) #write ciphertext to file
    f.close()
    
    #decrypted code below
    
    f = open ('encryption.txt', 'r')
    message = f.read()
    
    decrypted = key.decrypt(message)
    
    print 'decrypted', decrypted
    
    f = open ('encryption.txt', 'w')
    f.write(str(message))
    f.write(str(decrypted))
    f.close()
    
    1chương trình đó hoạt động, nhưng thông báo đã giải mã lại được mã hóa. Có vẻ như nó không đọc bản mã từ tệp.

Bất cứ ai có thể giúp tôi viết mã này để giải mã đọc bản mã từ tệp và sau đó sử dụng khóa để giải mã bản mã? 5 bình luận 193k xem chia sẻ 5 bình luận 193k xem chia sẻ

answer

52

python

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key

publickey = key.publickey() # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open('encryption.txt', 'r')
message = f.read()


decrypted = key.decrypt(ast.literal_eval(str(encrypted)))

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()

encryption 4 bình luận chia sẻ 4 bình luận chia sẻ

answer

9

# coding: utf-8
from __future__ import unicode_literals
import base64
import os

import six
from Crypto import Random
from Crypto.PublicKey import RSA


class PublicKeyFileExists(Exception): pass


class RSAEncryption(object):
    PRIVATE_KEY_FILE_PATH = None
    PUBLIC_KEY_FILE_PATH = None

    def encrypt(self, message):
        public_key = self._get_public_key()
        public_key_object = RSA.importKey(public_key)
        random_phrase = 'M'
        encrypted_message = public_key_object.encrypt(self._to_format_for_encrypt(message), random_phrase)[0]
        # use base64 for save encrypted_message in database without problems with encoding
        return base64.b64encode(encrypted_message)

    def decrypt(self, encoded_encrypted_message):
        encrypted_message = base64.b64decode(encoded_encrypted_message)
        private_key = self._get_private_key()
        private_key_object = RSA.importKey(private_key)
        decrypted_message = private_key_object.decrypt(encrypted_message)
        return six.text_type(decrypted_message, encoding='utf8')

    def generate_keys(self):
        """Be careful rewrite your keys"""
        random_generator = Random.new().read
        key = RSA.generate(1024, random_generator)
        private, public = key.exportKey(), key.publickey().exportKey()

        if os.path.isfile(self.PUBLIC_KEY_FILE_PATH):
            raise PublicKeyFileExists('Файл с публичным ключом существует. Удалите ключ')
        self.create_directories()

        with open(self.PRIVATE_KEY_FILE_PATH, 'w') as private_file:
            private_file.write(private)
        with open(self.PUBLIC_KEY_FILE_PATH, 'w') as public_file:
            public_file.write(public)
        return private, public

    def create_directories(self, for_private_key=True):
        public_key_path = self.PUBLIC_KEY_FILE_PATH.rsplit('/', 1)
        if not os.path.exists(public_key_path):
            os.makedirs(public_key_path)
        if for_private_key:
            private_key_path = self.PRIVATE_KEY_FILE_PATH.rsplit('/', 1)
            if not os.path.exists(private_key_path):
                os.makedirs(private_key_path)

    def _get_public_key(self):
        """run generate_keys() before get keys """
        with open(self.PUBLIC_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _get_private_key(self):
        """run generate_keys() before get keys """
        with open(self.PRIVATE_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _to_format_for_encrypt(value):
        if isinstance(value, int):
            return six.binary_type(value)
        for str_type in six.string_types:
            if isinstance(value, str_type):
                return value.encode('utf8')
        if isinstance(value, six.binary_type):
            return value

python

KEYS_DIRECTORY = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS

class TestingEncryption(RSAEncryption):
    PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'
    PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'


# django/flask
from django.core.files import File

class ProductionEncryption(RSAEncryption):
    PUBLIC_KEY_FILE_PATH = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS + 'public.key'

    def _get_private_key(self):
        """run generate_keys() before get keys """
        from corportal.utils import global_elements
        private_key = global_elements.request.FILES.get('private_key')
        if private_key:
            private_key_file = File(private_key)
            return private_key_file.read()

message = 'Hello мой friend'
encrypted_mes = ProductionEncryption().encrypt(message)
decrypted_mes = ProductionEncryption().decrypt(message)

encryption 4 bình luận chia sẻ 0 bình luận chia sẻ

answer

8

python

from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Cipher import PKCS1_OAEP


def rsa_encrypt_decrypt():
    key = RSA.generate(2048)
    private_key = key.export_key('PEM')
    public_key = key.publickey().exportKey('PEM')
    message = input('plain text for RSA encryption and decryption:')
    message = str.encode(message)

    rsa_public_key = RSA.importKey(public_key)
    rsa_public_key = PKCS1_OAEP.new(rsa_public_key)
    encrypted_text = rsa_public_key.encrypt(message)
    #encrypted_text = b64encode(encrypted_text)

    print('your encrypted_text is : {}'.format(encrypted_text))


    rsa_private_key = RSA.importKey(private_key)
    rsa_private_key = PKCS1_OAEP.new(rsa_private_key)
    decrypted_text = rsa_private_key.decrypt(encrypted_text)

    print('your decrypted_text is : {}'.format(decrypted_text))

encryption 4 bình luận chia sẻ 2 bình luận chia sẻ

answer

3

python

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate public and private keys

publickey = key.publickey # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext

f = open ('encryption.txt', 'w'w)
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open ('encryption.txt', 'r')
message = f.read()

decrypted = key.decrypt(message)

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
0

encryption 4 bình luận chia sẻ 3 bình luận chia sẻ

answer

1

python

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate public and private keys

publickey = key.publickey # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext

f = open ('encryption.txt', 'w'w)
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open ('encryption.txt', 'r')
message = f.read()

decrypted = key.decrypt(message)

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
1

encryption 4 bình luận chia sẻ 0 bình luận chia sẻ

answer

0

python

encryption 4 bình luận chia sẻ 0 bình luận chia sẻ

rsa

pycrypto 0 bình luận chia sẻ