在C++中将 PEM 转换为 DER
Converting PEM to DER in C++
我有一个PEM格式的证书,我想在C++中使用OpenSLL函数将其转换为DER格式。
我该怎么做?
谢谢。
你可以
这样做 -
#include <stdio.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/err.h>
void convert(char* cert_filestr,char* certificateFile)
{
X509* x509 = NULL;
FILE* fd = NULL,*fl = NULL;
fl = fopen(cert_filestr,"rb");
if(fl)
{
fd = fopen(certificateFile,"w+");
if(fd)
{
x509 = PEM_read_X509(fl,&x509,NULL,NULL);
if(x509)
{
i2d_X509_fp(fd, x509);
}
else
{
printf("failed to parse to X509 from fl");
}
fclose(fd);
}
else
{
printf("can't open fd");
}
fclose(fl);
}
else
{
printf("can't open f");
}
}
int main()
{
convert("abc.pem","axc.der");
return 0;
}
您可以在不使用OpenSSL函数的情况下执行此操作。试试这个——
int CertConv_pem2der(const uint8_t *pem, uint32_t plen, uint8_t **der,
uint32_t *dlen)
{
int value = 0;
int i;
int j;
int padZero = 0;
uint8_t *derPtr;
uint32_t derLen;
if ((pem == NULL) || (der == NULL))
{
return (-1);
}
for (i = plen; pem[i - 1] == '='; i--)
{
padZero++;
}
/* Base64 decode: 4 characters to 3 bytes */
derLen = (plen / 4) * 3;
derPtr = (uint8_t *) malloc(derLen);
if (!derPtr)
{
return (-1);
}
for (i = 0, j = 0; (i + 3) < plen && (j + 2) < derLen; i += 4, j += 3)
{
value = (base64Decode(pem[i]) << 18) + (base64Decode(pem[i + 1]) << 12)
+ (base64Decode(pem[i + 2]) << 6) + base64Decode(pem[i + 3]);
derPtr[j] = (value >> 16) & 0xFF;
derPtr[j + 1] = (value >> 8) & 0xFF;
derPtr[j + 2] = value & 0xFF;
}
/* Actual length of buffer filled */
*dlen = derLen - padZero;
*der = derPtr;
return (0);
}
static uint8_t base64Decode(uint8_t ch)
{
uint8_t ret = 0;
if (ch >= 'A' && ch <= 'Z')
{
ret = ch - 'A';
}
else if (ch >= 'a' && ch <= 'z')
{
ret = ch - 'a' + 26;
}
else if (ch >= '0' && ch <= '9')
{
ret = ch - '0' + 52;
}
else if (ch == '+')
{
ret = 62;
}
else if (ch == '/')
{
ret = 63;
}
return (ret);
}
试试这个 -
void convert(const unsigned char * pem_string_cert,char* certificateFile)
{
X509* x509 = NULL;
FILE* fd = NULL;
BIO *bio;
bio = BIO_new(BIO_s_mem());
BIO_puts(bio, pem_string_cert);
x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
fd = fopen(certificateFile,"w+");
if(fd)
{
i2d_X509_fp(fd, x509);
}
else
{
printf("can't open fd");
}
fclose(fd);
}
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 复制列表初始化的隐式转换的等级是多少
- 正在将指针转换为范围
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 在C++中将 PEM 转换为 DER
- 将DER编码的X509证书缓冲区转换为Windows cert_context结构
- 如何在 openSSL 中将 DER 编码字符串的向量转换为 x509
- 在 Windows CE 3 上将 PEM 转换为 DER