spbggenkeycsr.c

Exemplo de SPB para geração de chave, CSR e importação de certificado.

Veja Nota sobre os exemplos.
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dinamo.h>
#ifdef WIN32
#include <process.h>
#define FSTAT(x,y) _fstat(_fileno(x), y)
#define STAT _stat
#else
#define FSTAT(x,y) fstat(fileno(x),y)
#define STAT stat
#endif
/* Parametros da conexao */
#define HSM_USR "user"
#define HSM_IP "10.0.62.10"
#define HSM_PWD "12345678"
int main(void)
{
int nRet = 0;
struct AUTH_PWD_EX stAUTPWD = {0};
HSESSIONCTX hSession = NULL;
char szOutPrivKeyName[MAX_OBJ_ID_FQN_LEN] = {0};
char *szISPB_DOMAIN = "12345678@MES01";
char *szSubject = "/CN=BANCO TESTE S/A P001/OU=SISBACEN-00888/OU=ISPB-54444619/O=ICP-Brasil/L=Sao Paulo/S=Sao Paulo/C=BR";
DWORD dwCSRLen = 0;
BYTE *pbCSR = NULL;
char *szDomain = "MES01";
/* Nota: !!! Altere este buffer com o certificado recebido da Autoridade Certificadora !!! */
BYTE pbCertificate[] = {
0x00, 0x00
} ;
// Preenche a estrutura de usuario
strncpy(stAUTPWD.szAddr, HSM_IP, sizeof(stAUTPWD.szAddr));
strncpy(stAUTPWD.szUserId, HSM_USR, sizeof(stAUTPWD.szUserId));
strncpy(stAUTPWD.szPassword, HSM_PWD, sizeof(stAUTPWD.szPassword));
stAUTPWD.nPort = DEFAULT_PORT;
stAUTPWD.nStrongAuthLen = 0;
stAUTPWD.pbStrongAuth = NULL;
nRet = DOpenSession( &hSession, SS_USR_PWD_EX, (BYTE *) &stAUTPWD, sizeof(struct AUTH_PWD_EX), CACHE_BYPASS | LB_BYPASS | ENCRYPTED_CONN );
if(nRet) {
printf("DOpenSession : Failed! %d.\n", nRet);
goto clean;
}
/* Gera a chave privada */
nRet = DSPBGenerateKey( hSession, szISPB_DOMAIN, szOutPrivKeyName, EXPORTABLE_KEY, 0 );
if( nRet )
{
printf("DSPBGenerateKey : Failed! %d.\n", nRet);
goto clean;
}
/* Gera o CSR */
nRet = DSPBGenerateCSR( hSession,
szOutPrivKeyName,
szSubject,
&dwCSRLen,
&pbCSR,
0 );
if( nRet )
{
printf("DSPBGenerateKey : Failed! %d.\n", nRet);
goto clean;
}
/* Importa para o HSM o certificado relacionado a chave privada */
nRet = DSPBImportCertificate (hSession, 0, NULL, pbCertificate, sizeof(pbCertificate), szDomain, 0);
if( nRet ) {
printf("DSPBImportCertificate(no filter) : Failed! %d.\n", nRet);
goto clean;
}
clean:
if( hSession ) {
DCloseSession(&hSession, 0);
}
if( pbCSR ) {
DFree(pbCSR);
}
return nRet;
}