4

I need to generate symmetrics keys with standard AES in ECB mode block and with PKCS5Padding, but I can't do it.

During my searches, I only found functions to encrypt something with this conditions above. But I don't want this; I want to generate a symmetric key.

I need to can communicate with a webservice and I need this, because is one part of encryption.

I have looked at phpseclib, but the library doesn't generate symmetric keys either.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Ricardo Martins
  • 486
  • 7
  • 19

3 Answers3

5

First, to do PKCS#5 padding on the input you need to improvise:

// source: http://php.net/manual/en/ref.mcrypt.php#69782
function pkcs5_pad($text, $blocksize) 
{
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}

Then select your algorithm and generate the IV:

$alg = MCRYPT_RIJNDAEL_128; // AES
$mode = MCRYPT_MODE_ECB; // not recommended unless used with OTP

$iv_size = mcrypt_get_iv_size($alg, $mode);
$block_size = mcrypt_get_block_size($alg, $mode);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM); // pull from /dev/urandom

Initialize your encryption key:

$key = "This is a very secret key";

Apply padding to the input and encrypt it

$input = pkcs5_pad($input, $block_size);

$crypttext = mcrypt_encrypt($alg, $key, $input, $mode, $iv);
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • Jack, i've already used this, the problem it's i've to generate a different symmetric key in every request to webservice, so the key to encrypt ("This is a very secret key") could be a string compose with system date and username, for example? – Ricardo Martins Dec 28 '12 at 14:19
  • @RicardoMartins Well, it could, but normally the secret key is something that's known to both sides ... so if you have a special algorithm to make sure that both system dates are the same, then yes, you could do that. – Ja͢ck Dec 28 '12 at 14:24
1

In php I have used this to create a symmetric key.

<?php
srand((double)microtime()*1000000 );
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CFB, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$ks = mcrypt_enc_get_key_size($td);
$key = substr(sha1('Your Secret Key Here'), 0, $ks);

mcrypt_generic_init($td, $key, $iv);
$ciphertext = mcrypt_generic($td, 'This is very important data');
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

print $iv . "\n";
print trim($ciphertext) . "\n";
?>

This would be a good starting place : http://php.net/manual/en/function.mcrypt-create-iv.php

ROY Finley
  • 1,406
  • 1
  • 9
  • 18
1

You can do this with a call to the phpseclib library, which can be adjusted to any cipher (AES, DES..), encryption mode, key length and optional PBKDF2 derivation. Please see: http://phpseclib.sourceforge.net/crypt/examples.html

neid
  • 315
  • 1
  • 4
  • 12