EcdsaSignJce 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(); if (encoding == EcdsaEncoding.IEEE_P1363) { EllipticCurve curve = privateKey.getParams().getCurve(); signature = EllipticCurves.ecdsaDer2Ieee(signature, 2 * EllipticCurves.fieldSizeInBytes(curve)); } return signature; } EcdsaSignJce(final ECPrivateKey priv, HashType hash, EcdsaEncoding encoding); @Override byte[] sign(final byte[] data);  }
@Test public void testBasic() 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(); String message = "Hello"; EcdsaSignJce signer = new EcdsaSignJce(priv, HashType.SHA256, EcdsaEncoding.DER); byte[] signature = signer.sign(message.getBytes("UTF-8")); Signature verifier = Signature.getInstance("SHA256WithECDSA"); verifier.initVerify(pub); verifier.update(message.getBytes("UTF-8")); assertTrue(verifier.verify(signature)); }
@Test public void testBitFlipAgainstSignatureInstance() 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(); String message = "Hello"; EcdsaSignJce signer = new EcdsaSignJce(priv, HashType.SHA256, EcdsaEncoding.DER); byte[] signature = signer.sign(message.getBytes("UTF-8")); for (int i = 0; i < signature.length; i++) { for (int j = 0; j < 8; j++) { signature[i] = (byte) (signature[i] ^ (1 << j)); Signature verifier = Signature.getInstance("SHA256WithECDSA"); verifier.initVerify(pub); verifier.update(message.getBytes("UTF-8")); boolean verified = true; try { verified = verifier.verify(signature); } catch (GeneralSecurityException expected) { verified = false; } assertFalse(verified); signature[i] = (byte) (signature[i] ^ (1 << j)); } } }