3

Inside of my migration I have a string column named encryption_key which looks like this:

$table->string('encryption_key')->unique();

I have a Controller that uses a trait to generate the encryption commands.

use LiveChat;

public function create()
{
    $this->header->insert([
        'encryption_key' => $this->issueKey()
    ]);

    $this->participants->insert([
        'chat_id' => DB::getPdo()->lastInsertId(),
        'user_id' => Auth::id()
    ]);

    return response(['status' => true, 'chat_id' => DB::getPdo()->lastInsertId()], 200)
        ->header('Content-Type', 'application/json');
}

The trait looks like this so far

trait LiveChat
{
    protected function issueKey()
    {
        return random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
    }
}

However, upon testing this I receive this error:

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect string value: '\xFFX\x8Af\x1F$...' for column 'encryption_key' at row 1 (SQL: insert into chat_headers (encryption_key) values (ÿXŠf\x1F$¨ì™ÒÂø¢Ú!£”…¸ÈÍØ7ÿDå\x00Œ¿3ê))

If I use dd() to debug the response of $this->issueKey() I get something like this:

b"Bp,[\x1A\¢®ù·š(×g6ùs=l«j,©;_ó8ýòúÍ6"

I have tried to use iconv() like so

iconv("UTF-8", "ASCII", $this->issueKey())

Which gives me

iconv(): Detected an illegal character in input string

How can I store this key to use for future reference inside my DB?

Jaquarh
  • 6,493
  • 7
  • 34
  • 86
  • 1
    `base64_encode` it. Use `base64_decode` when you access it from the database. A mutator/accessor function (see the docs) may be useful for this. – ceejayoz Jan 29 '19 at 18:18
  • You are a star! I didn't think about using `base64_*` - which makes sense to do so. If you want to place an answer, I'll mark it as accepted @ceejayoz – Jaquarh Jan 29 '19 at 18:20
  • 1
    or you could bin2hex(random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES)); – gview Jan 29 '19 at 18:20

1 Answers1

3

You can base64_encode it for storage, and undo it with base64_decode.

Putting together a set of accessor and mutator functions will let you do this in an automatic fashion.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368