@Test
public void testEncryptDecryptWithInvalidRecordSizes() throws Exception {

  KeyPair uaKeyPair = EllipticCurves.generateKeyPair(WebPushConstants.NIST_P256_CURVE_TYPE);
  ECPrivateKey uaPrivateKey = (ECPrivateKey) uaKeyPair.getPrivate();
  ECPublicKey uaPublicKey = (ECPublicKey) uaKeyPair.getPublic();
  byte[] authSecret = Random.randBytes(16);
  // Test with out of range record sizes.
  {
    try {
      new WebPushHybridDecrypt.Builder()
          .withRecordSize(WebPushConstants.MAX_CIPHERTEXT_SIZE + 1)
          .withAuthSecret(authSecret)
          .withRecipientPublicKey(uaPublicKey)
          .withRecipientPrivateKey(uaPrivateKey)
          .build();
      fail("Expected IllegalArgumentException");
    } catch (IllegalArgumentException ex) {
      // expected.
    }
    try {
      new WebPushHybridDecrypt.Builder()
          .withRecordSize(WebPushConstants.CIPHERTEXT_OVERHEAD - 1)
          .withAuthSecret(authSecret)
          .withRecipientPublicKey(uaPublicKey)
          .withRecipientPrivateKey(uaPrivateKey)
          .build();
    } catch (IllegalArgumentException ex) {
      // expected.
    }
  }
  // Test with random mismatched record size.
  {
    for (int i = 0; i < 50; i++) {
      int recordSize =
          WebPushConstants.CIPHERTEXT_OVERHEAD
              + Random.randInt(
                  WebPushConstants.MAX_CIPHERTEXT_SIZE
                      - WebPushConstants.CIPHERTEXT_OVERHEAD
                      - 1);
      HybridEncrypt hybridEncrypt =
          new WebPushHybridEncrypt.Builder()
              .withRecordSize(recordSize)
              .withAuthSecret(authSecret)
              .withRecipientPublicKey(uaPublicKey)
              .build();
      HybridDecrypt hybridDecrypt =
          new WebPushHybridDecrypt.Builder()
              .withRecordSize(recordSize + 1)
              .withAuthSecret(authSecret)
              .withRecipientPublicKey(uaPublicKey)
              .withRecipientPrivateKey(uaPrivateKey)
              .build();
      byte[] plaintext = Random.randBytes(recordSize - WebPushConstants.CIPHERTEXT_OVERHEAD);
      byte[] ciphertext = hybridEncrypt.encrypt(plaintext, null /* contextInfo */);
      try {
        hybridDecrypt.decrypt(ciphertext, null /* contextInfo */);
        fail("Expected GeneralSecurityException");
      } catch (GeneralSecurityException ex) {
        // expected.
      }
    }
  }
}