I'm using Crypto++ to encrypt string with AES. Ok it works fine, but now I want to create a function that return a byte value that is the key.
byte AESBest::gen_key()
{
AutoSeededRandomPool prng;
// warning: address of local variable ‘key’ returned [enabled by default]
byte key[AES::MAX_KEYLENGTH];
prng.GenerateBlock(key, sizeof(key));
//Error: invalid conversion from ‘byte {aka unsigned char}’ to ‘const byte* {aka const unsigned char*}’ [-fpermissive] }
return key;
}
Well. I cannot return the key because something is not clear. When I set byte key[AES::MAX_KEYLENGTH]
eclipse show me the warning that seems to be returned.
But when in the end return key, there is a strange error about the invalid conversion.
Why happen this?
How can I solve this problem?
EDIT: Well. Now I have these 2 function. But the first works good, returning the 64 chars of the aes key. (gen_all)
The second - I dunno why - return just 4! Why? (gen_part)
string AESBest::gen_all()
{
AutoSeededRandomPool prng;
byte key[AES::MAX_KEYLENGTH];
prng.GenerateBlock(key, sizeof(key));
string encoded;
encoded.clear();
StringSource(key, sizeof(key), true,
new HexEncoder(
new StringSink(encoded)
)
);
return encoded;
}
And:
string AESBest::gen_part()
{
AutoSeededRandomPool prng;
std::vector<byte> key(AES::MAX_KEYLENGTH);
prng.GenerateBlock(key.data(), key.size());
string encoded;
encoded.clear();
StringSource(key.data(), sizeof(key.size()), true,
new HexEncoder(
new StringSink(encoded)
)
);
return encoded;
}
Where is the bug in the second one?
EDIT: nevermind! The bug was in sizeof
, so key.size() NO sizeof(key.size())
You cannot return raw arrays in C++ (nor can you pass them as function arguments by value). Instead, use a std::vector<byte>
:
std::vector<byte> key(AES::MAX_KEYLENGTH);
prng.GenerateBlock(key.data(), key.size());
return key;
You'll have to modify the function return type accordingly. Use key.data()
or &key[0]
to get a pointer to the underlying data array.