脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 利用Python实现RSA加密解密方法实例

利用Python实现RSA加密解密方法实例

2022-11-24 10:28浅若清风cyf Python

过去几天我一直在尝试用Python实现RSA算法,下面这篇文章主要给大家介绍了关于利用Python实现RSA加密解密的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下

前言

  • 加密技术在数据安全存储,数据传输中发挥着重要作用,能够保护用户隐私数据安全,防止信息窃取。RSA是一种非对称加密技术,在软件、网页中已得到广泛应用。本文将介绍RSA加密解密在python中的实现。
  • 原则:公钥加密,私钥解密
  • 解释:具体过程的解释请见代码前的注释

RSA加密实验基本流程:

一、选取两个大素数p、q,并计算得到n、phi_n

二、选取常用的e = 0x10001,方便将幂运算优化为左移,加快运算速度

三、计算d,使用了扩展欧几里得算法

四、输入明文a,将明文转化为可以用于计算的数字形式

五、对a使用快速幂取模,得到密文b,以16进制显示

RSA解密流程:

六、对b使用快速幂取模,得到明文a,以字符形式显示

一、安装模块

?
1
pip install pycryptodome

二、生成密钥对

  • 密钥对文件生成和读取
  • 代码:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from Crypto.PublicKey import RSA
def create_rsa_pair(is_save=False):
    '''
    创建rsa公钥私钥对
    :param is_save: default:False
    :return: public_key, private_key
    '''
    f = RSA.generate(2048)
    private_key = f.exportKey("PEM"# 生成私钥
    public_key = f.publickey().exportKey()  # 生成公钥
    if is_save:
        with open("crypto_private_key.pem", "wb") as f:
            f.write(private_key)
        with open("crypto_public_key.pem", "wb") as f:
            f.write(public_key)
    return public_key, private_key
 
def read_public_key(file_path="crypto_public_key.pem") -> bytes:
    with open(file_path, "rb") as x:
        b = x.read()
        return b
 
def read_private_key(file_path="crypto_private_key.pem") -> bytes:
    with open(file_path, "rb") as x:
        b = x.read()
        return b

三、加密

  • 流程:输入文本(str)→字符串编码(默认utf-8)(bytes)→rsa加密(bytes)→base64编码(bytes)→解码为字符串(str)
  • 代码:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
 
def encryption(text: str, public_key: bytes):
    # 字符串指定编码(转为bytes)
    text = text.encode('utf-8')
    # 构建公钥对象
    cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key))
    # 加密(bytes)
    text_encrypted = cipher_public.encrypt(text)
    # base64编码,并转为字符串
    text_encrypted_base64 = base64.b64encode(text_encrypted ).decode()
    return text_encrypted_base64
    
if __name__ == '__main__':
    public_key = read_public_key()
    text = '123456'
    text_encrypted_base64 = encryption(text, public_key)
    print('密文:',text_encrypted_base64)

四、解密

  • 说明:解密流程与加密流程相反(按照加密流程逆序解密)
  • 流程:输入文本(str)→字符串编码(默认utf-8)(bytes)→base64解码(bytes)→rsa解密(bytes)→解码为字符串(str)
  • 代码:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
from Crypto.PublicKey import RSA
 
def decryption(text_encrypted_base64: str, private_key: bytes):
    # 字符串指定编码(转为bytes)
    text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
    # base64解码
    text_encrypted = base64.b64decode(text_encrypted_base64 )
    # 构建私钥对象
    cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key))
    # 解密(bytes)
    text_decrypted = cipher_private.decrypt(text_encrypted , Random.new().read)
    # 解码为字符串
    text_decrypted = text_decrypted.decode()
    return text_decrypted
    
if __name__ == '__main__':
    # 生成密文
    public_key = read_public_key()
    text = '123456'
    text_encrypted_base64 = encryption(text, public_key)
    print('密文:',text_encrypted_base64)
    
    # 解密
    private_key = read_private_key()
    text_decrypted = decryption(text_encrypted_base64, private_key)
    print('明文:',text_decrypted)

五、完整代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import base64
from Crypto.Cipher import PKCS1_v1_5
from Crypto import Random
from Crypto.PublicKey import RSA
# ------------------------生成密钥对------------------------
def create_rsa_pair(is_save=False):
    '''
    创建rsa公钥私钥对
    :param is_save: default:False
    :return: public_key, private_key
    '''
    f = RSA.generate(2048)
    private_key = f.exportKey("PEM"# 生成私钥
    public_key = f.publickey().exportKey()  # 生成公钥
    if is_save:
        with open("crypto_private_key.pem", "wb") as f:
            f.write(private_key)
        with open("crypto_public_key.pem", "wb") as f:
            f.write(public_key)
    return public_key, private_key
 
def read_public_key(file_path="crypto_public_key.pem") -> bytes:
    with open(file_path, "rb") as x:
        b = x.read()
        return b
 
def read_private_key(file_path="crypto_private_key.pem") -> bytes:
    with open(file_path, "rb") as x:
        b = x.read()
        return b
# ------------------------加密------------------------
def encryption(text: str, public_key: bytes):
    # 字符串指定编码(转为bytes)
    text = text.encode('utf-8')
    # 构建公钥对象
    cipher_public = PKCS1_v1_5.new(RSA.importKey(public_key))
    # 加密(bytes)
    text_encrypted = cipher_public.encrypt(text)
    # base64编码,并转为字符串
    text_encrypted_base64 = base64.b64encode(text_encrypted).decode()
    return text_encrypted_base64
 
# ------------------------解密------------------------
def decryption(text_encrypted_base64: str, private_key: bytes):
    # 字符串指定编码(转为bytes)
    text_encrypted_base64 = text_encrypted_base64.encode('utf-8')
    # base64解码
    text_encrypted = base64.b64decode(text_encrypted_base64)
    # 构建私钥对象
    cipher_private = PKCS1_v1_5.new(RSA.importKey(private_key))
    # 解密(bytes)
    text_decrypted = cipher_private.decrypt(text_encrypted, Random.new().read)
    # 解码为字符串
    text_decrypted = text_decrypted.decode()
    return text_decrypted
 
if __name__ == '__main__':
    # 生成密钥对
    # create_rsa_pair(is_save=True)
    # public_key = read_public_key()
    # private_key = read_private_key()
    public_key, private_key = create_rsa_pair(is_save=False)
 
    # 加密
    text = '123456'
    text_encrypted_base64 = encryption(text, public_key)
    print('密文:', text_encrypted_base64)
 
    # 解密
    text_decrypted = decryption(text_encrypted_base64, private_key)
    print('明文:', text_decrypted)

利用Python实现RSA加密解密方法实例

总结

到此这篇关于利用Python实现RSA加密解密的文章就介绍到这了,更多相关Python RSA加密解密内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://juejin.cn/post/7083429856330907685

延伸 · 阅读

精彩推荐
  • PythonPython 自动化修改word的案例

    Python 自动化修改word的案例

    这篇文章主要介绍了Python 自动化修改word的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    Python3.78032021-09-16
  • PythonPython深入浅出分析enum枚举类

    Python深入浅出分析enum枚举类

    在python中枚举是一种类(Enum,IntEnum),存放在enum模块中。枚举类型可以给一组标签赋予一组特定的值,本文给大家介绍的非常详细,对大家的学习或工作具...

    Flyme awei6502022-07-21
  • Pythonpython使用reportlab生成pdf实例

    python使用reportlab生成pdf实例

    大家好,本篇文章主要讲的是python使用reportlab生成pdf实例,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下...

    yujie.zhao9992022-09-16
  • Pythonpython 排序算法总结及实例详解

    python 排序算法总结及实例详解

    这篇文章主要介绍了python 排序算法总结及实例详解的相关资料,需要的朋友可以参考下 ...

    Python教程网5752020-09-09
  • PythonPython实现用户注册登录程序

    Python实现用户注册登录程序

    这篇文章主要为大家详细介绍了Python实现用户注册登录程序,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    %木糖醇---LHY%10172022-09-14
  • PythonPython中的__init__作用是什么

    Python中的__init__作用是什么

    在本篇文章里小编给大家分享的是关于Python中的__init__作用以及相关用法内容,需要的朋友们可以学习下。 ...

    silencement14732020-06-10
  • PythonPython实现从脚本里运行scrapy的方法

    Python实现从脚本里运行scrapy的方法

    这篇文章主要介绍了Python实现从脚本里运行scrapy的方法,实例分析了Python脚本运行的使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下 ...

    pythoner7772020-05-31
  • Pythonpython3 实现在运行的时候隐藏命令窗口

    python3 实现在运行的时候隐藏命令窗口

    这篇文章主要介绍了python3 实现在运行的时候隐藏命令窗口方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...

    卧枝惠中天10372021-11-05