首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >AES128加密库加密输出垃圾

AES128加密库加密输出垃圾
EN

Stack Overflow用户
提问于 2018-12-13 03:09:08
回答 1查看 183关注 0票数 0

我正在使用这个已解决的帖子作为参考,但似乎无法获得相同的结果:AES128 in libgcrypt not encrypting

当我将字符串打印到控制台时,我得到了垃圾字符。我认为这可能是由于'\0'在字符串中,但我不确定如何去做。

//aes.cpp

代码语言:javascript
复制
#include "aes.h"
#include <iostream>
#include <stdio.h>

#define GCRY_CIPHER GCRY_CIPHER_AES128   // Pick the cipher here
#define GCRY_MODE GCRY_CIPHER_MODE_ECB // Pick the cipher mode here

aes::aes(std::string k)
{
    key_ = k;
    keyLength_ = gcry_cipher_get_algo_keylen(GCRY_CIPHER);

    gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
    gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
    gcry_cipher_open(&handle, GCRY_CIPHER, GCRY_MODE, 0);
    gcry_cipher_setkey(handle, key_.c_str(), keyLength_);
}

void aes::encrypt(string text, std::vector<char>& ret) {
    size_t textLength = text.size() + 1;
    ret.resize(textLength);
    gcry_cipher_encrypt(handle, ret.data(), textLength, text.c_str(), textLength);
}

string aes::decrypt(std::vector<char> const& text) {
    size_t textLength = text.size() + 1;


    char * decBuffer = new char[textLength];
    gcry_cipher_decrypt(handle, decBuffer, textLength, text.data(), textLength);
    string ret (decBuffer);
    delete [] decBuffer;
    return ret;
}

//aes.h

代码语言:javascript
复制
#include <gcrypt.h>
#include <iostream>

#ifndef AES_H
#define AES_H

class aes
{
public:
    aes(std::string);
    ~aes();

    gcry_cipher_hd_t handle;
    void encrypt(std::string, std::vector<char>&);
    std::string decrypt(std::vector<char> const&); 

private:
    std::string key_;
    size_t keyLength_; 
};

#endif // AES_H

//main.cpp

代码语言:javascript
复制
#include "aes.h"
#include <iostream>

int main()
{
    std::vector<char> data;

    aes bb = aes("one test AES key");
    bb.encrypt("Some message", data);

    std::string dec = bb.decrypt(data);
    std::cout << "decrypted string " << dec << std::endl;
    return 0;
    //output gives me: decrypted string �

}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53749797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档