def verify(self, message, signature): # First convert (r||s) raw signature to ASN1 encoded signature. sig_bytes = _helpers.to_bytes(signature) if len(sig_bytes) != 64: return False r = int.from_bytes(sig_bytes[:32], byteorder="big") s = int.from_bytes(sig_bytes[32:], byteorder="big") asn1_sig = encode_dss_signature(r, s) message = _helpers.to_bytes(message) try: self._pubkey.verify(asn1_sig, message, ec.ECDSA(hashes.SHA256())) return True except (ValueError, cryptography.exceptions.InvalidSignature): return False
def _unverified_decode(token): """Decodes a token and does no verification. Args: token (Union[str, bytes]): The encoded JWT. Returns: Tuple[str, str, str, str]: header, payload, signed_section, and signature. Raises: ValueError: if there are an incorrect amount of segments in the token. """ token = _helpers.to_bytes(token) if token.count(b'.') != 2: raise ValueError( 'Wrong number of segments in token: {0}'.format(token)) encoded_header, encoded_payload, signature = token.split(b'.') signed_section = encoded_header + b'.' + encoded_payload signature = _helpers.padded_urlsafe_b64decode(signature) # Parse segments header = _decode_jwt_segment(encoded_header) payload = _decode_jwt_segment(encoded_payload) return header, payload, signed_section, signature
def set_response(data, status=http_client.OK, headers=None): response = mock.Mock() response.status = status response.data = _helpers.to_bytes(data) response.headers = headers or {} request_mock.return_value = response return request_mock
def from_string(cls, public_key): """Construct an Verifier instance from a public key or public certificate string. Args: public_key (Union[str, bytes]): The public key in PEM format or the x509 public key certificate. Returns: Verifier: The constructed verifier. Raises: ValueError: If the public_key can't be parsed. """ public_key = _helpers.to_bytes(public_key) is_x509_cert = _CERTIFICATE_MARKER in public_key # If this is a certificate, extract the public key info. if is_x509_cert: der = rsa.pem.load_pem(public_key, "CERTIFICATE") asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate()) if remaining != b"": raise ValueError("Unused bytes", remaining) cert_info = asn1_cert["tbsCertificate"]["subjectPublicKeyInfo"] key_bytes = _bit_list_to_bytes(cert_info["subjectPublicKey"]) pubkey = rsa.PublicKey.load_pkcs1(key_bytes, "DER") else: pubkey = rsa.PublicKey.load_pkcs1(public_key, "PEM") return cls(pubkey)
def from_string(cls, public_key): """Construct an Verifier instance from a public key or public certificate string. Args: public_key (Union[str, bytes]): The public key in PEM format or the x509 public key certificate. Returns: Verifier: The constructed verifier. Raises: ValueError: If the public_key can't be parsed. """ public_key = _helpers.to_bytes(public_key) is_x509_cert = _CERTIFICATE_MARKER in public_key # If this is a certificate, extract the public key info. if is_x509_cert: der = rsa.pem.load_pem(public_key, 'CERTIFICATE') asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate()) if remaining != b'': raise ValueError('Unused bytes', remaining) cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo'] key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey']) pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER') else: pubkey = rsa.PublicKey.load_pkcs1(public_key, 'PEM') return cls(pubkey)
def verify(self, message, signature): message = _helpers.to_bytes(message) try: self._pubkey.verify(signature, message, _PADDING, _SHA256) return True except (ValueError, cryptography.exceptions.InvalidSignature): return False
def verify(self, message, signature): message = _helpers.to_bytes(message) try: self._pubkey.verify(signature, message, ec.ECDSA(hashes.SHA256())) return True except (ValueError, cryptography.exceptions.InvalidSignature): return False
def sign(self, message): message = _helpers.to_bytes(message) from google.auth.crypt import _cryptography_rsa # pylint: disable=g-import-not-at-top return self._key.sign( message, _cryptography_rsa._PADDING, # pylint: disable=protected-access _cryptography_rsa._SHA256) # pylint: disable=protected-access
def from_string(cls, public_key): """Construct an Verifier instance from a public key or public certificate string. Args: public_key (Union[str, bytes]): The public key in PEM format or the x509 public key certificate. Returns: Verifier: The constructed verifier. Raises: ValueError: If the public key can't be parsed. """ public_key_data = _helpers.to_bytes(public_key) if _CERTIFICATE_MARKER in public_key_data: cert = cryptography.x509.load_pem_x509_certificate( public_key_data, _BACKEND ) pubkey = cert.public_key() else: pubkey = serialization.load_pem_public_key(public_key_data, _BACKEND) return cls(pubkey)
def sign(self, message): message = _helpers.to_bytes(message) asn1_signature = self._key.sign(message, ec.ECDSA(hashes.SHA256())) # Convert ASN1 encoded signature to (r||s) raw signature. (r, s) = decode_dss_signature(asn1_signature) return utils.int_to_bytes(r, 32) + utils.int_to_bytes(s, 32)
def from_string(cls, public_key): """Construct an Verifier instance from a public key or public certificate string. Args: public_key (Union[str, bytes]): The public key in PEM format or the x509 public key certificate. Returns: Verifier: The constructed verifier. Raises: ValueError: If the public key can't be parsed. """ public_key_data = _helpers.to_bytes(public_key) if _CERTIFICATE_MARKER in public_key_data: cert = cryptography.x509.load_pem_x509_certificate( public_key_data, _BACKEND) pubkey = cert.public_key() else: pubkey = serialization.load_pem_public_key( public_key_data, _BACKEND) return cls(pubkey)
def sign(self, message): message = _helpers.to_bytes(message) asn1_signature = self._key.sign(message, ec.ECDSA(hashes.SHA256())) # Convert ASN1 encoded signature to (r||s) raw signature. (r, s) = decode_dss_signature(asn1_signature) return r.to_bytes(32, byteorder="big") + s.to_bytes(32, byteorder="big")
def from_string(cls, key_strings, key_id=None): del key_id key_string, password = (_helpers.to_bytes(k) for k in key_strings) from cryptography.hazmat.primitives.serialization import pkcs12 # pylint: disable=g-import-not-at-top from cryptography.hazmat import backends # pylint: disable=g-import-not-at-top key, _, _ = pkcs12.load_key_and_certificates( key_string, password, backend=backends.default_backend()) return cls(key)
def sign(self, message): message = _helpers.to_bytes(message) asn1_signature = self._key.sign(message, ec.ECDSA(hashes.SHA256())) # Convert ASN1 encoded signature to (r||s) raw signature. (r, s) = decode_dss_signature(asn1_signature) return ((r.to_bytes(32, byteorder="big") + s.to_bytes(32, byteorder="big")) if _helpers.is_python_3() else (utils.int_to_bytes(r, 32) + utils.int_to_bytes(s, 32)))
def make_request(data, status=http_client.OK, headers=None): response = mock.create_autospec(transport.Response, instance=True) response.status = status response.data = _helpers.to_bytes(data) response.headers = headers or {} request = mock.create_autospec(transport.Request) request.return_value = response return request
def make_request(self, data, status=http_client.OK, headers=None, side_effect=None): response = mock.create_autospec(transport.Response, instance=False) response.status = status response.data = _helpers.to_bytes(data) response.headers = headers or {} request = mock.create_autospec(transport.Request, instance=False) request.side_effect = side_effect request.return_value = response return request
def sign(self, message): """Signs a message. Args: message (Union[str, bytes]): The message to be signed. Returns: bytes: The signature of the message for the given key. """ message = _helpers.to_bytes(message) return rsa.pkcs1.sign(message, self._key, 'SHA-256')
def sign(message): """Signs a message. Args: message (Union[str, bytes]): The message to be signed. Returns: bytes: The signature of the message. """ message = _helpers.to_bytes(message) return app_identity.sign_blob(message)
def make_request(data, status=http_client.OK, headers=None, retry=False): response = mock.create_autospec(transport.Response, instance=True) response.status = status response.data = _helpers.to_bytes(data) response.headers = headers or {} request = mock.create_autospec(transport.Request) if retry: request.side_effect = [exceptions.TransportError(), response] else: request.return_value = response return request
def verify(self, message, signature): """Verifies a message against a cryptographic signature. Args: message (Union[str, bytes]): The message to verify. signature (Union[str, bytes]): The cryptography signature to check. Returns: bool: True if message was signed by the private key associated with the public key that this object was constructed with. """ message = _helpers.to_bytes(message) try: return rsa.pkcs1.verify(message, signature, self._pubkey) except (ValueError, rsa.pkcs1.VerificationError): return False
def _make_signing_request(self, message): """Makes a request to the API signBlob API.""" message = _helpers.to_bytes(message) method = "POST" url = _SIGN_BLOB_URI.format(self._service_account_email) headers = {} body = json.dumps({"bytesToSign": base64.b64encode(message).decode("utf-8")}) self._credentials.before_request(self._request, method, url, headers) response = self._request(url=url, method=method, body=body, headers=headers) if response.status != http_client.OK: raise exceptions.TransportError( "Error calling the IAM signBytes API: {}".format(response.data) ) return json.loads(response.data.decode("utf-8"))
def from_string(cls, key, key_id=None): """Construct a RSASigner from a private key in PEM format. Args: key (Union[bytes, str]): Private key in PEM format. key_id (str): An optional key id used to identify the private key. Returns: google.auth.crypt._cryptography_rsa.RSASigner: The constructed signer. Raises: ValueError: If ``key`` is not ``bytes`` or ``str`` (unicode). UnicodeDecodeError: If ``key`` is ``bytes`` but cannot be decoded into a UTF-8 ``str``. ValueError: If ``cryptography`` "Could not deserialize key data." """ key = _helpers.to_bytes(key) private_key = serialization.load_pem_private_key( key, password=None, backend=_BACKEND) return cls(private_key, key_id=key_id)
def _make_signing_request(self, message): """Makes a request to the API signBlob API.""" message = _helpers.to_bytes(message) method = 'POST' url = _SIGN_BLOB_URI.format(self._service_account_email) headers = {} body = json.dumps({ 'bytesToSign': base64.b64encode(message).decode('utf-8'), }) self._credentials.before_request(self._request, method, url, headers) response = self._request( url=url, method=method, body=body, headers=headers) if response.status != http_client.OK: raise exceptions.TransportError( 'Error calling the IAM signBytes API: {}'.format( response.data)) return json.loads(response.data.decode('utf-8'))
def test_sign_bytes(self, mock_donor_credentials, mock_authorizedsession_sign): credentials = self.make_credentials(lifetime=None) token = "token" expire_time = ( _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500) ).isoformat("T") + "Z" token_response_body = {"accessToken": token, "expireTime": expire_time} response = mock.create_autospec(transport.Response, instance=False) response.status = http_client.OK response.data = _helpers.to_bytes(json.dumps(token_response_body)) request = mock.create_autospec(transport.Request, instance=False) request.return_value = response credentials.refresh(request) assert credentials.valid assert not credentials.expired signature = credentials.sign_bytes(b"signed bytes") assert signature == b"signature"
def verify(self, message, signature): message = _helpers.to_bytes(message) try: return rsa.pkcs1.verify(message, signature, self._pubkey) except (ValueError, rsa.pkcs1.VerificationError): return False
def test_to_bytes_with_bytes(): value = b'bytes-val' assert _helpers.to_bytes(value) == value
def test_to_bytes_with_unicode(): value = u'string-val' encoded_value = b'string-val' assert _helpers.to_bytes(value) == encoded_value
def sign(self, message): message = _helpers.to_bytes(message) return self._key.sign(message, ec.ECDSA(hashes.SHA256()))
def sign(self, message): message = _helpers.to_bytes(message) return self._key.sign( message, _PADDING, _SHA256)
def test_to_bytes_with_nonstring_type(): with pytest.raises(ValueError): _helpers.to_bytes(object())
def sign(self, message): message = _helpers.to_bytes(message) return self._key.sign(message, _PADDING, _SHA256)
def sign(self, message): message = _helpers.to_bytes(message) return rsa.pkcs1.sign(message, self._key, 'SHA-256')
def sign(self, message): message = _helpers.to_bytes(message) return rsa.pkcs1.sign(message, self._key, "SHA-256")
def sign(self, message): message = _helpers.to_bytes(message) return crypto.sign(self._key, message, u'sha256')
def sign(self, message): message = _helpers.to_bytes(message) _, signature = app_identity.sign_blob(message) return signature