RsaSsaPkcs1SignJce implements PublicKeySign { @Override public byte[] sign(final byte[] data) throws GeneralSecurityException { Signature signer = EngineFactory.SIGNATURE.getInstance(signatureAlgorithm); signer.initSign(privateKey); signer.update(data); byte[] signature = signer.sign(); Signature verifier = EngineFactory.SIGNATURE.getInstance(signatureAlgorithm); verifier.initVerify(publicKey); verifier.update(data); if (!verifier.verify(signature)) { throw new java.lang.RuntimeException("Security bug: RSA signature computation error"); } return signature; } RsaSsaPkcs1SignJce(final RSAPrivateCrtKey priv, HashType hash); @Override byte[] sign(final byte[] data);  }
@Test public void testBasicAgainstJce() throws Exception { int keySize = 2048; KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(keySize); KeyPair keyPair = keyGen.generateKeyPair(); RSAPublicKey pub = (RSAPublicKey) keyPair.getPublic(); RSAPrivateCrtKey priv = (RSAPrivateCrtKey) keyPair.getPrivate(); String message = "Hello"; RsaSsaPkcs1SignJce signer = new RsaSsaPkcs1SignJce(priv, HashType.SHA256); byte[] signature = signer.sign(message.getBytes("UTF-8")); Signature verifier = Signature.getInstance("SHA256withRSA"); verifier.initVerify(pub); verifier.update(message.getBytes("UTF-8")); assertTrue(verifier.verify(signature)); }
@Test public void testSignWithTheSameMessage() throws Exception { if (TestUtil.isTsan()) { 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)); 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()))); } } assertEquals(1, allSignatures.size()); }