hifumi
2022-04-30 12:31:36 +08:00
这个需求还是挺简单的,只要 RSA 加密时你不加盐值就可以了呀,RSA 就是一个乘方取模运算,下面的实现支持加密、验证和解密,密钥长度可以改,只要密码比密钥短就行了(如果需要支持密码比密钥长也可以修改一下下面的 demo ,实现分组加密)
```
from Cryptodome.PublicKey import RSA
def encrypt(public_key, password):
password = int.from_bytes(password, byteorder='big')
encrypted_password = pow(password, public_key.e, public_key.n)
return encrypted_password
def decrypt(private_key, encrypted_password, length):
decrypted = pow(encrypted_password, private_key.d, private_key.n).to_bytes(byteorder='big', length=length)
return decrypted
def verify_password(public_key, encrypted_password, password_to_be_verified):
return encrypted_password == encrypt(public_key, password_to_be_verified)
if __name__ == "__main__":
ras_key_length = 2 ** 10
private = RSA.generate(bits=ras_key_length)
public = private.publickey()
original_password = b"passwordpaordpasswordpasswordpasswordpasswordpasswordpasswordpasrdpasswordpasswordpassword"
print("Original password:", original_password)
encrypted = encrypt(public, original_password)
print("Encrypted password:", hex(encrypted))
print("Verification result:", verify_password(public, encrypted, original_password))
decrypted = decrypt(private, encrypted, ras_key_length // 8)
print("Decrypted password:", decrypted)
```
运行结果如下
```
Original password: b'passwordpaordpasswordpasswordpasswordpasswordpasswordpasswordpasrdpasswordpasswordpassword'
Encrypted password: 0x68334196df3d5c177e55e102f939ca2f0b2275e774159f0814921440161e5aad4e54076d13039f74733068dbad1d7c69e433a21b78f4ad485110bad0d45ff9b1ad5cf71a24ae16f14e53cd4b7f3d021f3a8b3e911f493da1339918c6e7bd9f23ef0f876a2142fd7f3de4556f64a7b12cb230f0c06a57571b6ad6ee1bfef85731
Verification result: True
Decrypted password: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00passwordpaordpasswordpasswordpasswordpasswordpasswordpasswordpasrdpasswordpasswordpassword'
```