openssl gcm
时间: 2025-01-06 11:46:41 浏览: 61
### 使用 OpenSSL 实现 AES-GCM 模式的加密和解密
#### 加密过程
为了实现基于 OpenSSL 库的 AES-GCM 加密操作,可以采用如下 Python 代码片段来展示这一流程:
```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def encrypt_gcm(data, key):
cipher = AES.new(key, AES.MODE_GCM)
ciphertext, tag = cipher.encrypt_and_digest(data)
return (cipher.nonce, ciphertext, tag)
data = b'example plaintext'
key = get_random_bytes(32) # AES-256 requires a 256-bit key
nonce, ciphertext, tag = encrypt_gcm(data, key)
print(f"Ciphertext: {ciphertext.hex()}")
print(f"Tag: {tag.hex()}")
print(f"Nonce: {nonce.hex()}")[^4]
```
上述代码创建了一个新的 `AES` 对象并指定了 GCM 模式。调用 `encrypt_and_digest()` 方法不仅返回了经过加密的数据 (`ciphertext`) ,还提供了用于验证数据完整性的标签 (`tag`) 。此外,初始化向量(IV),在这里被称为 nonce,在每次执行加密函数时都会自动生成。
#### 解密过程
对于解密部分,则可以通过下面这段代码完成:
```python
def decrypt_gcm(nonce, ciphertext, tag, key):
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)
return data
decrypted_data = decrypt_gcm(nonce, ciphertext, tag, key)
print(f"Decrypted Data: {decrypted_data.decode('utf-8')}")
```
此段程序通过传递给构造器相同的密钥以及之前获得的 nonce 来重新实例化 `AES` 类对象。接着利用 `decrypt_and_verify()` 函数尝试恢复原始明文的同时也检验了接收到的消息是否未被篡改过。
需要注意的是以上例子依赖 PyCryptodome 库而非直接使用 OpenSSL C API;然而两者底层逻辑相同,并且都遵循标准定义下的 AES-GCM 行为特性。
阅读全文
相关推荐


















