test_crypt.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright 2016 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. from google.auth import crypt
  16. import yatest.common as yc
  17. DATA_DIR = os.path.join(os.path.dirname(yc.source_path(__file__)), "..", "data")
  18. # To generate privatekey.pem, privatekey.pub, and public_cert.pem:
  19. # $ openssl req -new -newkey rsa:1024 -x509 -nodes -out public_cert.pem \
  20. # > -keyout privatekey.pem
  21. # $ openssl rsa -in privatekey.pem -pubout -out privatekey.pub
  22. with open(os.path.join(DATA_DIR, "privatekey.pem"), "rb") as fh:
  23. PRIVATE_KEY_BYTES = fh.read()
  24. with open(os.path.join(DATA_DIR, "public_cert.pem"), "rb") as fh:
  25. PUBLIC_CERT_BYTES = fh.read()
  26. # To generate other_cert.pem:
  27. # $ openssl req -new -newkey rsa:1024 -x509 -nodes -out other_cert.pem
  28. with open(os.path.join(DATA_DIR, "other_cert.pem"), "rb") as fh:
  29. OTHER_CERT_BYTES = fh.read()
  30. def test_verify_signature():
  31. to_sign = b"foo"
  32. signer = crypt.RSASigner.from_string(PRIVATE_KEY_BYTES)
  33. signature = signer.sign(to_sign)
  34. assert crypt.verify_signature(to_sign, signature, PUBLIC_CERT_BYTES)
  35. # List of certs
  36. assert crypt.verify_signature(
  37. to_sign, signature, [OTHER_CERT_BYTES, PUBLIC_CERT_BYTES]
  38. )
  39. def test_verify_signature_failure():
  40. to_sign = b"foo"
  41. signer = crypt.RSASigner.from_string(PRIVATE_KEY_BYTES)
  42. signature = signer.sign(to_sign)
  43. assert not crypt.verify_signature(to_sign, signature, OTHER_CERT_BYTES)