@Test
public void testSignWithTheSameMessage() throws Exception {

  if (TestUtil.isTsan()) {
    // This test times out when running under thread sanitizer, so we just skip.
    return;
  }
  int keySize = 4096;
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(keySize);
  KeyPair keyPair = keyGen.generateKeyPair();
  RSAPrivateCrtKey priv = (RSAPrivateCrtKey) keyPair.getPrivate();
  RSAPublicKey pub = (RSAPublicKey) keyPair.getPublic();
  byte[] msg = Random.randBytes(20);
  TreeSet<String> allSignatures = new TreeSet<String>();
  RsaSsaPkcs1SignJce signer = new RsaSsaPkcs1SignJce(priv, HashType.SHA512);
  for (int i = 0; i < 100; i++) {
    byte[] sig = signer.sign(msg);
    allSignatures.add(TestUtil.hexEncode(sig));
    // Verify with JCE's Signature.
    Signature verifier = Signature.getInstance("SHA512WithRSA");
    verifier.initVerify(pub);
    verifier.update(msg);
    if (!verifier.verify(sig)) {
      fail(
          String.format(
              "\n\nMessage: %s\nSignature: %s\nPrivateKey: %s\nPublicKey: %s\n",
              TestUtil.hexEncode(msg),
              TestUtil.hexEncode(sig),
              TestUtil.hexEncode(priv.getEncoded()),
              TestUtil.hexEncode(pub.getEncoded())));
    }
  }
  // RSA SSA PKCS1 is deterministic, expect a unique signature for the same message.
  assertEquals(1, allSignatures.size());
}