使用openssl完成aes-cbc模式的数据加解密,输入和输出都是字符串的形式
生活随笔
收集整理的這篇文章主要介紹了
使用openssl完成aes-cbc模式的数据加解密,输入和输出都是字符串的形式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼
#include <cstring> #include <memory>#include <openssl/aes.h> #include <openssl/md5.h>namespace hsm{namespace mgmt{void get_md5_digest(const std::string &data,uint8_t result[16]){MD5_CTX md5_ctx{};MD5_Init(&md5_ctx);MD5_Update(&md5_ctx,data.c_str(),data.length());MD5_Final(result,&md5_ctx);} /*** @brief generate a valid aes key from input password** @note AES only support keys with length 128/192/256bits* @note this implementation use md5 as a method to fix the password*/std::unique_ptr<AES_KEY> get_aes_key(const std::string &password,int flag){auto aes_key = std::make_unique<AES_KEY>();uint8_t data[16]{};get_md5_digest(password,data);if (flag == AES_ENCRYPT){AES_set_encrypt_key(data,sizeof(data)*8,aes_key.get());} else if (flag == AES_DECRYPT){AES_set_decrypt_key(data,sizeof(data)*8,aes_key.get());}return aes_key;}std::string aes_cbc_encrypt_to_string(const std::string &data,const std::string &password){unsigned char buffer[AES_BLOCK_SIZE] = {0};auto aes_key = get_aes_key(password,AES_ENCRYPT);std::string result(data.length(),'0');auto input_offset = reinterpret_cast<const uint8_t *>(data.c_str());auto output_offset = reinterpret_cast<uint8_t *>(&result[0]);//encrypt blocksfor (size_t i = 0;i < 16;i++){buffer[i] += 1;}AES_cbc_encrypt(input_offset,output_offset,data.length(),aes_key.get(),buffer,AES_ENCRYPT);return result;}std::string aes_cbc_decrypt_from_string(const std::string &enc_data,const std::string &password){unsigned char buffer[AES_BLOCK_SIZE] = {0};auto aes_key = get_aes_key(password,AES_DECRYPT);std::string result(enc_data.length(),'0');auto input_offset = reinterpret_cast<const uint8_t *>(enc_data.c_str());auto output_offset = reinterpret_cast<uint8_t *>(&result[0]);for (size_t i = 0;i < 16;i++){buffer[i] += 1;}AES_cbc_encrypt(input_offset,output_offset,enc_data.length(),aes_key.get(),buffer,AES_DECRYPT);return result;}}//namespace mgmt }//namespace hsm注意事項
?
- 在CBC中,每個明文塊要先與前一個密文塊進行異或后再加密,每個密文塊都依賴于前面的所有明文塊。
- 那么問題又來了:第一個明文塊怎么辦?這個時候就要用到IV了。因此上面代碼for循環是為了給第一塊明文初始化,使其數據保持一致
- 在CBC中,IV先與第一個明文塊進行異或,得到第一個明文塊,然后再進行后續的加密。詳見下圖:
?
參考鏈接
- Openssl Aes加解密使用示例
- AES加密(3):AES加密模式與填充
- OpenSSL中AES加密的用法
- OpenSSL參考文檔
- openssl使用指南
總結
以上是生活随笔為你收集整理的使用openssl完成aes-cbc模式的数据加解密,输入和输出都是字符串的形式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 英语口语小组PPT--袁隆平
- 下一篇: 清除Docker的占用空间问题