OTP 就是 One-time password,翻譯過來就是一次性密碼。它的原理非常簡單,加密的過程就是明文和密鑰(key)進行異或,得到密文,而解密的過程就是密文和密鑰(key)異或,得到明文。
不知道你是否相信,只需 10 行代碼,就可以使用 Python 100% 安全地加密文件。這背后的原理就是 OTP。
原理
OTP 就是 One-time password,翻譯過來就是一次性密碼。它的原理非常簡單,加密的過程就是明文和密鑰(key)進行異或,得到密文,而解密的過程就是密文和密鑰(key)異或,得到明文。舉例如下:
加密:

解密:

理論上,基于以下假設,這個加密被認為是牢不可破的:
- 密鑰是真正隨機的
- 密鑰長度與信息長度相同
- 密鑰永遠不會全部或部分重復使用
- 密鑰 key 很安全,不會公開
應用:加密文件
如果自己有一個私密的文件,那么完全可以使用 OTP 來加密,密鑰保存在自己手里,很安全。話不多說,直接上代碼:
加密文件:
import os
def encryption(file):
toBeEncryptedFile = open(file, 'rb').read()
size = len(toBeEncryptedFile)
otpKey = os.urandom(size)
with open(file.split('.')[0] + '.key', 'wb') as key:
key.write(otpKey)
encryptedFile = bytes (a ^ b for (a, b) in zip(toBeEncryptedFile, otpKey))
with open(file, 'wb') as encrypted:
encrypted.write(encryptedFile)
這段代碼一共 10 行,密鑰 optKey 隨機生成并保存在文件中,然后用這個密鑰加密文件,當需要加密文件時,這樣調(diào)用 encryption 函數(shù):
if __name__ == "__main__":
encryption("/Users/aaron/Downloads/1/銀行卡.JPG")

成功執(zhí)行代碼后,我們無法再預覽或打開我們的圖像,因為它現(xiàn)在是加密的。此外,我們的文件夾中有一個新的密鑰文件“銀行卡.key”。

現(xiàn)在,我們來解密它。
解密文件只需要 6 行代碼:
def decryption(file, otpKey):
encryptedFile = open(file, 'rb').read()
otpKey = open(otpKey, 'rb').read()
decryptedFile = bytes (a ^ b for (a, b) in zip(encryptedFile, otpKey))
with open(file, 'wb') as decrypted:
decrypted.write(decryptedFile)
這樣調(diào)用:
if __name__ == "__main__":
# encryption("/Users/aaron/Downloads/1/銀行卡.JPG")
decryption("/Users/aaron/Downloads/1/銀行卡.JPG", "/Users/aaron/Downloads/1/銀行卡.key")
這樣就完成了解密:

完整代碼
import os
def encryption(file):
toBeEncryptedFile = open(file, "rb").read()
size = len(toBeEncryptedFile)
otpKey = os.urandom(size)
with open(file.split(".")[0] + ".key", "wb") as key:
key.write(otpKey)
encryptedFile = bytes(a ^ b for (a, b) in zip(toBeEncryptedFile, otpKey))
with open(file, "wb") as encrypted:
encrypted.write(encryptedFile)
def decryption(file, otpKey):
encryptedFile = open(file, "rb").read()
otpKey = open(otpKey, "rb").read()
decryptedFile = bytes(a ^ b for (a, b) in zip(encryptedFile, otpKey))
with open(file, "wb") as decrypted:
decrypted.write(decryptedFile)
if __name__ == "__main__":
# encryption("/Users/aaron/Downloads/1/銀行卡.JPG")
decryption("/Users/aaron/Downloads/1/銀行卡.JPG", "/Users/aaron/Download