OpenSSL API

/**
 * @file cert_openssl.c
 * @brief 利用openssl api处理证书
 * @author zy
 * @date 2014-10-11 modify
 */
#include 
#include 
#include 
#include 
#define CONTEXT_MAX_NUM 7
#define SERIAL_RAND_BITS 64
/**
* 描  述: 获取X509对象
* 参  数: @param[IN] cert_file  证书
* 返回值: X509对象
*/
X509* read_public_cert(const char* cert_file)
{
    X509 *x509 = NULL;
    
    FILE *fp = fopen (cert_file, "r");   
    if(!fp)
    {
        printf("read_public_cert, open cert failed!");
        return NULL; 
    }
    x509 = PEM_read_X509(fp, NULL, 0, NULL);
    if(x509 == NULL) 
    {  
        printf("read_public_cert, get x509 failed!");
        return NULL;   
    }
    return x509;
}
/**
* 描  述: 获取公钥
* 参  数: @param[IN] cert_file  证书
* 返回值: 公钥
*/
EVP_PKEY * read_public_key(const char* cert_file)
{
    X509 *x509 = NULL;
    EVP_PKEY *pkey = NULL;
    FILE *fp = fopen (cert_file, "r");   
    if(!fp)
    {
        printf("read_public_key, open cert failed!");
        return NULL;
    }
    x509 = PEM_read_X509(fp, NULL, 0, NULL);
    if(x509 == NULL) 
    {  
        printf("read_public_key, get x509 failed!");
        return NULL;   
    }
    fclose(fp);
    pkey = X509_extract_key(x509);
    X509_free(x509);
    if(pkey == NULL)
    {
        printf("read_public_key, get key failed!");
    }
    return pkey; 
}
/**
* 描  述: 获取私钥
* 参  数: @param[IN] key_file  证书
* 返回值: 私钥
*/
EVP_PKEY *read_private_key(const char* key_file)
{
    EVP_PKEY *pkey = NULL;
    
    FILE *fp = fopen(key_file, "r");
    if(!fp)
    {
        printf("read_private_key, open key failed!");
        return NULL;
    }
    pkey = PEM_read_PrivateKey(fp, NULL, 0, NULL);
    fclose(fp);
    if (pkey == NULL)
    {
        printf("read_private_key, get key failed!");
    }
    return pkey;
}
/**
* 描  述: 添加证书内容
* 参  数: @param[IN] name  X509_NAME
          @param[IN] ctx   使用者信息
          @param[IN] num   ctx数组长度
* 返回值: 1: 成功 0: 失败
*/
int add_cert_ctx(X509_NAME* name, char* ctx[], int num)
{
    int i = 0;
    int max = 0;
    int item[] = {NID_commonName, NID_countryName,
        NID_stateOrProvinceName, NID_localityName, 
        NID_organizationName, NID_organizationalUnitName,
        NID_pkcs9_emailAddress};
    max = sizeof(item)/sizeof(item[0]);
    max = max > num ? num : max;
    for(i=0; i 
			
				#include
			
				#include
			
				#include
			
				#include
			
				#include
			
			
				void hexprint(char *str,int len)
			
				{
			
				    int i=0;
			
				    for(i=0;i

 

你可能感兴趣的:(openssl)