EcdsaVerifyJce implements PublicKeyVerify { @Override public void verify(final byte[] signature, final byte[] data) throws GeneralSecurityException { byte[] derSignature = signature; if (encoding == EcdsaEncoding.IEEE_P1363) { EllipticCurve curve = publicKey.getParams().getCurve(); if (signature.length != 2 * EllipticCurves.fieldSizeInBytes(curve)) { throw new GeneralSecurityException("Invalid signature"); } derSignature = EllipticCurves.ecdsaIeee2Der(signature); } if (!EllipticCurves.isValidDerEncoding(derSignature)) { throw new GeneralSecurityException("Invalid signature"); } Signature verifier = EngineFactory.SIGNATURE.getInstance(signatureAlgorithm); verifier.initVerify(publicKey); verifier.update(data); boolean verified = false; try { verified = verifier.verify(derSignature); } catch (java.lang.RuntimeException ex) { verified = false; } if (!verified) { throw new GeneralSecurityException("Invalid signature"); } } EcdsaVerifyJce(final ECPublicKey pubKey, HashType hash, EcdsaEncoding encoding); @Override void verify(final byte[] signature, final byte[] data);  }
@Test public void testModification() throws Exception { ECParameterSpec ecParams = EllipticCurves.getNistP256Params(); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC"); keyGen.initialize(ecParams); KeyPair keyPair = keyGen.generateKeyPair(); ECPublicKey pub = (ECPublicKey) keyPair.getPublic(); ECPrivateKey priv = (ECPrivateKey) keyPair.getPrivate(); EcdsaEncoding[] encodings = new EcdsaEncoding[] {EcdsaEncoding.IEEE_P1363, EcdsaEncoding.DER}; for (EcdsaEncoding encoding : encodings) { EcdsaSignJce signer = new EcdsaSignJce(priv, HashType.SHA256, encoding); byte[] message = "Hello".getBytes("UTF-8"); byte[] signature = signer.sign(message); EcdsaVerifyJce verifier = new EcdsaVerifyJce(pub, HashType.SHA256, encoding); for (BytesMutation mutation : TestUtil.generateMutations(signature)) { try { verifier.verify(mutation.value, message); fail( String.format( "Invalid signature, should have thrown exception : signature = %s, message = %s, " + " description = %s", Hex.encode(mutation.value), Arrays.toString(message), mutation.description)); } catch (GeneralSecurityException expected) { } } verifier = new EcdsaVerifyJce( pub, HashType.SHA256, encoding == EcdsaEncoding.IEEE_P1363 ? EcdsaEncoding.DER : EcdsaEncoding.IEEE_P1363); try { verifier.verify(signature, message); fail("Invalid signature, should have thrown exception"); } catch (GeneralSecurityException expected) { } } }