数据加密是指将明文转化为密文的过程,以保证数据在传输或存储过程中不被非法获取或篡改。常见的加密算法有对称加密和非对称加密。
对称加密是指加密和解密使用同一把密钥的加密方式,常见的对称加密算法有DES、AES等。
非对称加密是指加密和解密使用不同密钥的加密方式,常见的非对称加密算法有RSA、DSA等。
解密就是将密文转化为明文的过程,只有知道密钥的人才能够解密。
在代码中实现数据加密和解密,可以使用各种编程语言自带的加密库或第三方加密库。以Python为例:
Python自带的加密库有hashlib、hmac等,还可以使用第三方库pycrypto、pycryptodome等。
对称加密的实现:
import hashlib
import base64
from Crypto.Cipher import AES
key = hashlib.sha256(b'mykey').digest()
iv = b'myiv'
def encrypt(message):
message = message.encode()
cipher = AES.new(key, AES.MODE_CFB, iv)
ciphertext = cipher.encrypt(message)
return base64.b64encode(ciphertext).decode()
def decrypt(ciphertext):
ciphertext = base64.b64decode(ciphertext.encode())
cipher = AES.new(key, AES.MODE_CFB, iv)
message = cipher.decrypt(ciphertext)
return message.decode()
非对称加密的实现:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
private_key = RSA.generate(2048)
public_key = private_key.publickey()
def encrypt(message):
message = message.encode()
cipher = PKCS1_OAEP.new(public_key)
ciphertext = cipher.encrypt(message)
return ciphertext.hex()
def decrypt(ciphertext):
ciphertext = bytes.fromhex(ciphertext)
cipher = PKCS1_OAEP.new(private_key)
message = cipher.decrypt(ciphertext)
return message.decode()
上述代码仅为示例,实际应用中需要根据具体需求进行调整和优化。