Frage

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())

War es hilfreich?

Lösung

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.

Andere Tipps

  • Warning reason: You are returning a pointer to a local array. It's wrong because the local variable will deleted after exiting the function.

  • Error reason: Compiler expected you return a byte value, but you are returning a pointer.

Try this:

void AESBest::gen_key(byte *key, int size)
{
  AutoSeededRandomPool prng;
  prng.GenerateBlock(key, size);
}

and call it like below:

byte key[AES::MAX_KEYLENGTH];
gen_key(key, AES::MAX_KEYLENGTH);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top