blob: 4dda78bf2b381893e439ca32f75f5bc834baeeb6 [file] [log] [blame]
James E. Blairbf1a4f22017-03-17 10:59:37 -07001# Copyright 2017 Red Hat, Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may
4# not use this file except in compliance with the License. You may obtain
5# 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, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14
15import os
16import subprocess
17import tempfile
18
19from zuul.lib import encryption
20
21from tests.base import BaseTestCase
22
23
24class TestEncryption(BaseTestCase):
25
26 def setUp(self):
27 super(TestEncryption, self).setUp()
28 self.private, self.public = encryption.generate_rsa_keypair()
29
30 def test_serialization(self):
31 "Verify key serialization"
32 pem_private = encryption.serialize_rsa_private_key(self.private)
33 private2, public2 = encryption.deserialize_rsa_keypair(pem_private)
34
35 # cryptography public / private key objects don't implement
36 # equality testing, so we make sure they have the same numbers.
37 self.assertEqual(self.private.private_numbers(),
38 private2.private_numbers())
39 self.assertEqual(self.public.public_numbers(),
40 public2.public_numbers())
41
James E. Blair717e8e92017-03-17 11:03:27 -070042 def test_pkcs1_oaep(self):
James E. Blairbf1a4f22017-03-17 10:59:37 -070043 "Verify encryption and decryption"
44 orig_plaintext = "some text to encrypt"
James E. Blair717e8e92017-03-17 11:03:27 -070045 ciphertext = encryption.encrypt_pkcs1_oaep(orig_plaintext, self.public)
46 plaintext = encryption.decrypt_pkcs1_oaep(ciphertext, self.private)
James E. Blairbf1a4f22017-03-17 10:59:37 -070047 self.assertEqual(orig_plaintext, plaintext)
48
James E. Blair717e8e92017-03-17 11:03:27 -070049 def test_openssl_pkcs1_oaep(self):
James E. Blairbf1a4f22017-03-17 10:59:37 -070050 "Verify that we can decrypt something encrypted with OpenSSL"
51 orig_plaintext = "some text to encrypt"
52 pem_public = encryption.serialize_rsa_public_key(self.public)
53 public_file = tempfile.NamedTemporaryFile(delete=False)
54 try:
55 public_file.write(pem_public)
56 public_file.close()
57
58 p = subprocess.Popen(['openssl', 'rsautl', '-encrypt',
59 '-oaep', '-pubin', '-inkey',
60 public_file.name],
61 stdin=subprocess.PIPE,
62 stdout=subprocess.PIPE)
63 (stdout, stderr) = p.communicate(orig_plaintext)
64 ciphertext = stdout
65 finally:
66 os.unlink(public_file.name)
67
James E. Blair717e8e92017-03-17 11:03:27 -070068 plaintext = encryption.decrypt_pkcs1_oaep(ciphertext, self.private)
James E. Blairbf1a4f22017-03-17 10:59:37 -070069 self.assertEqual(orig_plaintext, plaintext)