Using signatures - ivan-zaera/cipher GitHub Wiki

To sign some data with a Signer you can use the following code:

    var eccDomain = new ECDomainParameters( "prime192v1" );
  
    var d = new BigInteger("3062713166230336928689662410859599564103408831862304472446");
    var privParams = new PrivateKeyParameter(new ECPrivateKey(d, eccDomain));
    var signParams = () => new ParametersWithRandom(privParams, new SecureRandom() );
  
    var signer = new Signer("SHA-1/ECDSA")
      ..init( true, signParams )
    ;
    
    var message = inputMessage();
    
    var signature = signer.generateSignature( message );
    
    outputSignedMessage( message, signature );

For signature verification, the code is similar but we need to use the other key:

    var eccDomain = new ECDomainParameters( "prime192v1" );

    var Qx = new BigInteger("1498602238651628509310686451034731914387602356706565103527");
    var Qy = new BigInteger("6264116558863692852155702059476882343593676720209154057133");
    var Q = eccDomain.curve.createPoint( Qx, Qy );
    var verifyParams = () => new PublicKeyParameter( new ECPublicKey(Q, eccDomain) );
        
    var signer = new Signer("SHA-1/ECDSA")
      ..init( false, verifyParams )
    ;
    
    var message = inputMessage();
    var signature = inputSignature();
    
    var ok = signer.verifySignature( message, signature );
    
    outputValidSignature( ok );

In general, you construct the Signer with the factory constructor which receives the standard algorithm name and then init() the signer with its corresponding CipherParameters. See Algorithm nomenclature for documentation on standard algorithm names.

The type of CipherParameters to be used depends on the algorithm. For the example (SHA-1/ECDSA) it consists of the public or secret key but, for other algorithms, it can change. See the Table of provided algorithms to get information on which CipherParameters to use for the algorithm of your choice.

To sign you make a call to init() passing true as forSigning parameter value. Then you call generateSignature() with the message and the signature is returned. The structure of the Signature depends on the algorithm being used, so you need to cast it to its proper type. See the Table of provided algorithms to get information on signature structure.

On the other hand, to verify a signature you call verifySignature() and pass false as the first parameter when calling init(). The structure of the Signature depends on the algorithm being used, so you need to create it using a valid constructor. See the Table of provided algorithms to get information on signature structure.

Finally, you can reset an algorithm to its initial state with the reset() method.

NOTE: You can generate key pairs for asymmetric block ciphers as explained in Using key generators.