在现代信息时代,信息安全已经成为我们日常生活中不可或缺的一部分。而加密体制作为保障信息安全的核心技术,其发展历程可谓跌宕起伏。从古老的密码术到现代的数字安全,让我们一起揭开加密体制的神秘面纱。
古老的密码术
在互联网尚未普及的年代,人们就已经开始探索如何保护信息不被他人窃取。古老的密码术主要依靠纸笔进行,其形式多样,如替换密码、移位密码、栅栏密码等。以下是一些典型的古老密码术:
替换密码
替换密码是一种将原文中的每个字母或符号替换成另一个字母或符号的加密方法。例如,凯撒密码就是一种替换密码,它将字母表中的每个字母向后移动3位。
def caesar_cipher(text, shift):
result = ""
for char in text:
if char.isalpha():
shifted = ord(char) + shift
if char.islower():
if shifted > ord('z'):
shifted -= 26
elif char.isupper():
if shifted > ord('Z'):
shifted -= 26
result += chr(shifted)
else:
result += char
return result
# 示例
original_text = "hello world"
encrypted_text = caesar_cipher(original_text, 3)
print(encrypted_text) # Output: killo zruog
移位密码
移位密码是一种将字母表中的字母按照一定的顺序进行移位的加密方法。例如,一次右移一位的移位密码称为一次移位密码。
def shift_cipher(text, shift):
result = ""
for char in text:
if char.isalpha():
shifted = ord(char) + shift
if char.islower():
if shifted > ord('z'):
shifted -= 26
elif char.isupper():
if shifted > ord('Z'):
shifted -= 26
result += chr(shifted)
else:
result += char
return result
# 示例
original_text = "hello world"
encrypted_text = shift_cipher(original_text, 1)
print(encrypted_text) # Output: ifmmp xpsme
栅栏密码
栅栏密码是一种将原文分成若干行,然后将每行的字母依次排列成密文的加密方法。例如,将原文“hello world”分成两行,得到密文“hloewo lrld”。
现代加密体制
随着计算机技术的不断发展,古老的密码术逐渐被现代加密体制所取代。现代加密体制主要分为对称加密和非对称加密两种。
对称加密
对称加密是指加密和解密使用相同的密钥。常见的对称加密算法有DES、AES、Blowfish等。
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
def aes_encrypt(plain_text, key):
cipher = AES.new(key, AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(plain_text.encode('utf-8'), AES.block_size))
iv = cipher.iv
return iv + ct_bytes
def aes_decrypt(encrypted_text, key):
iv = encrypted_text[:16]
ct = encrypted_text[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
pt = unpad(cipher.decrypt(ct), AES.block_size).decode('utf-8')
return pt
# 示例
key = b'1234567890123456'
original_text = "hello world"
encrypted_text = aes_encrypt(original_text, key)
print(encrypted_text) # Output: iv+密文
decrypted_text = aes_decrypt(encrypted_text, key)
print(decrypted_text) # Output: hello world
非对称加密
非对称加密是指加密和解密使用不同的密钥,即公钥和私钥。常见的非对称加密算法有RSA、ECC等。
from Crypto.PublicKey import RSA
def generate_keys():
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()
return private_key, public_key
def rsa_encrypt(plain_text, public_key):
key = RSA.import_key(public_key)
encrypted_text = key.encrypt(plain_text.encode('utf-8'))
return encrypted_text
def rsa_decrypt(encrypted_text, private_key):
key = RSA.import_key(private_key)
decrypted_text = key.decrypt(encrypted_text)
return decrypted_text.decode('utf-8')
# 示例
private_key, public_key = generate_keys()
original_text = "hello world"
encrypted_text = rsa_encrypt(original_text, public_key)
print(encrypted_text) # Output: 密文
decrypted_text = rsa_decrypt(encrypted_text, private_key)
print(decrypted_text) # Output: hello world
总结
加密体制的发展历程见证了人类对信息安全的不断追求。从古老的密码术到现代的加密体制,我们见证了信息安全的演变。掌握加密体制,有助于我们在信息时代更好地保护自己的信息安全。
