Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top