CryptoAPI 對資料Base64編碼解碼

凝望著發表於2015-02-07

對資料進行Base64編碼解碼

只會用到

1.CryptBinaryToString

2.CryptStringToBinary

函式的引數及引數講解請參考: 點選檢視

#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
#pragma comment(lib,"crypt32.lib")

int main()
{
    BYTE *pbBuffer = (BYTE*)"武漢";
    DWORD dwBufferLen = strlen((char*)pbBuffer);
    char *chBase64Data  = NULL;
    DWORD dwBase64DataLen = 0;
    BYTE *pbOutBuffer = NULL;
    DWORD dwOutBufferLen = 0;
    do 
    {
        if (!CryptBinaryToStringA(pbBuffer,dwBufferLen,CRYPT_STRING_BASE64,NULL,&dwBase64DataLen))
        {
            printf("獲取編碼後的資料長度失敗\n");
            break;
        }

        chBase64Data = (char*)malloc(dwBase64DataLen+1);
        if (chBase64Data!=NULL)
        {
            memset(chBase64Data,0x00,dwBase64DataLen+1);
        }else{
            printf("分配記憶體失敗\n");
            break;
        }

        if (!CryptBinaryToStringA(pbBuffer,dwBufferLen,CRYPT_STRING_BASE64,chBase64Data,&dwBase64DataLen))
        {
            printf("Base64編碼失敗\n");
            break;
        }

        printf("Base64編碼:%s\n",chBase64Data);

        if (!CryptStringToBinaryA(chBase64Data,dwBase64DataLen,CRYPT_STRING_BASE64,NULL,&dwOutBufferLen,NULL,NULL))
        {
            printf("獲取解碼資料長度失敗\n");
            break;
        }

        pbOutBuffer = (BYTE*)malloc(dwOutBufferLen+1);
        if (pbOutBuffer!=NULL)
        {
            memset(pbOutBuffer,0x00,dwOutBufferLen+1);
        }else{
            printf("分配記憶體失敗\n");
            break;
        }

        if (!CryptStringToBinaryA(chBase64Data,dwBase64DataLen,CRYPT_STRING_BASE64,pbOutBuffer,&dwOutBufferLen,NULL,NULL))
        {
            printf("Base64解碼失敗\n");
        }
        printf("Base64解碼%s\n",(char*)pbOutBuffer);
    } while (0);
    if (chBase64Data)
    {
        free(chBase64Data);
        chBase64Data = NULL;
    }
    if (pbOutBuffer)
    {
    free(pbOutBuffer);
    pbOutBuffer = NULL;
    }
    return 0;
}

CryptStringToBinary這個方法的第三個引數有CRYPT_STRING_BASE64HEADER  我一般情況下是用來對一個Base64匯出的證書讀取時用到, 一段數字證書Base64資料開始結尾會存在:

-----BEGIN CERTIFICATE-----和-----END CERTIFICATE-----

傳入CRYPT_STRING_BASE64HEADER會自動過濾掉那兩段資料對證書進行解碼

相關文章