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