How to securely handle AES “Key” and “IV” values

后端 未结 5 1722
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 20:50

If I use AES (System.Security.Cryptography) to simply encrypt and decrypt blob or memo fields in a SQL server, then where do I store the “Key” and “IV” values on the server?

5条回答
  •  -上瘾入骨i
    2020-12-07 21:25

    Rules of thumb are:

    • Key must be secret at all times (must not be anywhere near the database)
    • IV must be different for each record.
    • IV must be "indistinguishable from random" and unpredictable, preferably it must come from the same source as your AES keys; other option is to encrypt some value (different for each record) with a secret key.
    • IV needs not to be secret

    Hence, one scheme you can use is:

    1. Create a table with fields ID (unique, int), IV (unique, 16 bytes), Encrypted(variable bytes, NULLable)
    2. To write a new record into the database, create new unique IV and create a new record in the database with empty encrypted data (to prevent collisions)
    3. Encrypt the data with your secret key and IV from step 2 (CBC or CTR mode - CTR is better) and update the record.

    Step two may be performed by taking the IV from previous record and encrypting it with the same secret key - AES's properties will make this an effectively random IV.

    This will be as secure as you can get with AES - meaning CCA/CPA secure. The only thing it does not prevent is tampering

提交回复
热议问题