1# Copyright 2017 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
15"""
16RSA cryptography signer and verifier.
17
18This file provides a shared wrapper, that defers to _python_rsa or _cryptography_rsa
19for implmentations using different third party libraries
20"""
21
22from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey
23
24from google.auth import _helpers
25from google.auth.crypt import _cryptography_rsa, base
26
27RSA_KEY_MODULE_PREFIX = "rsa.key"
28
29
30class RSAVerifier(base.Verifier):
31 """Verifies RSA cryptographic signatures using public keys.
32
33 Args:
34 public_key (Union["rsa.key.PublicKey", cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey]):
35 The public key used to verify signatures.
36 Raises:
37 ImportError: if called with an rsa.key.PublicKey, when the rsa library is not installed
38 ValueError: if an unrecognized public key is provided
39 """
40
41 def __init__(self, public_key):
42 module_str = public_key.__class__.__module__
43 if isinstance(public_key, RSAPublicKey):
44 impl_lib = _cryptography_rsa
45 elif module_str.startswith(RSA_KEY_MODULE_PREFIX):
46 from google.auth.crypt import _python_rsa
47
48 impl_lib = _python_rsa
49 else:
50 raise ValueError(f"unrecognized public key type: {type(public_key)}")
51 self._impl = impl_lib.RSAVerifier(public_key)
52
53 @_helpers.copy_docstring(base.Verifier)
54 def verify(self, message, signature):
55 return self._impl.verify(message, signature)
56
57 @classmethod
58 def from_string(cls, public_key):
59 """Construct a Verifier instance from a public key or public
60 certificate string.
61
62 Args:
63 public_key (Union[str, bytes]): The public key in PEM format or the
64 x509 public key certificate.
65
66 Returns:
67 google.auth.crypt.Verifier: The constructed verifier.
68
69 Raises:
70 ValueError: If the public_key can't be parsed.
71 """
72 instance = cls.__new__(cls)
73 instance._impl = _cryptography_rsa.RSAVerifier.from_string(public_key)
74 return instance
75
76
77class RSASigner(base.Signer, base.FromServiceAccountMixin):
78 """Signs messages with an RSA private key.
79
80 Args:
81 private_key (Union["rsa.key.PrivateKey", cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey]):
82 The private key to sign with.
83 key_id (str): Optional key ID used to identify this private key. This
84 can be useful to associate the private key with its associated
85 public key or certificate.
86
87 Raises:
88 ImportError: if called with an rsa.key.PrivateKey, when the rsa library is not installed
89 ValueError: if an unrecognized public key is provided
90 """
91
92 def __init__(self, private_key, key_id=None):
93 module_str = private_key.__class__.__module__
94 if isinstance(private_key, RSAPrivateKey):
95 impl_lib = _cryptography_rsa
96 elif module_str.startswith(RSA_KEY_MODULE_PREFIX):
97 from google.auth.crypt import _python_rsa
98
99 impl_lib = _python_rsa
100 else:
101 raise ValueError(f"unrecognized private key type: {type(private_key)}")
102 self._impl = impl_lib.RSASigner(private_key, key_id=key_id)
103
104 @property # type: ignore
105 @_helpers.copy_docstring(base.Signer)
106 def key_id(self):
107 return self._impl.key_id
108
109 @_helpers.copy_docstring(base.Signer)
110 def sign(self, message):
111 return self._impl.sign(message)
112
113 @classmethod
114 def from_string(cls, key, key_id=None):
115 """Construct a Signer instance from a private key in PEM format.
116
117 Args:
118 key (str): Private key in PEM format.
119 key_id (str): An optional key id used to identify the private key.
120
121 Returns:
122 google.auth.crypt.Signer: The constructed signer.
123
124 Raises:
125 ValueError: If the key cannot be parsed as PKCS#1 or PKCS#8 in
126 PEM format.
127 """
128 instance = cls.__new__(cls)
129 instance._impl = _cryptography_rsa.RSASigner.from_string(key, key_id=key_id)
130 return instance