Python代码与非对称密钥(公共和私有)加密/解密CSV文件

发布于 2025-01-17 19:46:08 字数 4253 浏览 4 评论 0原文

目的:使用非对称方法(公钥和私钥)加密/解密csv文件(各种大小) 尝试的解决方案:我们已经能够生成密钥,但无法加密 csv 文件。 另外,还没有尝试解密。 下面是我们尝试过的代码: 解决方案一: 非对称加密 -

#Asymmetric encryption-

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)
public_key = private_key.public_key()
from cryptography.hazmat.primitives import serialization
pem = private_key.private_bytes(
   encoding=serialization.Encoding.PEM,
   format=serialization.PrivateFormat.PKCS8,
   encryption_algorithm=serialization.NoEncryption()
)
with open('private_key.pem', 'wb') as f:
 f.write(pem)


from cryptography.hazmat.primitives import serialization
pem = public_key.public_bytes(
   encoding=serialization.Encoding.PEM,
   format=serialization.PublicFormat.SubjectPublicKeyInfo
)
with open('public_key.pem', 'wb') as f:
 f.write(pem)


from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
with open("private_key.pem", "rb") as key_file:
   private_key = serialization.load_pem_private_key(
       key_file.read(),
       password=None,
       backend=default_backend()
   )

with open("public_key.pem", "rb") as key_file:
   public_key = serialization.load_pem_public_key(
       key_file.read(),
       backend=default_backend()
   )

#Encryption
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
file = f"/data/nas/infacloud/ODSREP/Scripts/PMNONGMP_MEDI.csv"
f = open(file, 'rb')
message = f.read()
f.close()
encrypted = public_key.encrypt(
   message,
   padding.OAEP(
       mgf=padding.MGF1(algorithm=hashes.SHA256()),
       algorithm=hashes.SHA256(),
       label=None
   )
)
with open('PMNONGMP_MEDI_en', 'wb') as encrypted_file:
   encrypted_file.write(encrypted)
     
#Decryption
#from cryptography.hazmat.primitives import hashes
#from cryptography.hazmat.primitives.asymmetric import padding
#file1 = f"/data/nas/infacloud/ODSREP/Scripts/filekey_enc.key"
#f1 = open(file1, 'rb')
#message1 = f1.read()
#f1.close()
#original_message = private_key.decrypt(
#        message1,
#        padding.OAEP(
#            mgf=padding.MGF1(algorithm=hashes.SHA256()),
#            algorithm=hashes.SHA256(),
#            label=None
#        )
# )
#with open('filekey_dec.key', 'wb') as decrypted_file:
#   decrypted_file.write(original_message) 

错误: 回溯(最近一次调用最后一次): 文件“Encrypt2902.py”,第 109 行,位于 标签=无 文件“/opt/rh/rh-python36/root/lib64/python3.6/site-packages/cryptography/hazmat/backends/openssl/rsa.py”,第 537 行,加密 返回 _enc_dec_rsa(self._backend, self, 明文, 填充) 文件“/opt/rh/rh-python36/root/lib64/python3.6/site-packages/cryptography/hazmat/backends/openssl/rsa.py”,第 87 行,位于 _enc_dec_rsa 返回_enc_dec_rsa_pkey_ctx(后端,密钥,数据,padding_enum,填充) 文件“/opt/rh/rh-python36/root/lib64/python3.6/site-packages/cryptography/hazmat/backends/openssl/rsa.py”,第 151 行,位于 _enc_dec_rsa_pkey_ctx raise ValueError("加密/解密失败。") ValueError:加密/解密失败。

解决方案2:

import sys
import rsa

#generate private & public key and write to respective files(Asymmetric keys)
publicKey, privateKey = rsa.newkeys(4096)
pukey=open('publicKey.key','wb')
pukey.write(publicKey.save_pkcs1('PEM'))
pukey.close()
prkey=open('privateKey.key','wb')
prkey.write(privateKey.save_pkcs1('PEM'))
prkey.close()

#read the file for encrytion
skey=open('PMNONGMP_MEDI.csv','rb')
key=skey.read()

#open the public key file
pkey=open('publicKey.key','rb')
pkdata=pkey.read()

#load the file
pubkey=rsa.PublicKey.load_pkcs1(pkdata)

#encrypt the file with public key
encrypted_key=rsa.encrypt(key,pubkey)

#write the encrypted symmetric key to a file
#ekey= open('encrypted_symm_key.txt','wb')
ekey= open('PMNONGMP_MEDI_E.csv','wb')
ekey.write(encrypted_key)

错误: 回溯(最近一次调用最后一次): 文件“Encrypt2103.py”,第 37 行,位于 加密密钥=rsa.加密(密钥,公钥) 文件“/opt/rh/rh-python36/root/lib/python3.6/site-packages/rsa/pkcs1.py”,第 194 行,加密 填充= _pad_for_encryption(消息,密钥长度) 文件“/opt/rh/rh-python36/root/lib/python3.6/site-packages/rsa/pkcs1.py”,第 114 行,在 _pad_for_encryption 中 “ %i 的空间” % (msglength, max_msglength) OverflowError:消息需要2248字节,但只有501的空间

Aim: To encrypt/decrypt csv files(of various sizes) using asymmetric method(public and private keys)
Solutions tried: We have been able to generate the keys , but not able to encrypt the csv files.
Also, did not try decryption yet.
Below is the code we tried:
Solution 1:
Asymmetric encryption-

#Asymmetric encryption-

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)
public_key = private_key.public_key()
from cryptography.hazmat.primitives import serialization
pem = private_key.private_bytes(
   encoding=serialization.Encoding.PEM,
   format=serialization.PrivateFormat.PKCS8,
   encryption_algorithm=serialization.NoEncryption()
)
with open('private_key.pem', 'wb') as f:
 f.write(pem)


from cryptography.hazmat.primitives import serialization
pem = public_key.public_bytes(
   encoding=serialization.Encoding.PEM,
   format=serialization.PublicFormat.SubjectPublicKeyInfo
)
with open('public_key.pem', 'wb') as f:
 f.write(pem)


from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
with open("private_key.pem", "rb") as key_file:
   private_key = serialization.load_pem_private_key(
       key_file.read(),
       password=None,
       backend=default_backend()
   )

with open("public_key.pem", "rb") as key_file:
   public_key = serialization.load_pem_public_key(
       key_file.read(),
       backend=default_backend()
   )

#Encryption
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
file = f"/data/nas/infacloud/ODSREP/Scripts/PMNONGMP_MEDI.csv"
f = open(file, 'rb')
message = f.read()
f.close()
encrypted = public_key.encrypt(
   message,
   padding.OAEP(
       mgf=padding.MGF1(algorithm=hashes.SHA256()),
       algorithm=hashes.SHA256(),
       label=None
   )
)
with open('PMNONGMP_MEDI_en', 'wb') as encrypted_file:
   encrypted_file.write(encrypted)
     
#Decryption
#from cryptography.hazmat.primitives import hashes
#from cryptography.hazmat.primitives.asymmetric import padding
#file1 = f"/data/nas/infacloud/ODSREP/Scripts/filekey_enc.key"
#f1 = open(file1, 'rb')
#message1 = f1.read()
#f1.close()
#original_message = private_key.decrypt(
#        message1,
#        padding.OAEP(
#            mgf=padding.MGF1(algorithm=hashes.SHA256()),
#            algorithm=hashes.SHA256(),
#            label=None
#        )
# )
#with open('filekey_dec.key', 'wb') as decrypted_file:
#   decrypted_file.write(original_message) 

Error:
Traceback (most recent call last):
File "Encrypt2902.py", line 109, in
label=None
File "/opt/rh/rh-python36/root/lib64/python3.6/site-packages/cryptography/hazmat/backends/openssl/rsa.py", line 537, in encrypt
return _enc_dec_rsa(self._backend, self, plaintext, padding)
File "/opt/rh/rh-python36/root/lib64/python3.6/site-packages/cryptography/hazmat/backends/openssl/rsa.py", line 87, in _enc_dec_rsa
return _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding)
File "/opt/rh/rh-python36/root/lib64/python3.6/site-packages/cryptography/hazmat/backends/openssl/rsa.py", line 151, in _enc_dec_rsa_pkey_ctx
raise ValueError("Encryption/decryption failed.")
ValueError: Encryption/decryption failed.

Solution2:

import sys
import rsa

#generate private & public key and write to respective files(Asymmetric keys)
publicKey, privateKey = rsa.newkeys(4096)
pukey=open('publicKey.key','wb')
pukey.write(publicKey.save_pkcs1('PEM'))
pukey.close()
prkey=open('privateKey.key','wb')
prkey.write(privateKey.save_pkcs1('PEM'))
prkey.close()

#read the file for encrytion
skey=open('PMNONGMP_MEDI.csv','rb')
key=skey.read()

#open the public key file
pkey=open('publicKey.key','rb')
pkdata=pkey.read()

#load the file
pubkey=rsa.PublicKey.load_pkcs1(pkdata)

#encrypt the file with public key
encrypted_key=rsa.encrypt(key,pubkey)

#write the encrypted symmetric key to a file
#ekey= open('encrypted_symm_key.txt','wb')
ekey= open('PMNONGMP_MEDI_E.csv','wb')
ekey.write(encrypted_key)

Error:
Traceback (most recent call last):
File "Encrypt2103.py", line 37, in
encrypted_key=rsa.encrypt(key,pubkey)
File "/opt/rh/rh-python36/root/lib/python3.6/site-packages/rsa/pkcs1.py", line 194, in encrypt
padded = _pad_for_encryption(message, keylength)
File "/opt/rh/rh-python36/root/lib/python3.6/site-packages/rsa/pkcs1.py", line 114, in _pad_for_encryption
" space for %i" % (msglength, max_msglength)
OverflowError: 2248 bytes needed for message, but there is only space for 501

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文