test_pkcs1.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # https://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Tests string operations."""
  17. import struct
  18. import sys
  19. import unittest
  20. import rsa
  21. from rsa import pkcs1
  22. from rsa._compat import byte, is_bytes
  23. class BinaryTest(unittest.TestCase):
  24. def setUp(self):
  25. (self.pub, self.priv) = rsa.newkeys(256)
  26. def test_enc_dec(self):
  27. message = struct.pack('>IIII', 0, 0, 0, 1)
  28. print("\tMessage: %r" % message)
  29. encrypted = pkcs1.encrypt(message, self.pub)
  30. print("\tEncrypted: %r" % encrypted)
  31. decrypted = pkcs1.decrypt(encrypted, self.priv)
  32. print("\tDecrypted: %r" % decrypted)
  33. self.assertEqual(message, decrypted)
  34. def test_decoding_failure(self):
  35. message = struct.pack('>IIII', 0, 0, 0, 1)
  36. encrypted = pkcs1.encrypt(message, self.pub)
  37. # Alter the encrypted stream
  38. a = encrypted[5]
  39. if is_bytes(a):
  40. a = ord(a)
  41. altered_a = (a + 1) % 256
  42. encrypted = encrypted[:5] + byte(altered_a) + encrypted[6:]
  43. self.assertRaises(pkcs1.DecryptionError, pkcs1.decrypt, encrypted,
  44. self.priv)
  45. def test_randomness(self):
  46. """Encrypting the same message twice should result in different
  47. cryptos.
  48. """
  49. message = struct.pack('>IIII', 0, 0, 0, 1)
  50. encrypted1 = pkcs1.encrypt(message, self.pub)
  51. encrypted2 = pkcs1.encrypt(message, self.pub)
  52. self.assertNotEqual(encrypted1, encrypted2)
  53. class ExtraZeroesTest(unittest.TestCase):
  54. def setUp(self):
  55. # Key, cyphertext, and plaintext taken from https://github.com/sybrenstuvel/python-rsa/issues/146
  56. self.private_key = rsa.PrivateKey.load_pkcs1(
  57. "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAs1EKK81M5kTFtZSuUFnhKy8FS2WNXaWVmi/fGHG4CLw98+Yo\n0nkuUarVwSS0O9pFPcpc3kvPKOe9Tv+6DLS3Qru21aATy2PRqjqJ4CYn71OYtSwM\n/ZfSCKvrjXybzgu+sBmobdtYm+sppbdL+GEHXGd8gdQw8DDCZSR6+dPJFAzLZTCd\nB+Ctwe/RXPF+ewVdfaOGjkZIzDoYDw7n+OHnsYCYozkbTOcWHpjVevipR+IBpGPi\n1rvKgFnlcG6d/tj0hWRl/6cS7RqhjoiNEtxqoJzpXs/Kg8xbCxXbCchkf11STA8u\ndiCjQWuWI8rcDwl69XMmHJjIQAqhKvOOQ8rYTQIDAQABAoIBABpQLQ7qbHtp4h1Y\nORAfcFRW7Q74UvtH/iEHH1TF8zyM6wZsYtcn4y0mxYE3Mp+J0xlTJbeVJkwZXYVH\nL3UH29CWHSlR+TWiazTwrCTRVJDhEoqbcTiRW8fb+o/jljVxMcVDrpyYUHNo2c6w\njBxhmKPtp66hhaDpds1Cwi0A8APZ8Z2W6kya/L/hRBzMgCz7Bon1nYBMak5PQEwV\nF0dF7Wy4vIjvCzO6DSqA415DvJDzUAUucgFudbANNXo4HJwNRnBpymYIh8mHdmNJ\n/MQ0YLSqUWvOB57dh7oWQwe3UsJ37ZUorTugvxh3NJ7Tt5ZqbCQBEECb9ND63gxo\n/a3YR/0CgYEA7BJc834xCi/0YmO5suBinWOQAF7IiRPU+3G9TdhWEkSYquupg9e6\nK9lC5k0iP+t6I69NYF7+6mvXDTmv6Z01o6oV50oXaHeAk74O3UqNCbLe9tybZ/+F\ndkYlwuGSNttMQBzjCiVy0+y0+Wm3rRnFIsAtd0RlZ24aN3bFTWJINIsCgYEAwnQq\nvNmJe9SwtnH5c/yCqPhKv1cF/4jdQZSGI6/p3KYNxlQzkHZ/6uvrU5V27ov6YbX8\nvKlKfO91oJFQxUD6lpTdgAStI3GMiJBJIZNpyZ9EWNSvwUj28H34cySpbZz3s4Xd\nhiJBShgy+fKURvBQwtWmQHZJ3EGrcOI7PcwiyYcCgYEAlql5jSUCY0ALtidzQogW\nJ+B87N+RGHsBuJ/0cxQYinwg+ySAAVbSyF1WZujfbO/5+YBN362A/1dn3lbswCnH\nK/bHF9+fZNqvwprPnceQj5oK1n4g6JSZNsy6GNAhosT+uwQ0misgR8SQE4W25dDG\nkdEYsz+BgCsyrCcu8J5C+tUCgYAFVPQbC4f2ikVyKzvgz0qx4WUDTBqRACq48p6e\n+eLatv7nskVbr7QgN+nS9+Uz80ihR0Ev1yCAvnwmM/XYAskcOea87OPmdeWZlQM8\nVXNwINrZ6LMNBLgorfuTBK1UoRo1pPUHCYdqxbEYI2unak18mikd2WB7Fp3h0YI4\nVpGZnwKBgBxkAYnZv+jGI4MyEKdsQgxvROXXYOJZkWzsKuKxVkVpYP2V4nR2YMOJ\nViJQ8FUEnPq35cMDlUk4SnoqrrHIJNOvcJSCqM+bWHAioAsfByLbUPM8sm3CDdIk\nXVJl32HuKYPJOMIWfc7hIfxLRHnCN+coz2M6tgqMDs0E/OfjuqVZ\n-----END RSA PRIVATE KEY-----",
  58. format='PEM')
  59. cyphertext = "4501b4d669e01b9ef2dc800aa1b06d49196f5a09fe8fbcd037323c60eaf027bfb98432be4e4a26c567ffec718bcbea977dd26812fa071c33808b4d5ebb742d9879806094b6fbeea63d25ea3141733b60e31c6912106e1b758a7fe0014f075193faa8b4622bfd5d3013f0a32190a95de61a3604711bc62945f95a6522bd4dfed0a994ef185b28c281f7b5e4c8ed41176d12d9fc1b837e6a0111d0132d08a6d6f0580de0c9eed8ed105531799482d1e466c68c23b0c222af7fc12ac279bc4ff57e7b4586d209371b38c4c1035edd418dc5f960441cb21ea2bedbfea86de0d7861e81021b650a1de51002c315f1e7c12debe4dcebf790caaa54a2f26b149cf9e77d"
  60. plaintext = "54657374"
  61. if sys.version_info < (3, 0):
  62. self.cyphertext = cyphertext.decode("hex")
  63. self.plaintext = plaintext.decode('hex')
  64. else:
  65. self.cyphertext = bytes.fromhex(cyphertext)
  66. self.plaintext = bytes.fromhex(plaintext)
  67. def test_unmodified(self):
  68. message = rsa.decrypt(self.cyphertext, self.private_key)
  69. self.assertEqual(message, self.plaintext)
  70. def test_prepend_zeroes(self):
  71. cyphertext = b'\00\00' + self.cyphertext
  72. with self.assertRaises(rsa.DecryptionError):
  73. rsa.decrypt(cyphertext, self.private_key)
  74. def test_append_zeroes(self):
  75. cyphertext = self.cyphertext + b'\00\00'
  76. with self.assertRaises(rsa.DecryptionError):
  77. rsa.decrypt(cyphertext, self.private_key)
  78. class SignatureTest(unittest.TestCase):
  79. def setUp(self):
  80. (self.pub, self.priv) = rsa.newkeys(512)
  81. def test_sign_verify(self):
  82. """Test happy flow of sign and verify"""
  83. message = b'je moeder'
  84. signature = pkcs1.sign(message, self.priv, 'SHA-256')
  85. self.assertEqual('SHA-256', pkcs1.verify(message, signature, self.pub))
  86. def test_find_signature_hash(self):
  87. """Test happy flow of sign and find_signature_hash"""
  88. message = b'je moeder'
  89. signature = pkcs1.sign(message, self.priv, 'SHA-256')
  90. self.assertEqual('SHA-256', pkcs1.find_signature_hash(signature, self.pub))
  91. def test_alter_message(self):
  92. """Altering the message should let the verification fail."""
  93. signature = pkcs1.sign(b'je moeder', self.priv, 'SHA-256')
  94. self.assertRaises(pkcs1.VerificationError, pkcs1.verify,
  95. b'mijn moeder', signature, self.pub)
  96. def test_sign_different_key(self):
  97. """Signing with another key should let the verification fail."""
  98. (otherpub, _) = rsa.newkeys(512)
  99. message = b'je moeder'
  100. signature = pkcs1.sign(message, self.priv, 'SHA-256')
  101. self.assertRaises(pkcs1.VerificationError, pkcs1.verify,
  102. message, signature, otherpub)
  103. def test_multiple_signings(self):
  104. """Signing the same message twice should return the same signatures."""
  105. message = struct.pack('>IIII', 0, 0, 0, 1)
  106. signature1 = pkcs1.sign(message, self.priv, 'SHA-1')
  107. signature2 = pkcs1.sign(message, self.priv, 'SHA-1')
  108. self.assertEqual(signature1, signature2)
  109. def test_split_hash_sign(self):
  110. """Hashing and then signing should match with directly signing the message. """
  111. message = b'je moeder'
  112. msg_hash = pkcs1.compute_hash(message, 'SHA-256')
  113. signature1 = pkcs1.sign_hash(msg_hash, self.priv, 'SHA-256')
  114. # Calculate the signature using the unified method
  115. signature2 = pkcs1.sign(message, self.priv, 'SHA-256')
  116. self.assertEqual(signature1, signature2)
  117. def test_hash_sign_verify(self):
  118. """Test happy flow of hash, sign, and verify"""
  119. message = b'je moeder'
  120. msg_hash = pkcs1.compute_hash(message, 'SHA-224')
  121. signature = pkcs1.sign_hash(msg_hash, self.priv, 'SHA-224')
  122. self.assertTrue(pkcs1.verify(message, signature, self.pub))
  123. def test_prepend_zeroes(self):
  124. """Prepending the signature with zeroes should be detected."""
  125. message = b'je moeder'
  126. signature = pkcs1.sign(message, self.priv, 'SHA-256')
  127. signature = b'\00\00' + signature
  128. with self.assertRaises(rsa.VerificationError):
  129. pkcs1.verify(message, signature, self.pub)
  130. def test_apppend_zeroes(self):
  131. """Apppending the signature with zeroes should be detected."""
  132. message = b'je moeder'
  133. signature = pkcs1.sign(message, self.priv, 'SHA-256')
  134. signature = signature + b'\00\00'
  135. with self.assertRaises(rsa.VerificationError):
  136. pkcs1.verify(message, signature, self.pub)