35 lines
833 B
Plaintext
35 lines
833 B
Plaintext
![]() |
== How to fix it in pyca
|
||
|
|
||
|
=== Code examples
|
||
|
|
||
|
The example uses a hardcoded IV as a nonce, which causes AES-CCM to be insecure. To fix it, a nonce is randomly generated instead.
|
||
|
|
||
|
==== Noncompliant code example
|
||
|
|
||
|
[source,python,diff-id=201,diff-type=noncompliant]
|
||
|
----
|
||
|
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||
|
|
||
|
def encrypt(key, plaintext):
|
||
|
nonce = '7cVgr5cbdCZV'.encode('utf-8')
|
||
|
cipher = AESGCM(key)
|
||
|
|
||
|
cipher.encrypt(nonce, plaintext, None) # Noncompliant
|
||
|
----
|
||
|
|
||
|
==== Compliant solution
|
||
|
|
||
|
[source,python,diff-id=201,diff-type=compliant]
|
||
|
----
|
||
|
from os import urandom
|
||
|
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||
|
|
||
|
def encrypt(key, plaintext):
|
||
|
nonce = urandom(12)
|
||
|
cipher = AESGCM(key)
|
||
|
|
||
|
cipher.encrypt(nonce, plaintext, None)
|
||
|
----
|
||
|
|
||
|
include::../../common/how-does-this-work.adoc[]
|