示例#1
0
//============================================================
// Locates and reads users certificate from smartcard
// slot - number of the slot for decryption key. On ID card allways 0
// ppCert - address for newly allocated certificate pointer
// return error code or ERR_OK
//============================================================
EXP_OPTION int findUsersCertificate(int slot, X509** ppCert)
{
  int err = ERR_OK, l1, l2;
  LIBHANDLE pLibrary = 0;
  CK_RV rv = 0;
  CK_SLOT_ID slotids[20], slId;
  CK_OBJECT_HANDLE hCert;
  CK_SESSION_HANDLE hSession = 0;
  CK_ULONG certLen;
  CK_BYTE certData[2048];
  char driver[100];


  *ppCert = 0;
  snprintf(driver, sizeof(driver), "DIGIDOC_DRIVER_%d_FILE", ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1));
  ddocDebug(3, "findUsersCertificate", "Slot: %d Driver nr: %d - %s", slot,
	    ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1),
	    ConfigItem_lookup(driver));
  err = loadAndTestDriver(ConfigItem_lookup(driver), 
			  &pLibrary, (CK_SLOT_ID*)slotids, 20, (CK_ULONG)slot);
  if(err) return err;

  // find the right slotid
  for(l1 = l2 = 0; l1 < 20; l1++) {
    if(slotids[l1] != INVALID_SLOTIID) {
      if(l2 == slot)
	slId = slotids[l1];
      l2++;
    }
  }
  // open session
  hSession = OpenSession(slId, NULL);
  if (hSession == CK_INVALID_HANDLE) { SET_LAST_ERROR(ERR_PKCS_LOGIN); return ERR_PKCS_LOGIN; }
  ddocDebug(3, "findUsersCertificate", "OpenSession ok, hSession = %d", (int)hSession);
  
  // get cert
  memset(certData, 0, sizeof(certData));  
  certLen = sizeof(certData);
  hCert = LocateCertificate(hSession, certData, &certLen, 0, 0, 0);
  ddocDebug(3, "findUsersCertificate", "hCert = %d, len: %d", (int)hCert, certLen);
  if (hCert == (CK_OBJECT_HANDLE)-1) { err = ERR_PKCS_CERT_LOC; SET_LAST_ERROR(err); }

  // set cert data
  if(certLen)
    err = ddocDecodeX509Data(ppCert, certData, certLen);

  
  ddocDebug(3, "findUsersCertificate", "RV: %d, cert: %s", (int)rv, (*ppCert ? "OK" : "NULL"));
  if(hSession)
    closePKCS11Library(pLibrary, hSession);

  return err;
}
示例#2
0
static BOOL DigiCrypt_IsValidCert(PCCERT_CONTEXT  pCertContext, BOOL fTimeCheck)
{
BOOL  fIsValid = FALSE;
BOOL  fRes = FALSE;
BOOL  fKuCheck = TRUE;
BYTE  bKeyUsageBits = CERT_NON_REPUDIATION_KEY_USAGE;
DWORD dwKeyUsageBytes = 1;
// VS use auth certs if key_usage_check = 0
fKuCheck = (BOOL)ConfigItem_lookup_int("KEY_USAGE_CHECK", 1);
bKeyUsageBits = fKuCheck ? CERT_NON_REPUDIATION_KEY_USAGE : 0;
//LOG("KEY_USAGE_CHECK: %d ku: %d", fKuCheck, bKeyUsageBits); 
//Old version
//FILETIME oCurrentTime;
if (pCertContext != NULL && pCertContext->pCertInfo != NULL)
  {
  //not needed (info from Tarmo Milva)
  //if (DigiCrypt_CertIsSig(pCertContext) == TRUE)
    fRes = CertGetIntendedKeyUsage(X509_ASN_ENCODING,pCertContext->pCertInfo,&bKeyUsageBits,dwKeyUsageBytes);
  //else
  //  fRes = FALSE;
  if (fRes == TRUE)
    {
    //LOG("KU non-repu: %d", (bKeyUsageBits & CERT_NON_REPUDIATION_KEY_USAGE));
    if(!fKuCheck || (bKeyUsageBits & CERT_NON_REPUDIATION_KEY_USAGE))
	  fIsValid = TRUE;
    if(bKeyUsageBits & CERT_KEY_CERT_SIGN_KEY_USAGE) // don't display CA certs
	  fIsValid = FALSE;
	}
  if (fIsValid == TRUE && fTimeCheck == TRUE)
    {
    //Old version
    //GetSystemTimeAsFileTime(&oCurrentTime);
	  //if (CompareFileTime(&oCurrentTime, &pCertContext->pCertInfo->NotBefore) < 0 ||
		//    CompareFileTime(&oCurrentTime, &pCertContext->pCertInfo->NotAfter) > 0 )
    //  fIsValid = FALSE;
    //New version
    //NULL, if current datetime
    if (CertVerifyTimeValidity(NULL,pCertContext->pCertInfo) != 0)
      fIsValid = FALSE;
    }
  }
return(fIsValid);
}
示例#3
0
//--------------------------------------------------
// This unittest reads a ddoc file and removes a data file
//--------------------------------------------------
int main(int argc, char** argv)
{
  int err = ERR_OK, i, nMaxDfLen;
  char *infile=0, *outfile=0, *dfid;
  SignedDoc* pSigDoc = 0;
  DataFile* pDf = 0;

  fprintf(stdout, "%s - %s\n", g_szProg, g_szVer);
  if(argc < 3) {
    printf("USAGE: %s <ddoc-infile> <ddoc-outfile> <datafile-id>\n", g_szProg);
    return -1;
  } else {
	for(i = 0; (err == ERR_OK) && (i < argc); i++) {
	  err = checkArguments(argc, argv, &i, &infile);
	  err = checkArguments(argc, argv, &i, &outfile);
	  err = checkArguments(argc, argv, &i, &dfid);
	}
  }
  init(argc, argv);
  nMaxDfLen = ConfigItem_lookup_int("DATAFILE_MAX_CACHE", 0);
  fprintf(stdout, "Read ddoc: %s\n", infile);
  err = ddocSaxReadSignedDocFromFile(&pSigDoc, infile, 0, nMaxDfLen);
  if(!err) {
	fprintf(stdout, "Find datafile: %s\n", dfid);
	pDf = getDataFileWithId(pSigDoc, dfid);
	if(pDf) {
		err = DataFile_delete(pSigDoc, dfid);
	} else {
		err = ERR_BAD_DATAFILE_INDEX;
		fprintf(stdout, "Invalid datafile id: %s\n", dfid);
	}
  }
  if(!err) {
	fprintf(stdout, "Writing ddoc: %s\n", outfile);
	err = createSignedDoc(pSigDoc, infile, outfile);
  }
  
  // display result
  listStatus(g_szProg, err);
  return err;
}
示例#4
0
//--------------------------------------------------
// This unittest reads a ddoc file and adds a data file
//--------------------------------------------------
int main(int argc, char** argv)
{
  int err = ERR_OK, i, nMaxDfLen;
  char *infile=0, *outfile=0, *dfinfile, *mime=0, *content="EMBEDDED_BASE64";
  SignedDoc* pSigDoc = 0;
  DataFile* pDf = 0;

  fprintf(stdout, "%s - %s\n", g_szProg, g_szVer);
  if(argc < 5) {
    printf("USAGE: %s <ddoc-infile> <ddoc-outfile> <datafile-name> <mime-type> [<content-type>]\n", g_szProg);
    return -1;
  } else {
	for(i = 0; (err == ERR_OK) && (i < argc); i++) {
	  err = checkArguments(argc, argv, &i, &infile);
	  err = checkArguments(argc, argv, &i, &outfile);
	  err = checkArguments(argc, argv, &i, &dfinfile);
	  err = checkArguments(argc, argv, &i, &mime);
	  err = checkArguments(argc, argv, &i, &content);
	}
  }
  init(argc, argv);
  nMaxDfLen = ConfigItem_lookup_int("DATAFILE_MAX_CACHE", 0);
  fprintf(stdout, "Read ddoc: %s\n", infile);
  err = ddocSaxReadSignedDocFromFile(&pSigDoc, infile, 0, nMaxDfLen);
  if(!err) {
	fprintf(stdout, "Add datafile: %s mime: %s content: %s\n", dfinfile, mime, content);
	err = DataFile_new(&pDf, pSigDoc, NULL, dfinfile, 
		     content, mime, 0, NULL, 0, NULL, NULL);
  }
  if(!err)
	err = calculateDataFileSizeAndDigest(pSigDoc, pDf->szId, infile, DIGEST_SHA1);
  if(!err) {
	fprintf(stdout, "Writing ddoc: %s\n", outfile);
	err = createSignedDoc(pSigDoc, infile, outfile);
  }
  
  // display result
  listStatus(g_szProg, err);
  return err;
}
示例#5
0
//============================================================
// Decrypts RSA encrypted data with the private key
// slot - number of the slot for decryption key. On ID card allways 0
// pin - corresponding pin for the key. On ID card - PIN1
// encData - encrypted data
// encLen - length of encrypted data
// decData - buffer for decrypted data
// encLen - length of buffer. Will be modified by amount of decrypted data
// return error code or ERR_OK
//============================================================
EXP_OPTION int decryptWithEstID(int slot, const char* pin, 
				const char* encData, int encLen, 
				char* decData, int *decLen)
{
  int err = ERR_OK, l1, l2;
  LIBHANDLE pLibrary = 0;
  CK_ULONG keyIdLen[20];
  CK_RV rv;
  CK_SLOT_ID slotids[20], slId;
  CK_SESSION_HANDLE hSession = 0;
  CK_OBJECT_HANDLE hPrivateKey, hKeys[20];
  char keyId[20][20];
  char driver[100];
  CK_MECHANISM Mechanism = { CKM_RSA_PKCS, 0, 0 };
  CK_ULONG outlen;

  ddocDebug(3, "decryptWithEstID", "slot: %d enc-data: %d bytes buffer size: %d", slot, encLen, *decLen);
  snprintf(driver, sizeof(driver), "DIGIDOC_DRIVER_%d_FILE", ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1));
  ddocDebug(3, "decryptWithEstID", "Driver nr: %d - %s", 
	    ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1),
	    ConfigItem_lookup(driver));
  err = loadAndTestDriver(ConfigItem_lookup(driver), 
			  &pLibrary, (CK_SLOT_ID*)slotids, 20, (CK_ULONG)slot);
  if(err) return err;

  // find the right slotid
  for(l1 = l2 = 0; l1 < 20; l1++) {
    if(slotids[l1] != INVALID_SLOTIID) {
      if(l2 == slot)
	slId = slotids[l1];
      l2++;
    }
  }
  // open session
  hSession = OpenSession(slId, pin);
  if (hSession == CK_INVALID_HANDLE) { SET_LAST_ERROR(ERR_PKCS_LOGIN); return ERR_PKCS_LOGIN; }
  ddocDebug(3, "decryptWithEstID", "OpenSession ok, hSession = %d", (int)hSession);
  
  // get private key
  for(l1 = 0; l1 < 20; l1++) {
    memset(keyId[l1], 0, 20);
    keyIdLen[l1] = 0;
  }
  err = LocatePrivateKey(hSession, keyId, keyIdLen, hKeys);
  hPrivateKey = hKeys[0]; //???
  //ddocDebug(3, "decryptWithEstID", "Priv key: %s", keyId);
  //if (hPrivateKey == CK_INVALID_HANDLE) { SET_LAST_ERROR(ERR_PKCS_PK); return ERR_PKCS_PK; }
  // init decrypt
  rv = (*ckFunc->C_DecryptInit)(hSession, &Mechanism, hPrivateKey);
  ddocDebug(3, "decryptWithEstID", "DecryptInit: %d", (int)rv);
  if(rv != CKR_OK) SET_LAST_ERROR_RETURN(ERR_DENC_DECRYPT, ERR_DENC_DECRYPT)
  // decrypt data
  outlen = *decLen;
  rv = (*ckFunc->C_Decrypt)(hSession, (CK_BYTE_PTR)encData, (CK_ULONG)encLen, (CK_BYTE_PTR)decData, (CK_ULONG_PTR)&outlen);
  *decLen = outlen;
  ddocDebug(3, "decryptWithEstID", "RV: %d, dec-len: %d", (int)rv, *decLen);
  if(hSession)
    closePKCS11Library(pLibrary, hSession);
  if(rv != CKR_OK)
    SET_LAST_ERROR_RETURN(ERR_DENC_DECRYPT, ERR_DENC_DECRYPT)
  return err;
}
示例#6
0
//============================================================
// Calculates and stores a signature for this SignatureInfo object
// Uses EstEID card to sign the info
// pSigInfo - signature info object
// nSigType - signature type code
// keyfile - RSA key file
// passwd - key password
// certfile - certificate file
//============================================================
EXP_OPTION int calculateSignatureWithEstID(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, 
                    int slot, const char* passwd)
{
  int err = ERR_OK, nKey;
  LIBHANDLE pLibrary = 0;
  CK_ULONG certLen, sigLen, padDigLen;
  CK_RV rv;
  CK_SLOT_ID slotids[20], slId = 0;
  CK_SESSION_HANDLE hSession = 0;
  CK_OBJECT_HANDLE hPrivateKey, hKeys[20], hCert;
  char keyId[20][20];
  CK_ULONG keyIdLen[20];
  CK_BYTE certData[2048];
  CK_BYTE sigDig[100], padDig[130];
  CK_BYTE signature[256];
  CK_BYTE padding[] = { 48, 33, 48, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0, 4, 20 };
	CK_BYTE padding256[] = { 48, 49, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32};
	//CK_BYTE padding256[] = { 48, 33, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32};
  char* buf1;
  int l1, l2;
  X509* x509;
  DigiDocMemBuf mbuf1;

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(pSigDoc);
  // try active driver driver first
  snprintf((char*)signature, sizeof(signature), "DIGIDOC_DRIVER_%d_FILE", 
	  ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1));
  for(l1 = 0; l1 < 20; l1++) 
    slotids[l1] = INVALID_SLOTIID; // initialize
  err = loadAndTestDriver(ConfigItem_lookup((const char*)signature),
			  &pLibrary, (CK_SLOT_ID*)slotids, 20, (CK_ULONG)slot);
  ddocDebug(3, "calculateSignatureWithEstID", "Driver handle: %d err = %d slot: %d", 
	    pLibrary, err, slot);
  RETURN_IF_NOT(err == ERR_OK, err);
  // inittialize
  slId = INVALID_SLOTIID; // not found yet
  //err = ddocLocateSlotWithSignatureCert(pLibrary, slotids, 
  //					&slId, (char*)signature, sizeof(signature));
  
  // find suitable slotid
  
  for(l1 = 0; l1 < 20; l1++) {
    if(slotids[l1] != INVALID_SLOTIID)
      ddocDebug(3, "calculateSignatureWithEstID", 
		"Slot idx: %d = %d", l1, slotids[l1]);
    if(slotids[l1] != INVALID_SLOTIID && l1 == slot) {
      slId = slotids[l1];
      ddocDebug(3, "calculateSignatureWithEstID", 
		"Select idx: %d slot: %d", l1, slId);
    }
  }
  
  // open session
  if(slId != INVALID_SLOTIID) {
    hSession = OpenSession(slId, passwd);
    ddocDebug(3, "calculateSignatureWithEstID", 
	      "Open sess for slot: %d sess = %uld\n", slId, hSession);
    if (hSession == CK_INVALID_HANDLE) { err = ERR_PKCS_LOGIN; SET_LAST_ERROR(err); return err; }
    ddocDebug(3, "calculateSignatureWithEstID", "OpenSession ok, hSession = %d\n", (int)hSession);

    // get private key
    for(l1 = 0; l1 < 20; l1++) {
      memset(keyId[l1], 0, 20);
      keyIdLen[l1] = 0;
    }
    err = LocatePrivateKey(hSession, keyId, keyIdLen, hKeys);
    //ddocDebug(3, "calculateSignatureWithEstID", "Priv key: %s", keyId);
    //if (hPrivateKey == CK_INVALID_HANDLE) { err = ERR_PKCS_PK; SET_LAST_ERROR(err); return err; }

    // get cert     
    memset(certData, 0, sizeof(certData));  
    certLen = sizeof(certData);
    hCert = LocateCertificate(hSession, certData, &certLen, keyId, keyIdLen, &nKey);
    hPrivateKey = hKeys[nKey];
    ddocDebug(3, "calculateSignatureWithEstID", "selected priv-key: %ld pos %d id: %s", hPrivateKey, nKey, keyId[nKey]);
    ddocDebug(3, "calculateSignatureWithEstID", "Cert-len: %ld", certLen);
    //printf("Cert: %s", certData);
    if (hCert == (CK_OBJECT_HANDLE)-1) { err = ERR_PKCS_CERT_LOC; SET_LAST_ERROR(err); return err; }

    // set cert data
    err = ddocDecodeX509Data(&x509, certData, certLen);
    if (!x509) { err = ERR_PKCS_CERT_DECODE;  }
	  // save cert in file
	  if(ConfigItem_lookup_int("DEBUG_LEVEL", 1) > 3)
	  saveCert(x509, "signer.pem", FILE_FORMAT_PEM);
		//AM 07.03.08 setSignatureCert for BDOC
		if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME)) { 
				setSignatureCertBDOC(pSigInfo, x509);
		}else{
				setSignatureCert(pSigInfo, x509);
		}

		//AM 12.03.08
		//VS 23.02.2010 - not necessary?
		/*if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME)) { 
		findCAForCertificate(&ppCA, x509);
		err = bdocSigInfo_addCert(pSigInfo, ppCA, CERTID_TYPE_CA_CERTID);
		}*/ 

    // FIXME
    createTimestamp(pSigDoc, (char*)sigDig, sizeof(sigDig));
    setString((char**)&(pSigInfo->szTimeStamp), (const char*)sigDig, -1);

    // Signed properties digest
    buf1 = createXMLSignedProperties(pSigDoc, pSigInfo, 0);
    //dumpInFile("sigprop-sign1.txt", buf1);
    if (!buf1) { 
      err = ERR_NULL_POINTER; 
      SET_LAST_ERROR(err);
      return err;
    }
    mbuf1.pMem = canonicalizeXML((char*)buf1, strlen(buf1));
    mbuf1.nLen = strlen((const char*)mbuf1.pMem);
    ddocDebugWriteFile(4, "sigprop-signed.txt", &mbuf1);
    l2 = sizeof(sigDig);
	//AM 24.04.08
	if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME))
		err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, BDOC_DIGEST, sigDig, &l2);
	else
		err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, DIGEST_SHA1, sigDig, &l2);
    free(buf1);
    ddocMemBuf_free(&mbuf1);
    if (err != ERR_OK) {
      SET_LAST_ERROR(err);			
      return err;
    }
    ddocSigInfo_SetSigPropDigest(pSigInfo, (const char*)sigDig, l2);
    ddocSigInfo_SetSigPropRealDigest(pSigInfo, (const char*)sigDig, l2);
    // create signed info
	//AM 11.03.08 createXMLSignedInfo for BDOC
	if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME))
		buf1 = createXMLSignedInfoBDoc(pSigDoc, pSigInfo);
	else
		buf1 = createXMLSignedInfo(pSigDoc, pSigInfo);      
    if (!buf1) {
      err = ERR_NULL_POINTER;
      SET_LAST_ERROR(err);
      return err ;
    }
    // get digest
    l2 = sizeof(sigDig);
	/*if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME))
		err = calculateDigest((const byte*)buf1, strlen(buf1),  BDOC_DIGEST, sigDig, &l2);
	else*/
		err = calculateDigest((const byte*)buf1, strlen(buf1),  DIGEST_SHA1, sigDig, &l2);
    free(buf1);
    if (err != ERR_OK) {
      err = ERR_NULL_POINTER;
      SET_LAST_ERROR(err);
      return err;
    } 
    ddocSigInfo_SetSigInfoRealDigest(pSigInfo, (const char*)sigDig, l2);
    // sign data
    sigLen = sizeof(signature);
    memset(signature, 0, sizeof(signature));
    // pad PKCS#1 ver 1
    /*if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME) && BDOC_DIGEST==DIGEST_SHA256) {
		padDigLen = 51;
		memset(padDig, 0, sizeof(padDig));
		memcpy(padDig, padding256, 19);
		memcpy(padDig + 19, sigDig, l2);
	} else {*/
		padDigLen = 35;
		memset(padDig, 0, sizeof(padDig));
		memcpy(padDig, padding, 15);
		memcpy(padDig + 15, sigDig, l2);
	//}
    //rv = RSA_padding_add_PKCS1_type_1(padDig, padDigLen, sigDig, l2);
    //rv = RSA_padding_check_PKCS1_type_1(sigDig, l2, padDig, padDigLen, padDigLen+1);
    // checkErrors();
    // sign data
    rv = SignData(hSession, hPrivateKey, 
		  signature, &sigLen, padDig, padDigLen);    
    if (rv != CKR_OK) { 
      err = ERR_PKCS_SIGN_DATA;
      SET_LAST_ERROR(err);
      return err;
    }		

    // set signature value
    ddocSigInfo_SetSignatureValue(pSigInfo, (const char*)signature, (int)sigLen);
  } // if slotid found
    
  if(hSession)
    closePKCS11Library(pLibrary, hSession);
  return err;
}
示例#7
0
//============================================================
// Calculates and stores a signature for this SignatureInfo object
// Uses EstEID card to sign the info
// pSigInfo - signature info object
// nSigType - signature type code
// keyfile - RSA key file
// passwd - key password
// certfile - certificate file
//============================================================
EXP_OPTION int calculateSignatureWithEstID(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, 
                    int slot, const char* passwd)
{
  int err = ERR_OK, nKey;
  LIBHANDLE pLibrary = 0;
  CK_ULONG certLen, sigLen, padDigLen;
  CK_RV rv;
  CK_SLOT_ID slotids[20], slId = 0;
  CK_SESSION_HANDLE hSession = 0;
  CK_OBJECT_HANDLE hPrivateKey = 0, hKeys[20], hCert;
  char keyId[20][20], kId[20];
  CK_ULONG keyIdLen[20];
  CK_BYTE certData[2048];
  CK_BYTE sigDig[100], padDig[130];
  CK_BYTE signature[256];
  CK_BYTE padding[] = { 48, 33, 48, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0, 4, 20 };
  //CK_BYTE padding256[] = { 48, 49, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32};
  //CK_BYTE padding256[] = { 48, 33, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32};
  char* buf1;
  int l1, l2, kILen;
  X509* x509 = 0;
  DigiDocMemBuf mbuf1;

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(pSigDoc);
  // try active driver driver first
  snprintf((char*)signature, sizeof(signature), "DIGIDOC_DRIVER_%d_FILE", 
	  ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1));
  for(l1 = 0; l1 < 20; l1++) 
    slotids[l1] = INVALID_SLOTIID; // initialize
  err = loadAndTestDriver(ConfigItem_lookup((const char*)signature),
			  &pLibrary, (CK_SLOT_ID*)slotids, 20, (CK_ULONG)slot);
  ddocDebug(3, "calculateSignatureWithEstID", "Driver handle: %d err = %d slot: %d", 
	    pLibrary, err, slot);
  RETURN_IF_NOT(err == ERR_OK, err);
  // inittialize
  slId = INVALID_SLOTIID; // not found yet  
  // try key-usage check
  if(ConfigItem_lookup_int("KEY_USAGE_CHECK", 1)) {
    kILen = sizeof(kId);
    ddocDebug(3, "calculateSignatureWithEstID", "Find slot by key-usage, slot: %d", slot);
    err = ddocLocateSlotWithSignatureCert(pLibrary, slotids, &slId, &x509, kId, &kILen, slot, &l1);
    ddocDebug(3, "calculateSignatureWithEstID", 
		"Select by key-usage slot idx: %d = %d err: %d key-id: %s, kid-len: %d", l1, slId, err, kId, kILen);
    if(err != ERR_OK || l1 < 0 || l1 >= 20) {
		SET_LAST_ERROR(ERR_SIGNERS_CERT_NON_REPU);
        return ERR_SIGNERS_CERT_NON_REPU;
	}
  } else {
    ddocDebug(3, "calculateSignatureWithEstID", "Find slot by slot idx: %d", slot);
    for(l1 = 0; (l1 < 20) && (slId == INVALID_SLOTIID); l1++) {
      if(slotids[l1] != INVALID_SLOTIID)
        ddocDebug(3, "calculateSignatureWithEstID", 
                        "Slot idx: %d = %d", l1, slotids[l1]);
      if(slotids[l1] != INVALID_SLOTIID && l1 == slot) {
        slId = slotids[l1];
        ddocDebug(3, "calculateSignatureWithEstID", 
                        "Select idx: %d slot: %d", l1, slId);
    } // if slotid
    } // for
  }
  // use default if not found by key-id or direct 
  if(slId == INVALID_SLOTIID) {
      l1 = ConfigItem_lookup_int("DIGIDOC_SIGNATURE_SLOT", 0);
      if(slotids[l1] != INVALID_SLOTIID) {
          ddocDebug(3, "calculateSignatureWithEstID", 
                    "Select default slot idx: %d = %d", l1, slotids[l1]);
          slId = slotids[l1];
      }
  }

  // open session
  if(slId != INVALID_SLOTIID) {
    hSession = OpenSession(slId, passwd);
    ddocDebug(3, "calculateSignatureWithEstID", 
	      "Open sess for slot: %d sess = %d", slId, hSession);
    if (hSession == CK_INVALID_HANDLE) { err = ERR_PKCS_LOGIN; SET_LAST_ERROR(err); return err; }
    ddocDebug(3, "calculateSignatureWithEstID", "OpenSession ok, hSession1 = %d", (int)hSession);

    if(!x509) {
		ddocDebug(3, "calculateSignatureWithEstID", "Cert ok");
      // get private key
      for(l1 = 0; l1 < 20; l1++) {
        memset(keyId[l1], 0, 20);
        keyIdLen[l1] = 0;
      }
      err = LocatePrivateKey(hSession, keyId, keyIdLen, hKeys);
      //ddocDebug(3, "calculateSignatureWithEstID", "Priv key: %s", keyId);
      //

      // get cert  
      memset(certData, 0, sizeof(certData));  
      certLen = sizeof(certData);
      hCert = LocateCertificate(hSession, certData, &certLen, keyId, keyIdLen, &nKey);
      hPrivateKey = hKeys[nKey];
      ddocDebug(3, "calculateSignatureWithEstID", "selected priv-key: %ld pos %d id: %s", hPrivateKey, nKey, keyId[nKey]);
      ddocDebug(3, "calculateSignatureWithEstID", "Cert-len: %ld", certLen);
      //printf("Cert: %s", certData);
      if (hCert == (CK_OBJECT_HANDLE)-1) { err = ERR_PKCS_CERT_LOC; SET_LAST_ERROR(err); return err; }

      // set cert data
      err = ddocDecodeX509Data(&x509, certData, certLen);
      

    } else { // cert already found
		//kILen = sizeof(kId);
        ddocDebug(3, "calculateSignatureWithEstID", "Locate priv key2 id: %s, len: %d, hkey: %d", kId, kILen, hPrivateKey);
		err = LocatePrivateKeyWithId(hSession, (CK_BYTE_PTR)kId, kILen, &hPrivateKey);
		ddocDebug(3, "calculateSignatureWithEstID", "Priv key-id: %s len: %d hkey: %d err: %d", kId, kILen, hPrivateKey, err);
    }	 
	ddocDebug(3, "calculateSignatureWithEstID", "Priv key: %d err: %d", hPrivateKey, err);
    if (hPrivateKey == CK_INVALID_HANDLE) { err = ERR_PKCS_PK; SET_LAST_ERROR(err); return err; }
    if (!x509) { err = ERR_PKCS_CERT_DECODE;  }
      
   // save cert in file
   if(ConfigItem_lookup_int("DEBUG_LEVEL", 1) > 3) 
     saveCert(x509, "signer.pem", FILE_FORMAT_PEM);
   setSignatureCert(pSigInfo, x509);

    // FIXME
    createTimestamp(pSigDoc, (char*)sigDig, sizeof(sigDig));
    setString((char**)&(pSigInfo->szTimeStamp), (const char*)sigDig, -1);

    // Signed properties digest
    buf1 = createXMLSignedProperties(pSigDoc, pSigInfo, 0);
    //dumpInFile("sigprop-sign1.txt", buf1);
    if (!buf1) { 
      err = ERR_NULL_POINTER; 
      SET_LAST_ERROR(err);
      return err;
    }
    mbuf1.pMem = canonicalizeXML((char*)buf1, strlen(buf1));
    mbuf1.nLen = strlen((const char*)mbuf1.pMem);
    ddocDebugWriteFile(4, "sigprop-signed.txt", &mbuf1);
    l2 = sizeof(sigDig);
    err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, DIGEST_SHA1, sigDig, &l2);
    free(buf1);
    ddocMemBuf_free(&mbuf1);
    if (err != ERR_OK) {
      SET_LAST_ERROR(err);			
      return err;
    }
    ddocSigInfo_SetSigPropDigest(pSigInfo, (const char*)sigDig, l2);
    ddocSigInfo_SetSigPropRealDigest(pSigInfo, (const char*)sigDig, l2);
    // create signed info
    buf1 = createXMLSignedInfo(pSigDoc, pSigInfo);      
    if (!buf1) {
      err = ERR_NULL_POINTER;
      SET_LAST_ERROR(err);
      return err ;
    }
    // get digest
    l2 = sizeof(sigDig);
	err = calculateDigest((const byte*)buf1, strlen(buf1),  DIGEST_SHA1, sigDig, &l2);
    free(buf1);
    if (err != ERR_OK) {
      err = ERR_NULL_POINTER;
      SET_LAST_ERROR(err);
      return err;
    } 
    ddocSigInfo_SetSigInfoRealDigest(pSigInfo, (const char*)sigDig, l2);
    // sign data
    sigLen = sizeof(signature);
    memset(signature, 0, sizeof(signature));
    // pad PKCS#1 ver 1
	padDigLen = 35;
	memset(padDig, 0, sizeof(padDig));
	memcpy(padDig, padding, 15);
	memcpy(padDig + 15, sigDig, l2);
    //rv = RSA_padding_add_PKCS1_type_1(padDig, padDigLen, sigDig, l2);
    //rv = RSA_padding_check_PKCS1_type_1(sigDig, l2, padDig, padDigLen, padDigLen+1);
    // checkErrors();
    // sign data
    rv = SignData(hSession, hPrivateKey, 
		  signature, &sigLen, padDig, padDigLen);    
    if (rv != CKR_OK) { 
      err = ERR_PKCS_SIGN_DATA;
      SET_LAST_ERROR(err);
      return err;
    }		

    // set signature value
    ddocSigInfo_SetSignatureValue(pSigInfo, (const char*)signature, (int)sigLen);
	ddocDebug(3, "calculateSignatureWithEstID", "Sig-len: %ld", sigLen);
    
  } // if slotid found
    
  if(hSession)
    closePKCS11Library(pLibrary, hSession);
  return err;
}
示例#8
0
PCCERT_CONTEXT DigiCrypt_ReadCertFromCard(void)
{
HCRYPTPROV hCryptProv;
BYTE       *pbData = NULL;   
HCRYPTKEY  hKey;          
DWORD cbData = 0;
DWORD dwKeyType=0, dwKeySpec = AT_SIGNATURE;
DWORD dwErrCode=0;
DWORD cspType=0;
DWORD cspFlag=CRYPT_SILENT;
char *psCspName = NULL;
char *psKeyContainer;
BOOL fRes = FALSE;
PCCERT_CONTEXT  pCertContext = NULL; 
CRYPT_KEY_PROV_INFO KeyProvInfo;
LPWSTR wszContainerName=NULL;
LPWSTR wszProvName=NULL;
DWORD cchContainerName;
DWORD cchCSPName;
HCRYPTPROV hProv;


DigiCrypt_ReleaseFirstAllowedCSP();

psCspName=DigiCrypt_GetFirstAllowedCSPNameNew();

//very dummy thing.. i check from csp creators why i should do so...
if(!lstrcmp(psCspName,"EstEID Card CSP"))
   fRes = CryptAcquireContext(&hProv,"XXX",psCspName,2, CRYPT_SILENT);
// end dummy//

if (psCspName == NULL || strstr(psCspName,psData_Est_CSP_Name) == NULL)
  return(pCertContext);

cspType=DigiCrypt_FindContext_GetCSPType(psCspName);

psKeyContainer=DigiCrypt_GetDefaultKeyContainerName(psCspName);

fRes = CryptAcquireContext(&hCryptProv,psKeyContainer,psCspName,cspType, CRYPT_SILENT);
if (fRes == FALSE)
  return(pCertContext);

// VS: use alsu auth keys if KEY_USAGE_CHECK=false
dwKeySpec = ConfigItem_lookup_int("KEY_USAGE_CHECK", 1) ? AT_SIGNATURE : 0;

fRes=CryptGetUserKey(hCryptProv, dwKeySpec, &hKey);
if (fRes == TRUE)
  {
  fRes=CryptGetKeyParam(hKey, KP_CERTIFICATE, NULL, &cbData, 0);
  if (fRes == TRUE)
    {
    pbData = malloc(cbData);
    if (pbData == NULL)
      fRes = FALSE;
    }
  if (fRes == TRUE)
    fRes=CryptGetKeyParam(hKey, KP_CERTIFICATE, pbData, &cbData, 0);
  if (fRes == TRUE)
    {
    pCertContext = CertCreateCertificateContext(MY_ENCODING_TYPE,pbData,cbData);
    if (pCertContext != NULL)
      { 
	  wszContainerName=NULL;
	  wszProvName=NULL;
	  cchContainerName = (lstrlen(psKeyContainer) + 1)  * sizeof(WCHAR);
	  cchCSPName = (lstrlen(psCspName) + 1) * sizeof(WCHAR);
      wszContainerName = (LPWSTR) malloc(cchContainerName);
      wszProvName = (LPWSTR) malloc(cchCSPName);
      mbstowcs(wszContainerName, psKeyContainer,cchContainerName);
	  mbstowcs(wszProvName, psCspName, cchCSPName);
      ZeroMemory((PVOID)&KeyProvInfo, sizeof(CRYPT_KEY_PROV_INFO));
      KeyProvInfo.pwszContainerName = (LPWSTR) wszContainerName;
      KeyProvInfo.pwszProvName      = (LPWSTR) wszProvName;
      KeyProvInfo.dwProvType        = PROV_RSA_SIG;
      KeyProvInfo.dwFlags           = 0;
      KeyProvInfo.dwKeySpec         = dwKeyType;
      fRes = CertSetCertificateContextProperty(pCertContext,CERT_KEY_PROV_INFO_PROP_ID, 0, (const void *) &KeyProvInfo);
      if (wszContainerName != NULL)
        free(wszContainerName);
      if (wszProvName != NULL)
        free(wszProvName);

      }
    }
  }

//if (pCertContext != NULL)
//  DigiCrypt_AddCertToStore(pCertContext);
if (fRes == FALSE && pCertContext != NULL)
  {
  CertFreeCertificateContext(pCertContext);
  pCertContext = NULL;
  }
if (pbData != NULL)
  free(pbData);
if (hCryptProv != 0)
  CryptReleaseContext(hCryptProv, 0);
return(pCertContext);
}