_python_rsa.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. """Pure-Python RSA cryptography implementation.
  15. Uses the ``rsa``, ``pyasn1`` and ``pyasn1_modules`` packages
  16. to parse PEM files storing PKCS#1 or PKCS#8 keys as well as
  17. certificates. There is no support for p12 files.
  18. """
  19. from __future__ import absolute_import
  20. import io
  21. from pyasn1.codec.der import decoder # type: ignore
  22. from pyasn1_modules import pem # type: ignore
  23. from pyasn1_modules.rfc2459 import Certificate # type: ignore
  24. from pyasn1_modules.rfc5208 import PrivateKeyInfo # type: ignore
  25. import rsa # type: ignore
  26. from google.auth import _helpers
  27. from google.auth import exceptions
  28. from google.auth.crypt import base
  29. _POW2 = (128, 64, 32, 16, 8, 4, 2, 1)
  30. _CERTIFICATE_MARKER = b"-----BEGIN CERTIFICATE-----"
  31. _PKCS1_MARKER = ("-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----")
  32. _PKCS8_MARKER = ("-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----")
  33. _PKCS8_SPEC = PrivateKeyInfo()
  34. def _bit_list_to_bytes(bit_list):
  35. """Converts an iterable of 1s and 0s to bytes.
  36. Combines the list 8 at a time, treating each group of 8 bits
  37. as a single byte.
  38. Args:
  39. bit_list (Sequence): Sequence of 1s and 0s.
  40. Returns:
  41. bytes: The decoded bytes.
  42. """
  43. num_bits = len(bit_list)
  44. byte_vals = bytearray()
  45. for start in range(0, num_bits, 8):
  46. curr_bits = bit_list[start : start + 8]
  47. char_val = sum(val * digit for val, digit in zip(_POW2, curr_bits))
  48. byte_vals.append(char_val)
  49. return bytes(byte_vals)
  50. class RSAVerifier(base.Verifier):
  51. """Verifies RSA cryptographic signatures using public keys.
  52. Args:
  53. public_key (rsa.key.PublicKey): The public key used to verify
  54. signatures.
  55. """
  56. def __init__(self, public_key):
  57. self._pubkey = public_key
  58. @_helpers.copy_docstring(base.Verifier)
  59. def verify(self, message, signature):
  60. message = _helpers.to_bytes(message)
  61. try:
  62. return rsa.pkcs1.verify(message, signature, self._pubkey)
  63. except (ValueError, rsa.pkcs1.VerificationError):
  64. return False
  65. @classmethod
  66. def from_string(cls, public_key):
  67. """Construct an Verifier instance from a public key or public
  68. certificate string.
  69. Args:
  70. public_key (Union[str, bytes]): The public key in PEM format or the
  71. x509 public key certificate.
  72. Returns:
  73. google.auth.crypt._python_rsa.RSAVerifier: The constructed verifier.
  74. Raises:
  75. ValueError: If the public_key can't be parsed.
  76. """
  77. public_key = _helpers.to_bytes(public_key)
  78. is_x509_cert = _CERTIFICATE_MARKER in public_key
  79. # If this is a certificate, extract the public key info.
  80. if is_x509_cert:
  81. der = rsa.pem.load_pem(public_key, "CERTIFICATE")
  82. asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
  83. if remaining != b"":
  84. raise exceptions.InvalidValue("Unused bytes", remaining)
  85. cert_info = asn1_cert["tbsCertificate"]["subjectPublicKeyInfo"]
  86. key_bytes = _bit_list_to_bytes(cert_info["subjectPublicKey"])
  87. pubkey = rsa.PublicKey.load_pkcs1(key_bytes, "DER")
  88. else:
  89. pubkey = rsa.PublicKey.load_pkcs1(public_key, "PEM")
  90. return cls(pubkey)
  91. class RSASigner(base.Signer, base.FromServiceAccountMixin):
  92. """Signs messages with an RSA private key.
  93. Args:
  94. private_key (rsa.key.PrivateKey): The private key to sign with.
  95. key_id (str): Optional key ID used to identify this private key. This
  96. can be useful to associate the private key with its associated
  97. public key or certificate.
  98. """
  99. def __init__(self, private_key, key_id=None):
  100. self._key = private_key
  101. self._key_id = key_id
  102. @property # type: ignore
  103. @_helpers.copy_docstring(base.Signer)
  104. def key_id(self):
  105. return self._key_id
  106. @_helpers.copy_docstring(base.Signer)
  107. def sign(self, message):
  108. message = _helpers.to_bytes(message)
  109. return rsa.pkcs1.sign(message, self._key, "SHA-256")
  110. @classmethod
  111. def from_string(cls, key, key_id=None):
  112. """Construct an Signer instance from a private key in PEM format.
  113. Args:
  114. key (str): Private key in PEM format.
  115. key_id (str): An optional key id used to identify the private key.
  116. Returns:
  117. google.auth.crypt.Signer: The constructed signer.
  118. Raises:
  119. ValueError: If the key cannot be parsed as PKCS#1 or PKCS#8 in
  120. PEM format.
  121. """
  122. key = _helpers.from_bytes(key) # PEM expects str in Python 3
  123. marker_id, key_bytes = pem.readPemBlocksFromFile(
  124. io.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER
  125. )
  126. # Key is in pkcs1 format.
  127. if marker_id == 0:
  128. private_key = rsa.key.PrivateKey.load_pkcs1(key_bytes, format="DER")
  129. # Key is in pkcs8.
  130. elif marker_id == 1:
  131. key_info, remaining = decoder.decode(key_bytes, asn1Spec=_PKCS8_SPEC)
  132. if remaining != b"":
  133. raise exceptions.InvalidValue("Unused bytes", remaining)
  134. private_key_info = key_info.getComponentByName("privateKey")
  135. private_key = rsa.key.PrivateKey.load_pkcs1(
  136. private_key_info.asOctets(), format="DER"
  137. )
  138. else:
  139. raise exceptions.MalformedError("No key could be detected.")
  140. return cls(private_key, key_id=key_id)