SecurityTokenUtils { static void writeBits(ByteArrayOutputStream stream, BigInteger value, int width) { if (value.signum() == -1) { throw new IllegalArgumentException("value is negative"); } else if (width <= 0) { throw new IllegalArgumentException("width <= 0"); } final byte[] prime = value.toByteArray(); int skip = 0; while ((skip < prime.length) && (prime[skip] == 0)) ++skip; if ((prime.length - skip) > width) { throw new IllegalArgumentException("not enough width to fit value: " + (prime.length - skip) + "/" + width); } byte[] res = new byte[width]; System.arraycopy(prime, skip, res, width - (prime.length - skip), prime.length - skip); stream.write(res, 0, width); Arrays.fill(res, (byte) 0); Arrays.fill(prime, (byte) 0); }  static byte[] attributesFromSecretKey(KeyType slot, CanonicalizedSecretKey secretKey,
            KeyFormat formatForKeyType); static byte[] createRSAPrivKeyTemplate(RSAPrivateCrtKey secretKey, KeyType slot,
            RSAKeyFormat format); static byte[] createECPrivKeyTemplate(ECPrivateKey secretKey, ECPublicKey publicKey, KeyType slot,
            ECKeyFormat format);  }
@Test public void testWriteBits() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); SecurityTokenUtils.writeBits(stream, new BigInteger("0"), 10); Assert.assertArrayEquals(new byte[10], stream.toByteArray()); stream.reset(); SecurityTokenUtils.writeBits(stream, new BigInteger("0"), 1); Assert.assertArrayEquals(new byte[1], stream.toByteArray()); stream.reset(); SecurityTokenUtils.writeBits(stream, new BigInteger("65537"), 3); Assert.assertArrayEquals(new byte[]{1, 0, 1}, stream.toByteArray()); stream.reset(); SecurityTokenUtils.writeBits(stream, new BigInteger("128"), 1); Assert.assertArrayEquals(new byte[]{(byte) 128}, stream.toByteArray()); stream.reset(); SecurityTokenUtils.writeBits(stream, new BigInteger("65537"), 4); Assert.assertArrayEquals(new byte[]{0, 1, 0, 1}, stream.toByteArray()); stream.reset(); SecurityTokenUtils.writeBits(stream, new BigInteger("65537"), 11); Assert.assertArrayEquals(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1}, stream.toByteArray()); }
@Test(expected = IllegalArgumentException.class) public void testWriteBitsInvalidValue() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); SecurityTokenUtils.writeBits(stream, new BigInteger("-1"), 1); }
@Test(expected = IllegalArgumentException.class) public void testWriteBitsInvalidBits() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); SecurityTokenUtils.writeBits(stream, new BigInteger("1"), 0); }
@Test(expected = IllegalArgumentException.class) public void testWriteBitsDoesntFit() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); SecurityTokenUtils.writeBits(stream, new BigInteger("65537"), 2); }