Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/auth/crypt/_python_rsa.py: 43%
74 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:25 +0000
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:25 +0000
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.
15"""Pure-Python RSA cryptography implementation.
17Uses the ``rsa``, ``pyasn1`` and ``pyasn1_modules`` packages
18to parse PEM files storing PKCS#1 or PKCS#8 keys as well as
19certificates. There is no support for p12 files.
20"""
22from __future__ import absolute_import
24from pyasn1.codec.der import decoder # type: ignore
25from pyasn1_modules import pem # type: ignore
26from pyasn1_modules.rfc2459 import Certificate # type: ignore
27from pyasn1_modules.rfc5208 import PrivateKeyInfo # type: ignore
28import rsa # type: ignore
29import six
31from google.auth import _helpers
32from google.auth import exceptions
33from google.auth.crypt import base
35_POW2 = (128, 64, 32, 16, 8, 4, 2, 1)
36_CERTIFICATE_MARKER = b"-----BEGIN CERTIFICATE-----"
37_PKCS1_MARKER = ("-----BEGIN RSA PRIVATE KEY-----", "-----END RSA PRIVATE KEY-----")
38_PKCS8_MARKER = ("-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----")
39_PKCS8_SPEC = PrivateKeyInfo()
42def _bit_list_to_bytes(bit_list):
43 """Converts an iterable of 1s and 0s to bytes.
45 Combines the list 8 at a time, treating each group of 8 bits
46 as a single byte.
48 Args:
49 bit_list (Sequence): Sequence of 1s and 0s.
51 Returns:
52 bytes: The decoded bytes.
53 """
54 num_bits = len(bit_list)
55 byte_vals = bytearray()
56 for start in six.moves.xrange(0, num_bits, 8):
57 curr_bits = bit_list[start : start + 8]
58 char_val = sum(val * digit for val, digit in six.moves.zip(_POW2, curr_bits))
59 byte_vals.append(char_val)
60 return bytes(byte_vals)
63class RSAVerifier(base.Verifier):
64 """Verifies RSA cryptographic signatures using public keys.
66 Args:
67 public_key (rsa.key.PublicKey): The public key used to verify
68 signatures.
69 """
71 def __init__(self, public_key):
72 self._pubkey = public_key
74 @_helpers.copy_docstring(base.Verifier)
75 def verify(self, message, signature):
76 message = _helpers.to_bytes(message)
77 try:
78 return rsa.pkcs1.verify(message, signature, self._pubkey)
79 except (ValueError, rsa.pkcs1.VerificationError):
80 return False
82 @classmethod
83 def from_string(cls, public_key):
84 """Construct an Verifier instance from a public key or public
85 certificate string.
87 Args:
88 public_key (Union[str, bytes]): The public key in PEM format or the
89 x509 public key certificate.
91 Returns:
92 google.auth.crypt._python_rsa.RSAVerifier: The constructed verifier.
94 Raises:
95 ValueError: If the public_key can't be parsed.
96 """
97 public_key = _helpers.to_bytes(public_key)
98 is_x509_cert = _CERTIFICATE_MARKER in public_key
100 # If this is a certificate, extract the public key info.
101 if is_x509_cert:
102 der = rsa.pem.load_pem(public_key, "CERTIFICATE")
103 asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
104 if remaining != b"":
105 raise exceptions.InvalidValue("Unused bytes", remaining)
107 cert_info = asn1_cert["tbsCertificate"]["subjectPublicKeyInfo"]
108 key_bytes = _bit_list_to_bytes(cert_info["subjectPublicKey"])
109 pubkey = rsa.PublicKey.load_pkcs1(key_bytes, "DER")
110 else:
111 pubkey = rsa.PublicKey.load_pkcs1(public_key, "PEM")
112 return cls(pubkey)
115class RSASigner(base.Signer, base.FromServiceAccountMixin):
116 """Signs messages with an RSA private key.
118 Args:
119 private_key (rsa.key.PrivateKey): The private key to sign with.
120 key_id (str): Optional key ID used to identify this private key. This
121 can be useful to associate the private key with its associated
122 public key or certificate.
123 """
125 def __init__(self, private_key, key_id=None):
126 self._key = private_key
127 self._key_id = key_id
129 @property # type: ignore
130 @_helpers.copy_docstring(base.Signer)
131 def key_id(self):
132 return self._key_id
134 @_helpers.copy_docstring(base.Signer)
135 def sign(self, message):
136 message = _helpers.to_bytes(message)
137 return rsa.pkcs1.sign(message, self._key, "SHA-256")
139 @classmethod
140 def from_string(cls, key, key_id=None):
141 """Construct an Signer instance from a private key in PEM format.
143 Args:
144 key (str): Private key in PEM format.
145 key_id (str): An optional key id used to identify the private key.
147 Returns:
148 google.auth.crypt.Signer: The constructed signer.
150 Raises:
151 ValueError: If the key cannot be parsed as PKCS#1 or PKCS#8 in
152 PEM format.
153 """
154 key = _helpers.from_bytes(key) # PEM expects str in Python 3
155 marker_id, key_bytes = pem.readPemBlocksFromFile(
156 six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER
157 )
159 # Key is in pkcs1 format.
160 if marker_id == 0:
161 private_key = rsa.key.PrivateKey.load_pkcs1(key_bytes, format="DER")
162 # Key is in pkcs8.
163 elif marker_id == 1:
164 key_info, remaining = decoder.decode(key_bytes, asn1Spec=_PKCS8_SPEC)
165 if remaining != b"":
166 raise exceptions.InvalidValue("Unused bytes", remaining)
167 private_key_info = key_info.getComponentByName("privateKey")
168 private_key = rsa.key.PrivateKey.load_pkcs1(
169 private_key_info.asOctets(), format="DER"
170 )
171 else:
172 raise exceptions.MalformedError("No key could be detected.")
174 return cls(private_key, key_id=key_id)