0

Im trying to generate a symmetric key, which i can use to both encrypt and decrypt a message with the same key, in php.

I've made my way through the php documentation below but can only find public/private key generations: http://www.php.net/manual/en/function.openssl-pkey-new.php

Any ideas on how i can use these key generating functions for making a symmetric key?

Thanks, Joe

1
  • There are special functions for generating public/private keypairs because the two keys have a special mathematical relationship to each other, but a symmetric key is ideally just a random number with no mathematical relationship to anything. So you want to look at functions for generating cryptographic-quality random numbers. Commented Feb 23, 2014 at 15:57

2 Answers 2

1

A symetric key is basically a random set of bytes. If you want to use the openssl extension use openssl_random_pseudo_bytes():

$symetric_key = openssl_random_pseudo_bytes($length);
Sign up to request clarification or add additional context in comments.

Comments

0

To generate a symmetric key you can either use random_bytes() (starting from PHP 7) or openssl_random_pseudo_bytes(). Using the OpenSSL extension to crypt data with a symmetric key, you can use openssl_cipher_key_length() to know the required key length.

$cipher = "aes-256-gcm";
$plaintext = "Attack at dawn!";

if (in_array($cipher, openssl_get_cipher_methods())) {
  $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
  $key = openssl_random_pseudo_bytes(openssl_cipher_key_length($cipher));
  $ciphertext = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.