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
15import os
16
17from google.auth import crypt
18
19
20DATA_DIR = os.path.join(os.path.dirname(__file__), "..", "data")
21
22# To generate privatekey.pem, privatekey.pub, and public_cert.pem:
23#   $ openssl req -new -newkey rsa:1024 -x509 -nodes -out public_cert.pem \
24#   >    -keyout privatekey.pem
25#   $ openssl rsa -in privatekey.pem -pubout -out privatekey.pub
26
27with open(os.path.join(DATA_DIR, "privatekey.pem"), "rb") as fh:
28    PRIVATE_KEY_BYTES = fh.read()
29
30with open(os.path.join(DATA_DIR, "public_cert.pem"), "rb") as fh:
31    PUBLIC_CERT_BYTES = fh.read()
32
33# To generate other_cert.pem:
34#   $ openssl req -new -newkey rsa:1024 -x509 -nodes -out other_cert.pem
35
36with open(os.path.join(DATA_DIR, "other_cert.pem"), "rb") as fh:
37    OTHER_CERT_BYTES = fh.read()
38
39
40def test_verify_signature():
41    to_sign = b"foo"
42    signer = crypt.RSASigner.from_string(PRIVATE_KEY_BYTES)
43    signature = signer.sign(to_sign)
44
45    assert crypt.verify_signature(to_sign, signature, PUBLIC_CERT_BYTES)
46
47    # List of certs
48    assert crypt.verify_signature(
49        to_sign, signature, [OTHER_CERT_BYTES, PUBLIC_CERT_BYTES]
50    )
51
52
53def test_verify_signature_failure():
54    to_sign = b"foo"
55    signer = crypt.RSASigner.from_string(PRIVATE_KEY_BYTES)
56    signature = signer.sign(to_sign)
57
58    assert not crypt.verify_signature(to_sign, signature, OTHER_CERT_BYTES)
59