DER证书读取保存和转换
1 /**读取文本中的内容,返回值需要自己手动释放,utf8,unicode格式的文本读取后需要自己转换*/ 2 char* ReadFileContent(char *filePath, int &contentLen) 3 { 4 FILE *fp = NULL; 5 fopen_s(&fp, filePath, "rb"); 6 assert(fp!=NULL); 7 if (fp == NULL) return NULL; 8 9 fseek(fp, 0, SEEK_END); 10 int isize = ftell(fp); 11 fseek(fp, 0, SEEK_SET); 12 char *buf = (char*)malloc(sizeof(char)*(isize+1)); 13 assert(fp!=NULL); 14 memset(buf, 0, isize+1); 15 16 contentLen = fread(buf, 1, isize, fp); 17 fclose(fp); 18 return buf; 19 } 20 21 /*写文件*/ 22 int WriteContentToFile(char *filePath, char *pContent, int iLen) 23 { 24 assert(filePath!=NULL); 25 assert(pContent!=NULL); 26 assert(iLen>0); 27 28 FILE *fp = NULL; 29 fopen_s(&fp, filePath, "wb");//二进制方式打开 30 assert(fp!=NULL); 31 if (fp == NULL) return NULL; 32 fwrite(pContent, sizeof(char), iLen, fp); 33 fclose(fp); 34 return 1; 35 } 36 37 /**根据X509获取DER编码,返回值需要自己手动释放*/ 38 char* ConvertX509ToDer(X509* pCertx509, int& contentLen) 39 { 40 char *pCertBuf = NULL; 41 char *pTemp = NULL; 42 43 int len = i2d_X509(pCertx509, NULL); 44 pTemp = (char*)malloc(len); 45 memset(pTemp, 0, sizeof(char)*len); 46 47 pCertBuf = pTemp; 48 contentLen = i2d_X509(pCertx509, (unsigned char**)&pTemp); ///<pTemp发生了变化已经是pCertBuf+contentLen 49 return pCertBuf; 50 } 51 52 53 /**读取DER格式文件,并转化为X509格式*/ 54 X509* GetX509FromDer(char *filePath) 55 { 56 int content_length = 0; 57 char* pContent = ReadFileContent(filePath, content_length); 58 char* pTemp = pContent; 59 X509* pCert = d2i_X509(NULL, (const unsigned char**)&pTemp, content_length); 60 if (pContent!=NULL){ 61 free(pContent); 62 pContent = NULL; 63 } 64 return pCert; 65 } 66 67 /**保存为DER格式文件*/ 68 int SaveFileDer(X509* pCert, char *filePath) 69 { 70 int iLen = 0; 71 char *pDerStr = ConvertX509ToDer(pCert, iLen); 72 int iRes = WriteContentToFile(filePath, pDerStr, iLen); 73 74 free(pDerStr); 75 pDerStr = NULL; 76 77 return iRes; 78 } 79 80 81 int main() 82 { 83 X509 *pCert = GetX509FromDer("D:\\derTest.cer"); 84 SaveFileDer(pCert, "D:\\saveTest.cer"); 85 86 X509_free(pCert); 87 return 0; 88 }
文章出处:http://www.cnblogs.com/zhfuliang/archive/2013/05/10/3071139.html