# 加密的字符串长度 [英] Length of Encrypted String

### 问题描述

I need to create a database column which will store a string encrypted using Triple DES. How do I determine the length of the encrypted string column?

（有答案的算法比三重DES等也欢迎。）

(Answers for algorithms other than Triple DES are also welcome.)

### 推荐答案

Block-ciphers such as DES, 3DES and AES can only operate on blocks of bytes. DES and 3DES operate on block of 8 bytes and AES on blocks of 16 bytes.

To handle this, you usually apply a reversible padding to your plaintext before encrypting it. It will mostly always be "PKCS"-padding (also called PKCS5- or PKCS7-padding).

PKCS-填充增加了至少一个字节，使得所述填塞文本的长度整除与块长度（8字节为3DES）。填充字节的值是增加的字节数。 FX。 ABCDEF被填充到ABCDEF0505050505和0011223344556677被填充到0011223344566770808080808080808.请注意，这是很容易去除：你刚才看的填充字节的最后一个字节，验证它是1块长之间，并删除字节数从端（验证每个除去字节具有正确的值）。

PKCS-padding adds at least one byte such that the padded text has a length divisible with the block-length (8 bytes for 3DES). The value of the padding-bytes is the number of bytes added. Fx. ABCDEF is padded to ABCDEF0505050505 and 0011223344556677 is padded to 0011223344566770808080808080808. Note that this is easy to remove: you just look at the final byte of the padded bytes, verify that it is between 1 and the block-length, and remove that number of bytes from the end (verifying that each removed byte has the correct value).

Finally, to answer your question: Assuming you are using 3DES with CBC encryption and PKCS-padding - which you probably are - the encryption of a string of length n will have length:

``````n + 8 - (n % 8)
``````