Elliptic Curve with Digital Signature Algorithm (ECDSA) implementation on BouncyCastle

22,010

Solution 1

owlstead is correct. And to elaborate a bit more, you can do this:

KeyPair pair = GenerateKeys();
Signature ecdsaSign = Signature.getInstance("SHA256withECDSA", "BC");
ecdsaSign.initSign(pair.getPrivate());
ecdsaSign.update(plaintext.getBytes("UTF-8"));
byte[] signature = ecdsaSign.sign();

And to verify:

Signature ecdsaVerify = Signature.getInstance("SHA256withECDSA", "BC");
ecdsaVerify.initVerify(pair.getPublic());
ecdsaVerify.update(plaintext.getBytes("UTF-8"));
boolean result = ecdsaVerify.verify(signature);

Solution 2

BouncyCastle is a provider: a set of classes which provides some cryptographic functionalities that applications are supposed to use through the generic API that Java comes with. See the Java Cryptography Architecture, especially the section on signatures, to see how to generate or verify a signature. Basically, you get a java.security.Signature instance (with the static getInstance() method), then you initialize it with either a private key (initSign(), to generate a signature) or a public key (initVerify(), to verify a signature). You then input the message data with one or several update() calls, and finally you call sign() or verify(), to generate or verify a signature.

Solution 3

You seem to be using Bouncy Castle mainly as provider. In that case you could simply use Signature.getInstance("SHA256withECDSA", "BC").

Share:
22,010
Yagiz
Author by

Yagiz

Updated on August 16, 2020

Comments

  • Yagiz
    Yagiz almost 4 years

    I am trying to implement ECDSA (Elliptic Curve Digital Signature Algorithm) but I couldn't find any examples in Java which use Bouncy Castle. I created the keys, but I really don't know what kind of functions I should use to create a signature and verify it.

    public static KeyPair GenerateKeys()
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException
    {
        ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("B-571");
        KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
        g.initialize(ecSpec, new SecureRandom());
        return g.generateKeyPair();
    }