1# Copyright 2011 Sybren A. Stüvel <[email protected]> 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# https://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 unittest 16import struct 17 18from rsa._compat import byte, xor_bytes 19 20 21class TestByte(unittest.TestCase): 22 """Tests for single bytes.""" 23 24 def test_byte(self): 25 for i in range(256): 26 byt = byte(i) 27 self.assertIsInstance(byt, bytes) 28 self.assertEqual(ord(byt), i) 29 30 def test_raises_StructError_on_overflow(self): 31 self.assertRaises(struct.error, byte, 256) 32 self.assertRaises(struct.error, byte, -1) 33 34 def test_byte_literal(self): 35 self.assertIsInstance(b'abc', bytes) 36 37 38class TestBytes(unittest.TestCase): 39 """Tests for bytes objects.""" 40 41 def setUp(self): 42 self.b1 = b'\xff\xff\xff\xff' 43 self.b2 = b'\x00\x00\x00\x00' 44 self.b3 = b'\xf0\xf0\xf0\xf0' 45 self.b4 = b'\x4d\x23\xca\xe2' 46 self.b5 = b'\x9b\x61\x3b\xdc' 47 self.b6 = b'\xff\xff' 48 49 self.byte_strings = (self.b1, self.b2, self.b3, self.b4, self.b5, self.b6) 50 51 def test_xor_bytes(self): 52 self.assertEqual(xor_bytes(self.b1, self.b2), b'\xff\xff\xff\xff') 53 self.assertEqual(xor_bytes(self.b1, self.b3), b'\x0f\x0f\x0f\x0f') 54 self.assertEqual(xor_bytes(self.b1, self.b4), b'\xb2\xdc\x35\x1d') 55 self.assertEqual(xor_bytes(self.b1, self.b5), b'\x64\x9e\xc4\x23') 56 self.assertEqual(xor_bytes(self.b2, self.b3), b'\xf0\xf0\xf0\xf0') 57 self.assertEqual(xor_bytes(self.b2, self.b4), b'\x4d\x23\xca\xe2') 58 self.assertEqual(xor_bytes(self.b2, self.b5), b'\x9b\x61\x3b\xdc') 59 self.assertEqual(xor_bytes(self.b3, self.b4), b'\xbd\xd3\x3a\x12') 60 self.assertEqual(xor_bytes(self.b3, self.b5), b'\x6b\x91\xcb\x2c') 61 self.assertEqual(xor_bytes(self.b4, self.b5), b'\xd6\x42\xf1\x3e') 62 63 def test_xor_bytes_length(self): 64 self.assertEqual(xor_bytes(self.b1, self.b6), b'\x00\x00') 65 self.assertEqual(xor_bytes(self.b2, self.b6), b'\xff\xff') 66 self.assertEqual(xor_bytes(self.b3, self.b6), b'\x0f\x0f') 67 self.assertEqual(xor_bytes(self.b4, self.b6), b'\xb2\xdc') 68 self.assertEqual(xor_bytes(self.b5, self.b6), b'\x64\x9e') 69 self.assertEqual(xor_bytes(self.b6, b''), b'') 70 71 def test_xor_bytes_commutative(self): 72 for first in self.byte_strings: 73 for second in self.byte_strings: 74 min_length = min(len(first), len(second)) 75 result = xor_bytes(first, second) 76 77 self.assertEqual(result, xor_bytes(second, first)) 78 self.assertEqual(len(result), min_length) 79