1# Copyright 2015 Google Inc. All rights reserved. 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"""Unit tests for oauth2client._pycrypto_crypt.""" 15 16import os 17 18import unittest2 19 20from oauth2client import crypt 21 22 23class TestPyCryptoVerifier(unittest2.TestCase): 24 25 PUBLIC_CERT_FILENAME = os.path.join(os.path.dirname(__file__), 26 'data', 'public_cert.pem') 27 PRIVATE_KEY_FILENAME = os.path.join(os.path.dirname(__file__), 28 'data', 'privatekey.pem') 29 30 def _load_public_cert_bytes(self): 31 with open(self.PUBLIC_CERT_FILENAME, 'rb') as fh: 32 return fh.read() 33 34 def _load_private_key_bytes(self): 35 with open(self.PRIVATE_KEY_FILENAME, 'rb') as fh: 36 return fh.read() 37 38 def test_verify_success(self): 39 to_sign = b'foo' 40 signer = crypt.PyCryptoSigner.from_string( 41 self._load_private_key_bytes()) 42 actual_signature = signer.sign(to_sign) 43 44 verifier = crypt.PyCryptoVerifier.from_string( 45 self._load_public_cert_bytes(), is_x509_cert=True) 46 self.assertTrue(verifier.verify(to_sign, actual_signature)) 47 48 def test_verify_failure(self): 49 verifier = crypt.PyCryptoVerifier.from_string( 50 self._load_public_cert_bytes(), is_x509_cert=True) 51 bad_signature = b'' 52 self.assertFalse(verifier.verify(b'foo', bad_signature)) 53 54 def test_verify_bad_key(self): 55 verifier = crypt.PyCryptoVerifier.from_string( 56 self._load_public_cert_bytes(), is_x509_cert=True) 57 bad_signature = b'' 58 self.assertFalse(verifier.verify(b'foo', bad_signature)) 59 60 def test_from_string_unicode_key(self): 61 public_key = self._load_public_cert_bytes() 62 public_key = public_key.decode('utf-8') 63 verifier = crypt.PyCryptoVerifier.from_string( 64 public_key, is_x509_cert=True) 65 self.assertIsInstance(verifier, crypt.PyCryptoVerifier) 66 67 68class TestPyCryptoSigner(unittest2.TestCase): 69 70 def test_from_string_bad_key(self): 71 key_bytes = 'definitely-not-pem-format' 72 with self.assertRaises(NotImplementedError): 73 crypt.PyCryptoSigner.from_string(key_bytes) 74