How to securely generate an IV for AES CBC Encryption?

后端 未结 3 471
自闭症患者
自闭症患者 2021-01-11 16:39

I work on some crypto stuff.

  • I use AES 256 with CBC mode
  • I use OPENSSL

I am aware of the following things (source = wikipedia):

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-11 17:05

    You can use openssl_random_pseudo_bytes(len, &crypto_stron).

    The first parameter is the length you want in bytes. If you are using this for use in one of the open ssl methods, you can use the function openssl_cipher_iv_length(method) to get the correct length for the method used.

    The second parameter, &crypto_strong, allows you to pass in a boolean variable that will be set to true or false depending on whether the algorithm used was cryptographically secure. You can then check this variable and handle it properly if the variable comes back false. It should never happen, but if it does then you will probably want to know.

    Here is an example of proper usage:

    $method = 'aes-256-cbc';
    $ivlen = openssl_cipher_iv_length($method);
    $isCryptoStrong = false; // Will be set to true by the function if the algorithm used was cryptographically secure
    $iv = openssl_random_pseudo_bytes($ivlen, $isCryptoStrong);
    if(!$isCryptoStrong)
        throw new Exception("Non-cryptographically strong algorithm used for iv generation. This IV is not safe to use.");
    

    For more information see:

    • http://php.net/manual/en/function.openssl-random-pseudo-bytes.php
    • http://php.net/manual/en/function.openssl-cipher-iv-length.php
    • http://php.net/manual/en/function.openssl-get-cipher-methods.php

提交回复
热议问题