Add more demonstrative code to examples (#6234)

1. In signature generation code example, add a `key' assignment so it can be run solely.
2. In verify() code example, add a positive case before the negative one. Also use copy() to do self authentication.

Co-authored-by: Baofeng Wang <baofeng.wang67@gmail.com>
This commit is contained in:
match man 2021-08-29 16:45:19 +03:00 committed by GitHub
parent 3c2488b8a2
commit cd4ae74ef1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -28,10 +28,12 @@ of a message.
.. doctest::
>>> from cryptography.hazmat.primitives import hashes, hmac
>>> key = b'test key. Beware! A real key should use os.urandom or TRNG to generate'
>>> h = hmac.HMAC(key, hashes.SHA256())
>>> h.update(b"message to hash")
>>> h.finalize()
b'#F\xdaI\x8b"e\xc4\xf1\xbb\x9a\x8fc\xff\xf5\xdex.\xbc\xcd/+\x8a\x86\x1d\x84\'\xc3\xa6\x1d\xd8J'
>>> signature = h.finalize()
>>> signature
b'k\xd9\xb29\xefS\xf8\xcf\xec\xed\xbf\x95\xe6\x97X\x18\x9e%\x11DU1\x9fq}\x9a\x9c\xe0)y`='
If the backend doesn't support the requested ``algorithm`` an
:class:`~cryptography.exceptions.UnsupportedAlgorithm` exception will be
@ -48,7 +50,10 @@ of a message.
>>> h = hmac.HMAC(key, hashes.SHA256())
>>> h.update(b"message to hash")
>>> h.verify(b"an incorrect signature")
>>> h_copy = h.copy() # get a copy of `h' to be reused
>>> h.verify(signature)
>>>
>>> h_copy.verify(b"an incorrect signature")
Traceback (most recent call last):
...
cryptography.exceptions.InvalidSignature: Signature did not match digest.