python3 常见解密加密算法

一.使用base64

Base64编码,64指A-Z、a-z、0-9、+和/这64个字符,还有“=”号不属于编码字符,而是填充字符。

优点:方法简单

缺点:不保险,别人拿到密文可以自己解密出明文

编码原理:将3个字节转换成4个字节((3 X 8)=24=(4X6)),先读入3个字节,每读一个字节,左移8位,再右移四次,每次6位,这样就有4个字节了。
解码原理:将4个字节转换成3个字节,先读入4个6位(用或运算),每次左移6位,再右移3次,每次8位,这样就还原了。

Python3中base64模块与Python2使用方法有了明显的不一样,接下来简要介绍下base64模块。

Python 3.5.2+ (default, Aug  5 2016, 08:07:14)
[GCC 6.1.1 20160724] on linux
Type "help", "copyright", "credits" or "license" for more information.

首先导入base64模块

>>> import base64
>>> my_str='hello'

然后把字符串转码为UTF-8格式:

>>> utf_str=my_str.encode(encoding="utf-8")
>>> utf_str
b'hello'

我们试着用Base64方式加密:

>>> word=base64.b64encode(utf_str)
>>> word
b'aGVsbG8='

最后用Base64方式解密:

>>> hello=base64.b64decode(word.decode())
>>> hello
b'hello'
>>> hello.decode()
'hello'
可以看到,已经成功解密出来!

二.使用pycrypto

Python有个专门的加密解密工具包pycropto,这个包里面实现了MD2,MD4,MD5,RIPEMD,SHA1,SHA256等加密算法。

>>> from Crypto.Hash import MD5

>>> obj = MD5.new()

>>> obj.update(b"hello")
>>> obj.hexdigest()

>>> obj.hexdigest()
'5d41402abc4b2a76b9719d911017c592'  



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Python3 RSA 加密和解密代码: ```python import random # 求最大公因数 def gcd(a, b): while b: a, b = b, a % b return a # 求模反元素 def modinv(a, m): if gcd(a, m) != 1: return None # 如果 a 和 m 不互质,则不存在模反元素 u1, u2, u3 = 1, 0, a v1, v2, v3 = 0, 1, m while v3 != 0: q = u3 // v3 v1, v2, v3, u1, u2, u3 = ( u1 - q * v1, u2 - q * v2, u3 - q * v3, v1, v2, v3 ) return u1 % m # 生成公钥和私钥 def generate_keypair(p, q): n = p * q phi = (p - 1) * (q - 1) e = random.randrange(1, phi) while gcd(e, phi) != 1: e = random.randrange(1, phi) d = modinv(e, phi) return (e, n), (d, n) # 加密函数 def encrypt(public_key, plaintext): e, n = public_key ciphertext = [pow(ord(char), e, n) for char in plaintext] return ciphertext # 解密函数 def decrypt(private_key, ciphertext): d, n = private_key plaintext = [chr(pow(char, d, n)) for char in ciphertext] return ''.join(plaintext) # 测试 p, q = 61, 53 public_key, private_key = generate_keypair(p, q) plaintext = 'Hello World!' ciphertext = encrypt(public_key, plaintext) decrypted_text = decrypt(private_key, ciphertext) print('加密前:', plaintext) print('加密后:', ciphertext) print('解密后:', decrypted_text) ``` 这段代码中使用了两个大素数 p 和 q 生成了公钥和私钥,使用了欧拉函数 phi、模反元素和快速幂算法进行加密和解密。需要注意的是,这里加密和解密的文本都必须是 ASCII 码,如果需要加密中文等非 ASCII 码字符,可使用 Base64 等编码方式将其转换为 ASCII 码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值