您好,登錄后才能下訂單哦!
這篇文章給大家介紹基于mbedtls-1.3.14庫的aes加解密以及base64編碼與解碼用法是什么,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
aes加密,base64輸出
void AesEncryptAndOutBase64(const unsigned char *InBuf,int InBufLen,const unsigned char *AesKey,unsigned char *OutBuf) { unsigned char iv[IV_SIZE] = {0}; memcpy(iv,AesKey,IV_SIZE); aes_context aes_enc; aes_init(&aes_enc); unsigned char pt_buf[8000] = {0}; int i = 0; for(i; i < InBufLen; i++) { pt_buf[i] = InBuf[i]; } //不夠16字節的剩余部分,填充 int index = InBufLen; int pading = 16 - (index % 16); for(i = 0; i < pading; i++) { pt_buf[index + i] = pading; } int ret = -1; ret = aes_setkey_enc(&aes_enc,AesKey,AES_KEY_SIZE); if (ret != 0) { DEBUG_INFO("set aes key failed,ret=%d",ret); return; } ret = aes_crypt_cbc(&aes_enc,AES_ENCRYPT,index+pading,iv,pt_buf,pt_buf); if (ret != 0) { DEBUG_INFO("aes cbc en failed,ret=%d",ret); return; } #if 1 printf("aes en after:"); for(i = 0; i < index + pading; i++) { printf("%02x",pt_buf[i]); } printf("\n"); #endif size_t n = 0; //第一個參數為NULL,表示獲取密文長度 base64_encode(NULL,&n,pt_buf,index + pading); //第二次真正解碼 ret = base64_encode(OutBuf,&n,pt_buf,index + pading); if (ret != 0) { DEBUG_INFO("baae64 encode failed,ret=%d",ret); return; } DEBUG_INFO("aes en,base64 encode out:%s",OutBuf); }
base解碼,aes解密
int DecryptBas64Aes(const unsigned char *Base64 ,const unsigned char* AesKey , unsigned char * OutBuf) { size_t n = 0; int ret = -1; unsigned char base64_de_out[8000] = {0}; //第一個參數為NULL,表示獲取密文長度 base64_decode(NULL,&n,Base64,strlen(Base64)); //第二次真正解碼 ret = base64_decode(base64_de_out,&n,Base64,strlen(Base64)); if (ret != 0) { DEBUG_INFO("base de failed,ret=%d",ret); return -1; } #if 1 DEBUG_INFO("base de after:"); int i = 0; for(i = 0; i < n; i++) { printf("%02x",base64_de_out[i]); } printf("\n"); #endif unsigned char iv[IV_SIZE] = {0}; memcpy(iv,AesKey,IV_SIZE); aes_context aes_dec; aes_init(&aes_dec); ret = aes_setkey_dec(&aes_dec,AesKey,AES_KEY_SIZE); if (ret != 0) { DEBUG_INFO("set aes key dec failed,ret=%d",ret); return -1; } //aes解密 ret = aes_crypt_cbc(&aes_dec,AES_DECRYPT,n,iv,base64_de_out,OutBuf); if (ret != 0) { DEBUG_INFO("aes en failed,ret=%d",ret); return -1; } //有時解密失敗,會導致填充部分的index異常(大于整個數組長度,或者小于0),為了防止數組越界,這里作一下判斷 if(OutBuf[n-1] > n || OutBuf[n-1] < 0) { OutBuf[0]='\0'; return -1; } //最后一個字符填充'\0',不然用strcmp不能比較 int Num = n-OutBuf[n-1]; OutBuf[Num]='\0'; DEBUG_INFO("aes de %s",OutBuf); return Num; }
測試
void TestAes(void) { char AesKey[17] = {"1234567887654321"}; char *InBuf = "abcdef明文"; char EnOutBuf[1024] = {0}; char DeOutBuf[1024] = {0}; AesEncryptAndOutBase64(InBuf,strlen(InBuf),AesKey,EnOutBuf); DecryptBas64Aes(EnOutBuf,AesKey,DeOutBuf); DEBUG_INFO("%s",DeOutBuf); }
int main(void) { TestAes(); return 0; }
關于基于mbedtls-1.3.14庫的aes加解密以及base64編碼與解碼用法是什么就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。