import java.util.Random; import org.junit.*; public class TinyCipherTests { private static final String SECRET = "secret"; @Test public void testSimpleRoundtrip() { exhaustivelyCheckRoundtrip(8); } /** * Thanks are due to Dmitry Kichinsky for pointing out this bug. */ @Test public void testOddBlockSizeRoundtrip() { exhaustivelyCheckRoundtrip(9); } private void exhaustivelyCheckRoundtrip(int bits) { TinyCipher c = newTinyCipher(bits); for (int plaintext = 0; plaintext < (1 << bits); ++plaintext) { checkRoundtrip(c, plaintext); } } @Test public void testFullWidthBlockSizeRoundtrip() { sparselyCheckRoundtrip(32); } private void sparselyCheckRoundtrip(int bits) { TinyCipher c = newTinyCipher(bits); Random rnd = new Random(SECRET.hashCode()); int mask = (int)((1L << bits) - 1); for (int i = 0; i < 100000; ++i) { int plaintext = rnd.nextInt() & mask; checkRoundtrip(c, plaintext); } } private TinyCipher newTinyCipher(int bits) { return new TinyCipher(bits, SECRET.getBytes()); } private void checkRoundtrip(TinyCipher c, int plaintext) { int ciphertext = c.encrypt(plaintext); int recoveredPlaintext = c.decrypt(ciphertext); Assert.assertEquals(plaintext, recoveredPlaintext); } }