RsaKem { static byte[] bigIntToByteArray(BigInteger bigInt, int size) { byte[] value = bigInt.toByteArray(); if (value.length == size) { return value; } byte[] result = new byte[size]; if (value.length == result.length + 1) { if (value[0] != 0) { throw new IllegalArgumentException( "Value is one-byte longer than the expected size, but its first byte is not 0"); } System.arraycopy(value, 1, result, 0, result.length); } else if (value.length < result.length) { System.arraycopy(value, 0, result, result.length - value.length, value.length); } else { throw new IllegalArgumentException( String.format( "Value has invalid length, must be of length at most (%d + 1), but" + " got %d", size, value.length)); } return result; } private  RsaKem();   }
@Test public void bigIntToByteArray_approximate() throws Exception { int expectedSize = 2048; BigInteger bigInt = new BigInteger(2048, new Random()); byte[] bigIntBytes = RsaKem.bigIntToByteArray(bigInt, expectedSize); assertThat(bigIntBytes).hasLength(expectedSize); assertThat(new BigInteger(1, bigIntBytes)).isEqualTo(bigInt); }
@Test public void bigIntToByteArray_withALeadingZero() throws Exception { int expectedSize = 2048; BigInteger bigIntWithALeadingZero; while (true) { bigIntWithALeadingZero = new BigInteger(2048, new Random()); byte[] r = bigIntWithALeadingZero.toByteArray(); if (r[0] == 0) { break; } } byte[] modBytes = RsaKem.bigIntToByteArray(bigIntWithALeadingZero, expectedSize); assertThat(modBytes).hasLength(expectedSize); assertThat(new BigInteger(1, modBytes)).isEqualTo(bigIntWithALeadingZero); }
@Test public void bigIntToByteArray_small() throws Exception { int expectedSize = 2048; BigInteger smallInt = BigInteger.valueOf(42L); byte[] smallIntBytes = RsaKem.bigIntToByteArray(smallInt, expectedSize); assertThat(smallIntBytes).hasLength(expectedSize); assertThat(new BigInteger(1, smallIntBytes)).isEqualTo(smallInt); }