SOL9 2.0 Class: Signature

 SOL9 C++ Class Library  SOL9 Samples  SOL9 Tutorial  SOL9 FAQ  SOL9 ClassTree 

Source code

/*
 * Signature.h 
 * Copyright (c) 2011 Antillia.com TOSHIYUKI ARAI. ALL RIGHTS RESERVED. 
 */


// SOL9
// 2009/02/03
// 2009/03/05 Added sign and verify methods taking Bytes parameter.

#pragma once

#include <sol/crypt/MessageDigest.h>

namespace SOL {

class Signature :public MessageDigest {


public:
    /**
     * Constructor
     */
    Signature(CryptServiceProvider& csp, ALG_ID algId)
    :MessageDigest(csp, algId) {
         
    }

public:
    /**
     * Destructor
     */
    ~Signature() {
    }

public:
    /**
     * Sign to the bytes.
     */
    // 2009/03/05
    int sign(Bytes& bytes) {
        int rc = NO_ERROR;
        unsigned char* sig = NULL;
        unsigned int   len = 0;
        if (sign(&sig, &len) == NO_ERROR) {
            bytes.shallowCopy(sig, len);
        } else {
            rc = GetLastError();
        }
        return rc;
    }

public:
    /**
     * Sign
     */
    int sign(unsigned char** signature, unsigned int* length) {
        int rc = NO_ERROR;

        //1. Determine the size of the signature.
        DWORD len= 0;

        if (CryptSignHash(
                getHashHandle(), 
                AT_SIGNATURE, 
                NULL, 
                0, 
                NULL, 
                &len)) {
            // OK
            *length = len;        
            unsigned char* buffer =  new unsigned char[len];

            //2. Sign the hash object.
            if (CryptSignHash(
                getHashHandle(), 
                AT_SIGNATURE, 
                NULL, 
                0, 
                buffer, 
                &len)) {
                // OK
                *signature = buffer;
            } else {
                // Failed
                delete[] buffer;
                rc = GetLastError();
            }
        } else {
            //Failed
            rc = GetLastError();
        }    
        return rc;
    }

public:
    /**
     * Verify signature for bytes.
     */
    // 2009/03/05
    int verify(HCRYPTKEY hPubKey, Bytes& bytes) {
    
        return verify(hPubKey, bytes.getData(), bytes.getSize());
    }


public:
    /**
     * Verify signature for signature.
     *
     */
    int verify(HCRYPTKEY hPubKey, 
            unsigned char* signature, unsigned int length) {

        int rc = NO_ERROR;

        // Validate the digital signature.
        if (!CryptVerifySignature(
               getHashHandle(), 
               signature, 
               length, 
               hPubKey,
               NULL, 0)) {
            rc = GetLastError();
        }
        return rc;
    }
};

}

Last modified: 1 Feb 2012

Copyright (c) 2009-2012 Antillia.com ALL RIGHTS RESERVED.