blob: b9dd562daafc16dc8f9a393143be5140924f5e2a [file] [log] [blame]
"""
Unit tests for L{OpenSSL.crypto}.
"""
from unittest import TestCase
from OpenSSL.crypto import TYPE_RSA, TYPE_DSA, Error, PKey, PKeyType
class PKeyTests(TestCase):
"""
Unit tests for L{OpenSSL.crypto.PKey}.
"""
def test_construction(self):
"""
L{PKey} takes no arguments and returns a new L{PKeyType} instance.
"""
self.assertRaises(TypeError, PKey, None)
key = PKey()
self.assertTrue(
isinstance(key, PKeyType),
"%r is of type %r, should be %r" % (key, type(key), PKeyType))
def test_pregeneration(self):
"""
L{PKeyType.bits} and L{PKeyType.type} return C{0} before the key is
generated.
"""
key = PKey()
self.assertEqual(key.type(), 0)
self.assertEqual(key.bits(), 0)
def test_failedGeneration(self):
"""
L{PKeyType.generate_key} takes two arguments, the first giving the
key type as one of L{TYPE_RSA} or L{TYPE_DSA} and the second giving
the number of bits to generate. If an invalid type is specified or
generation fails, L{Error} is raised.
"""
key = PKey()
self.assertRaises(TypeError, key.generate_key)
self.assertRaises(TypeError, key.generate_key, 1, 2, 3)
self.assertRaises(TypeError, key.generate_key, "foo", "bar")
self.assertRaises(Error, key.generate_key, -1, 0)
self.assertRaises(Error, key.generate_key, TYPE_RSA, 0)
# XXX DSA generation seems happy with any number of bits. The DSS
# says bits must be between 512 and 1024 inclusive. OpenSSL's DSA
# generator doesn't seem to care about the upper limit at all. For
# the lower limit, it uses 512 if anything smaller is specified.
# So, it doesn't seem possible to make generate_key fail for
# TYPE_DSA with a bits argument which is at least an int.
# self.assertRaises(Error, key.generate_key, TYPE_DSA, -7)
def test_rsaGeneration(self):
"""
L{PKeyType.generate_key} generates an RSA key when passed
L{TYPE_RSA} as a type and a reasonable number of bits.
"""
bits = 128
key = PKey()
key.generate_key(TYPE_RSA, bits)
self.assertEqual(key.type(), TYPE_RSA)
self.assertEqual(key.bits(), bits)
def test_dsaGeneration(self):
"""
L{PKeyType.generate_key} generates a DSA key when passed
L{TYPE_DSA} as a type and a reasonable number of bits.
"""
# 512 is a magic number. The DSS (Digital Signature Standard)
# allows a minimum of 512 bits for DSA. DSA_generate_parameters
# will silently promote any value below 512 to 512.
bits = 512
key = PKey()
key.generate_key(TYPE_DSA, bits)
self.assertEqual(key.type(), TYPE_DSA)
self.assertEqual(key.bits(), bits)
def test_regeneration(self):
"""
L{PKeyType.generate_key} can be called multiple times on the same
key to generate new keys.
"""
key = PKey()
for type, bits in [(TYPE_RSA, 512), (TYPE_DSA, 576)]:
key.generate_key(type, bits)
self.assertEqual(key.type(), type)
self.assertEqual(key.bits(), bits)