表 14.18 加密函数Table 14.18 Encryption Functions
| 名称Name | 说明Description |
|---|---|
AES_DECRYPT() |
使用 AES 解密Decrypt using AES |
AES_ENCRYPT() |
使用 AES 加密Encrypt using AES |
COMPRESS()COMPRESS() |
将结果作为二进制字符串返回Return result as a binary string |
MD5() |
计算 MD5 校验和Calculate MD5 checksum |
RANDOM_BYTES() |
返回一个随机字节向量Return a random byte vector |
SHA1(), SHA() |
计算 SHA-1 160 位校验和Calculate an SHA-1 160-bit checksum |
SHA2() |
计算 SHA-2 校验和Calculate an SHA-2 checksum |
STATEMENT_DIGEST() |
计算语句摘要哈希值Compute statement digest hash value |
STATEMENT_DIGEST_TEXT() |
计算归一化语句摘要Compute normalized statement digest |
UNCOMPRESS() |
解压缩已压缩的字符串Uncompress a string compressed |
UNCOMPRESSED_LENGTH() |
返回压缩前字符串的长度Return the length of a string before compression |
VALIDATE_PASSWORD_STRENGTH() |
确定密码强度Determine strength of password |
许多加密和压缩函数返回的字符串可能包含任意字节值。如果您想存储这些结果,请使用带有 VARBINARY 或 BLOB 二进制字符串数据类型的列。这可以避免由于使用非二进制字符串数据类型(CHAR、VARCHAR、TEXT)而可能发生的尾部空格移除或字符集转换从而改变数据值的问题。Many encryption and compression functions return strings for which
the result might contain arbitrary byte values. If you want to
store these results, use a column with a
VARBINARY or
BLOB binary string data type. This
avoids potential problems with trailing space removal or character
set conversion that would change data values, such as may occur if
you use a nonbinary string data type
(CHAR,
VARCHAR,
TEXT).
一些加密函数会返回 ASCII 字符串:MD5(),SHA(),SHA1(),SHA2(),STATEMENT_DIGEST(),STATEMENT_DIGEST_TEXT()。它们的返回值是一个字符串,其字符集和校对规则由系统变量 character_set_connection 和 collation_connection 决定。除非字符集是 binary,否则这是一个非二进制字符串。Some encryption functions return strings of ASCII characters:
MD5(),
SHA(),
SHA1(),
SHA2(),
STATEMENT_DIGEST(),
STATEMENT_DIGEST_TEXT(). Their
return value is a string that has a character set and collation
determined by the
character_set_connection and
collation_connection system
variables. This is a nonbinary string unless the character set is
binary.
If an application stores values from a function such as
MD5()或者SHA1() that returns a string of hex
digits, more efficient storage and comparisons can be obtained by
converting the hex representation to binary using
UNHEX() and storing the result in a
BINARY(
column. Each pair of hexadecimal digits requires one byte in
binary form, so the value of N)N depends
on the length of the hex string. N is
16 for an MD5() value and 20 for a
SHA1() value. For
SHA2(),
N ranges from 28 to 32 depending on the
argument specifying the desired bit length of the result.If an application stores values from a function such as
MD5() or
SHA1() that returns a string of hex
digits, more efficient storage and comparisons can be obtained by
converting the hex representation to binary using
UNHEX() and storing the result in a
BINARY(
column. Each pair of hexadecimal digits requires one byte in
binary form, so the value of N)N depends
on the length of the hex string. N is
16 for an MD5() value and 20 for a
SHA1() value. For
SHA2(),
N ranges from 28 to 32 depending on the
argument specifying the desired bit length of the result.
在 CHAR 列中存储十六进制字符串的空间代价至少是两倍,如果值存储在使用 utf8mb4 字符集的列中(每个字符使用 4 字节),代价可能高达八倍。存储该字符串还会导致比较操作变慢,因为值更大,并且需要考虑字符集校对规则。The size penalty for storing the hex string in a
CHAR column is at least two times,
up to eight times if the value is stored in a column that uses the
utf8mb4 character set (where each character
uses 4 bytes). Storing the string also results in slower
comparisons because of the larger values and the need to take
character set collation rules into account.
假设一个应用在 CHAR(32) 列中存储 MD5() 字符串值:Suppose that an application stores
MD5() string values in a
CHAR(32) column:
CREATE TABLE md5_tbl (md5_val CHAR(32), ...);
INSERT INTO md5_tbl (md5_val, ...) VALUES(MD5('abcdef'), ...);
要将十六进制字符串转换为更紧凑的形式,请修改应用程序以使用 UNHEX() 和 BINARY(16),操作如下:To convert hex strings to more compact form, modify the
application to use UNHEX() and
BINARY(16) instead as follows:
CREATE TABLE md5_tbl (md5_val BINARY(16), ...);
INSERT INTO md5_tbl (md5_val, ...) VALUES(UNHEX(MD5('abcdef')), ...);
应用程序应该准备好处理哈希函数对两个不同输入值产生相同值的极少数情况。使碰撞可检测的一种方法是将哈希列设置为主键。Applications should be prepared to handle the very rare case that a hashing function produces the same value for two different input values. One way to make collisions detectable is to make the hash column a primary key.
针对 MD5 和 SHA-1 算法的漏洞已被公开。您可能希望考虑使用本节中描述的另一种单向加密函数,例如 SHA2()。Exploits for the MD5 and SHA-1 algorithms have become known. You
may wish to consider using another one-way encryption function
described in this section instead, such as
SHA2().
作为加密函数参数提供的密码或其他敏感值将以明文形式发送到 MySQL 服务器,除非使用 SSL 连接。此外,这些值也会出现在它们被写入的任何 MySQL 日志中。为了避免此类暴露,应用程序可以在将敏感值发送到服务器之前,在客户端进行加密。相同的考虑也适用于加密密钥。为了避免泄露,加密应用程序可以使用存储过程在服务器端加密和解密值。Passwords or other sensitive values supplied as arguments to encryption functions are sent as cleartext to the MySQL server unless an SSL connection is used. Also, such values appear in any MySQL logs to which they are written. To avoid these types of exposure, applications can encrypt sensitive values on the client side before sending them to the server. The same considerations apply to encryption keys. To avoid exposing these, applications can use stored procedures to encrypt and decrypt values on the server side.
AES_DECRYPT(crypt_str,key_str[,init_vector][,kdf_name][,salt][,info | iterations])此函数使用官方的 AES(高级加密标准)算法解密数据。有关更多信息,请参阅
AES_ENCRYPT()的描述。This function decrypts data using the official AES (Advanced Encryption Standard) algorithm. For more information, see the description ofAES_ENCRYPT().使用
AES_DECRYPT()的语句对于基于语句的复制是不安全的。Statements that useAES_DECRYPT()are unsafe for statement-based replication.AES_ENCRYPT(str,key_str[,init_vector][,kdf_name][,salt][,info | iterations])AES_ENCRYPT()和AES_DECRYPT()实现了使用官方 AES(高级加密标准)算法的数据加密和解密,该算法以前被称为 “Rijndael.” AES 标准允许使用不同的密钥长度。默认情况下,这些函数使用 128 位密钥长度实现 AES。之后将描述可以使用 196 或 256 位的密钥长度。密钥长度是在性能和安全性之间的权衡。AES_ENCRYPT()andAES_DECRYPT()implement encryption and decryption of data using the official AES (Advanced Encryption Standard) algorithm, previously known as “Rijndael.” The AES standard permits various key lengths. By default these functions implement AES with a 128-bit key length. Key lengths of 196 or 256 bits can be used, as described later. The key length is a trade off between performance and security.AES_ENCRYPT()使用密钥字符串key_str对字符串str进行加密,并返回一个包含加密结果的二进制字符串。AES_DECRYPT()使用密钥字符串key_str对加密字符串crypt_str进行解密,并以十六进制格式返回原始(二进制)字符串。(要将结果作为明文字符串获取,请将结果转换为CHAR。或者,使用 mysql 客户端启动时加上--skip-binary-as-hex,以便所有二进制值以文本形式显示。)如果任一函数参数为NULL,函数返回NULL。如果AES_DECRYPT()检测到数据无效或填充不正确,它会返回NULL。然而,如果输入数据或密钥无效,AES_DECRYPT()也可能返回非NULL的值(可能是垃圾数据)。AES_ENCRYPT()encrypts the stringstrusing the key stringkey_str, and returns a binary string containing the encrypted output.AES_DECRYPT()decrypts the encrypted stringcrypt_strusing the key stringkey_str, and returns the original (binary) string in hexadecimal format. (To obtain the string as plaintext, cast the result toCHAR. Alternatively, start the mysql client with--skip-binary-as-hexto cause all binary values to be displayed as text.) If either function argument isNULL, the function returnsNULL. IfAES_DECRYPT()detects invalid data or incorrect padding, it returnsNULL. However, it is possible forAES_DECRYPT()to return a non-NULLvalue (possibly garbage) if the input data or the key is invalid.这些函数支持使用密钥派生函数(KDF)从传入的
key_str信息中创建一个加密强度的秘密密钥。派生的密钥用于加密和解密数据,它会保留在 MySQL 服务器实例中,用户无法访问。强烈建议使用 KDF,因为相比在函数中使用自己预先生成的密钥或通过更简单的方法派生密钥,它提供了更好的安全性。该函数支持 HKDF(从 OpenSSL 1.1.0 起可用),您可以为其指定可选的盐值和上下文特定信息以包含在密钥材料中;也支持 PBKDF2(从 OpenSSL 1.0.2 起可用),您可以为其指定可选的盐值并设置生成密钥时使用的迭代次数。These functions support the use of a key derivation function (KDF) to create a cryptographically strong secret key from the information passed inkey_str. The derived key is used to encrypt and decrypt the data, and it remains in the MySQL Server instance and is not accessible to users. Using a KDF is highly recommended, as it provides better security than specifying your own premade key or deriving it by a simpler method as you use the function. The functions support HKDF (available from OpenSSL 1.1.0), for which you can specify an optional salt and context-specific information to include in the keying material, and PBKDF2 (available from OpenSSL 1.0.2), for which you can specify an optional salt and set the number of iterations used to produce the key.如果不使用 KDF,密钥大小应小于 16 字节。
AES_ENCRYPT()在不使用 KDF 时默认执行以下操作:If you do not use a KDF, the key size should be less than 16 bytes.AES_ENCRYPT()does the following by default when a KDF is not used:将完整的 16 字节密钥设置为 0。Sets the full 16-byte key to 0s.
将提供的密钥与内部密钥进行异或运算,只要有数据就继续。XORs the supplied key into the internal key for as long as there is data.
如果提供的密钥比所需密钥长,它将从结果密钥的开头重新循环,并继续进行异或运算,直到提供的密钥中的数据用完。If the supplied key is longer than the required key, it wraps around at the start of the result key and keeps XORing until there is data in the supplied key.
AES_ENCRYPT()和AES_DECRYPT()允许控制块加密模式。block_encryption_mode系统变量控制基于块的加密算法的模式。其默认值为aes-128-ecb,表示使用 128 位密钥和 ECB 模式进行加密。如需了解此变量允许值的说明,请参见 第 7.1.8 节,“服务器系统变量”。可选的init_vector参数用于为需要它的块加密模式提供初始化向量。AES_ENCRYPT()andAES_DECRYPT()permit control of the block encryption mode. Theblock_encryption_modesystem variable controls the mode for block-based encryption algorithms. Its default value isaes-128-ecb, which signifies encryption using a key length of 128 bits and ECB mode. For a description of the permitted values of this variable, see Section 7.1.8, “Server System Variables”. The optionalinit_vectorargument is used to provide an initialization vector for block encryption modes that require it.使用
AES_ENCRYPT()或AES_DECRYPT()的语句对于基于语句的复制是不安全的。Statements that useAES_ENCRYPT()orAES_DECRYPT()are unsafe for statement-based replication.如果从 mysql 客户端中调用
AES_ENCRYPT(),二进制字符串会根据--binary-as-hex的值以十六进制形式显示。如需了解该选项的更多信息,请参见 第 6.5.1 节,“mysql — MySQL 命令行客户端”。IfAES_ENCRYPT()is invoked from within the mysql client, binary strings display using hexadecimal notation, depending on the value of the--binary-as-hex. For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client”.以下是
AES_ENCRYPT()和AES_DECRYPT()函数的参数:The arguments for theAES_ENCRYPT()andAES_DECRYPT()functions are as follows:-
str 用于
AES_ENCRYPT()函数的字符串,用于使用密钥字符串key_str加密,或使用由指定 KDF 派生的密钥。该字符串可以是任意长度。会自动在str上添加填充,使其符合块算法(如 AES)所需的块倍数。该填充会被AES_DECRYPT()函数自动移除。The string forAES_ENCRYPT()to encrypt using the key stringkey_str, or the key derived from it by the specified KDF. The string can be any length. Padding is automatically added tostrso it is a multiple of a block as required by block-based algorithms such as AES. This padding is automatically removed by theAES_DECRYPT()function.-
crypt_str 使用键字符串
key_str或通过指定的 KDF 从其派生的键解密的AES_DECRYPT()的加密字符串。该字符串可以是任意长度。crypt_str的长度可以根据原始字符串的长度使用以下公式计算:The encrypted string forAES_DECRYPT()to decrypt using the key stringkey_str, or the key derived from it by the specified KDF. The string can be any length. The length ofcrypt_strcan be calculated from the length of the original string using this formula:16 * (trunc(
string_length/ 16) + 1)-
key_str 加密密钥,或者用于作为基础通过密钥派生函数(KDF)导出密钥的输入密钥材料。对于相同的数据实例,使用相同的
key_str值来使用AES_ENCRYPT()加密和使用AES_DECRYPT()解密。The encryption key, or the input keying material that is used as the basis for deriving a key using a key derivation function (KDF). For the same instance of data, use the same value ofkey_strfor encryption withAES_ENCRYPT()and decryption withAES_DECRYPT().如果您使用 KDF,
key_str可以是任何任意信息,例如密码或短语。在函数的进一步参数中,您指定 KDF 名称,然后根据 KDF 的要求添加进一步的选项以提高安全性。If you are using a KDF,key_strcan be any arbitrary information such as a password or passphrase. In the further arguments for the function, you specify the KDF name, then add further options to increase the security as appropriate for the KDF.当您使用 KDF(密钥派生函数)时,该函数会从传入的
key_str信息以及您在其他参数中提供的盐值或附加信息中创建一个加密强度高的密钥。派生的密钥用于加密和解密数据,它会保存在 MySQL Server 实例中,用户无法访问。强烈建议使用 KDF,因为与使用您自己预制的密钥或通过更简单的方法在函数调用时派生密钥相比,它提供了更好的安全性。When you use a KDF, the function creates a cryptographically strong secret key from the information passed inkey_strand any salt or additional information that you provide in the other arguments. The derived key is used to encrypt and decrypt the data, and it remains in the MySQL Server instance and is not accessible to users. Using a KDF is highly recommended, as it provides better security than specifying your own premade key or deriving it by a simpler method as you use the function.如果您没有使用 KDF,对于 128 位的密钥长度,将密钥传递给
key_str参数的最安全方法是创建一个真正随机的 128 位值,并以二进制形式传递。例如:If you are not using a KDF, for a key length of 128 bits, the most secure way to pass a key to thekey_strargument is to create a truly random 128-bit value and pass it as a binary value. For example:INSERT INTO t VALUES (1,AES_ENCRYPT('text',UNHEX('F3229A0B371ED2D9441B830D21A390C3')));可以通过对口令进行哈希来生成 AES 密钥。例如:A passphrase can be used to generate an AES key by hashing the passphrase. For example:
INSERT INTO t VALUES (1,AES_ENCRYPT('text', UNHEX(SHA2('My secret passphrase',512))));如果您超过最大密钥长度 128 位,将返回警告。如果您不使用 KDF,请不要直接将密码或口令传递给
key_str,请先进行哈希处理。以前版本的文档建议使用以前的方法,但现在不再推荐,因为这里显示的示例更加安全。If you exceed the maximum key length of 128 bits, a warning is returned. If you are not using a KDF, do not pass a password or passphrase directly tokey_str, hash it first. Previous versions of this documentation suggested the former approach, but it is no longer recommended as the examples shown here are more secure.-
init_vector 初始化向量,用于需要它的块加密模式。
block_encryption_mode系统变量控制模式。对于相同的数据实例,加密时使用AES_ENCRYPT()和解密时使用AES_DECRYPT(),请使用相同的init_vector值。An initialization vector, for block encryption modes that require it. Theblock_encryption_modesystem variable controls the mode. For the same instance of data, use the same value ofinit_vectorfor encryption withAES_ENCRYPT()and decryption withAES_DECRYPT().Note如果您正在使用 KDF,您必须为此参数指定一个初始化向量或一个空字符串,以便访问后续参数来定义 KDF。If you are using a KDF, you must specify an initialization vector or a null string for this argument, in order to access the later arguments to define the KDF.
对于需要初始化向量的模式,初始化向量必须至少为 16 字节(超过 16 字节的部分将被忽略)。如果缺少
init_vector,将发生错误。对于不需要初始化向量的模式,初始化向量将被忽略,如果指定了init_vector,将生成警告,除非您正在使用 KDF。For modes that require an initialization vector, it must be 16 bytes or longer (bytes in excess of 16 are ignored). An error occurs ifinit_vectoris missing. For modes that do not require an initialization vector, it is ignored and a warning is generated ifinit_vectoris specified, unless you are using a KDF.block_encryption_mode系统变量的默认值是aes-128-ecb,即 ECB 模式,该模式不需要初始化向量。允许的其他块加密模式 CBC、CFB1、CFB8、CFB128 和 OFB 都需要初始化向量。The default value for theblock_encryption_modesystem variable isaes-128-ecb, or ECB mode, which does not require an initialization vector. The alternative permitted block encryption modes CBC, CFB1, CFB8, CFB128, and OFB all require an initialization vector.一个用于初始化向量的随机字节字符串可以通过调用
RANDOM_BYTES(16)生成。A random string of bytes to use for the initialization vector can be produced by callingRANDOM_BYTES(16).-
kdf_name 从传入的
key_str输入键材料创建密钥的密钥派生函数(KDF)的名称,以及适合该 KDF 的其他参数。可选。The name of the key derivation function (KDF) to create a key from the input keying material passed inkey_str, and other arguments as appropriate for the KDF. Optional.对于同一数据实例,在使用
AES_ENCRYPT()进行加密和使用AES_DECRYPT()进行解密时,请使用相同的kdf_name值。当您指定kdf_name时,必须指定init_vector,可以使用有效的初始化向量,或者如果加密模式不需要初始化向量,则使用空字符串。For the same instance of data, use the same value ofkdf_namefor encryption withAES_ENCRYPT()and decryption withAES_DECRYPT(). When you specifykdf_name, you must specifyinit_vector, using either a valid initialization vector, or a null string if the encryption mode does not require an initialization vector.支持以下值:The following values are supported:
-
hkdf HKDF,可从 OpenSSL 1.1.0 获取。HKDF 从密钥材料中提取伪随机密钥,然后将其扩展为其他密钥。使用 HKDF,您可以指定可选的盐值(
salt)和上下文相关信息,例如应用程序详细信息(info)纳入密钥材料中。HKDF, which is available from OpenSSL 1.1.0. HKDF extracts a pseudorandom key from the keying material then expands it into additional keys. With HKDF, you can specify an optional salt (salt) and context-specific information such as application details (info) to include in the keying material.-
pbkdf2_hmac PBKDF2,可从 OpenSSL 1.0.2 获取。PBKDF2 对密钥材料应用伪随机函数,并重复此过程大量次以生成密钥。使用 PBKDF2,您可以指定可选的盐值(
salt)纳入密钥材料中,并设置用于生成密钥的迭代次数(iterations)。PBKDF2, which is available from OpenSSL 1.0.2. PBKDF2 applies a pseudorandom function to the keying material, and repeats this process a large number of times to produce the key. With PBKDF2, you can specify an optional salt (salt) to include in the keying material, and set the number of iterations used to produce the key (iterations).
在此示例中,HKDF 被指定为密钥派生函数,并提供了盐和上下文信息。初始化向量的参数已包含,但为空字符串:In this example, HKDF is specified as the key derivation function, and a salt and context information are provided. The argument for the initialization vector is included but is the empty string:
SELECT AES_ENCRYPT('mytext','mykeystring', '', 'hkdf', 'salt', 'info');在此示例中,PBKDF2 被指定为密钥派生函数,提供了盐,并且迭代次数是推荐最小值的两倍:In this example, PBKDF2 is specified as the key derivation function, a salt is provided, and the number of iterations is doubled from the recommended minimum:
SELECT AES_ENCRYPT('mytext','mykeystring', '', 'pbkdf2_hmac','salt', '2000');-
-
saltsalt 一个将传递给密钥派生函数 (KDF) 的盐。可选的。HKDF 和 PBKDF2 都可以使用盐,建议使用盐以帮助防止基于常用密码字典或彩虹表的攻击。A salt to be passed to the key derivation function (KDF). Optional. Both HKDF and PBKDF2 can use salts, and their use is recommended to help prevent attacks based on dictionaries of common passwords or rainbow tables.
盐值由随机数据组成,为了安全,每次加密操作必须使用不同的盐值。可以通过调用
RANDOM_BYTES()生成用于盐值的随机字节字符串。此示例生成一个 64 位盐值:A salt consists of random data, which for security must be different for each encryption operation. A random string of bytes to use for the salt can be produced by callingRANDOM_BYTES(). This example produces a 64-bit salt:SET @salt = RANDOM_BYTES(8);
对于相同的数据实例,在使用
AES_ENCRYPT()加密和AES_DECRYPT()解密时,应使用相同的salt值。盐值可以安全地与加密数据一起存储。For the same instance of data, use the same value ofsaltfor encryption withAES_ENCRYPT()and decryption withAES_DECRYPT(). The salt can safely be stored along with the encrypted data.-
info 用于 HKDF 的上下文特定信息,以包含在密钥材料中,例如关于应用程序的信息。可选;当您将
hkdf指定为 KDF 名称时可用。HKDF 将此信息添加到key_str中指定的密钥材料和salt中指定的盐,以生成密钥。Context-specific information for HKDF to include in the keying material, such as information about the application. Optional; available when you specifyhkdfas the KDF name. HKDF adds this information to the keying material specified inkey_strand the salt specified insaltto produce the key.对于相同的数据实例,在使用
AES_ENCRYPT()加密和使用AES_DECRYPT()解密时,请使用相同的info值。For the same instance of data, use the same value ofinfofor encryption withAES_ENCRYPT()and decryption withAES_DECRYPT().-
iterations 生成密钥时 PBKDF2 使用的迭代次数。可选;当您指定
pbkdf2_hmac作为 KDF 名称时可用。较高的迭代次数可以提供更强的抵抗暴力攻击的能力,因为这对攻击者来说计算成本更高,但密钥派生过程本身也同样耗费更多。若未指定此参数,默认值为 1000,这是 OpenSSL 标准推荐的最小值。The iteration count for PBKDF2 to use when producing the key. Optional; available when you specifypbkdf2_hmacas the KDF name. A higher count gives greater resistance to brute-force attacks because it has a greater computational cost for the attacker, but the same is necessarily true for the key derivation process. The default if you do not specify this argument is 1000, which is the minimum recommended by the OpenSSL standard.对于相同的数据实例,加密时使用
AES_ENCRYPT()和解密时使用AES_DECRYPT(),请使用相同的iterations值。For the same instance of data, use the same value ofiterationsfor encryption withAES_ENCRYPT()and decryption withAES_DECRYPT().
mysql>
SET block_encryption_mode = 'aes-256-cbc';mysql>SET @key_str = SHA2('My secret passphrase',512);mysql>SET @init_vector = RANDOM_BYTES(16);mysql>SET @crypt_str = AES_ENCRYPT('text',@key_str,@init_vector);mysql>SELECT CAST(AES_DECRYPT(@crypt_str,@key_str,@init_vector) AS CHAR);+-------------------------------------------------------------+ | CAST(AES_DECRYPT(@crypt_str,@key_str,@init_vector) AS CHAR) | +-------------------------------------------------------------+ | text | +-------------------------------------------------------------+压缩一个字符串并返回作为二进制字符串的结果。此函数要求 MySQL 必须使用压缩库(如
zlib)编译。否则,返回值始终为NULL。如果string_to_compress为NULL,返回值也为NULL。压缩后的字符串可以使用UNCOMPRESS()进行解压。Compresses a string and returns the result as a binary string. This function requires MySQL to have been compiled with a compression library such aszlib. Otherwise, the return value is alwaysNULL. The return value is alsoNULLifstring_to_compressisNULL. The compressed string can be uncompressed withUNCOMPRESS().mysql>
SELECT LENGTH(COMPRESS(REPEAT('a',1000)));-> 21 mysql>SELECT LENGTH(COMPRESS(''));-> 0 mysql>SELECT LENGTH(COMPRESS('a'));-> 13 mysql>SELECT LENGTH(COMPRESS(REPEAT('a',16)));-> 15压缩字符串的内容存储方式如下:The compressed string contents are stored the following way:
空字符串存储为空字符串。Empty strings are stored as empty strings.
非空字符串存储为未压缩字符串的 4 字节长度(低字节优先),随后是压缩字符串。如果字符串以空格结尾,会额外添加一个
.字符,以避免在结果存储到CHAR或VARCHAR列时出现末尾空格剪裁问题。(但是,不推荐使用非二进制字符串数据类型如CHAR或VARCHAR来存储压缩字符串,因为可能会发生字符集转换。建议使用VARBINARY或BLOB二进制字符串列。)Nonempty strings are stored as a 4-byte length of the uncompressed string (low byte first), followed by the compressed string. If the string ends with space, an extra.character is added to avoid problems with endspace trimming should the result be stored in aCHARorVARCHARcolumn. (However, use of nonbinary string data types such asCHARorVARCHARto store compressed strings is not recommended anyway because character set conversion may occur. Use aVARBINARYorBLOBbinary string column instead.)
如果在 mysql 客户端中调用
COMPRESS(),二进制字符串将根据--binary-as-hex的值以十六进制表示。关于该选项的更多信息,请参见 第 6.5.1 节,“mysql — MySQL 命令行客户端”。IfCOMPRESS()is invoked from within the mysql client, binary strings display using hexadecimal notation, depending on the value of the--binary-as-hex. For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client”.计算字符串的 MD5 128 位校验和。该值以 32 位十六进制数字的字符串形式返回,如果参数为
NULL,则返回NULL。返回值例如可以用作哈希键。有关如何高效存储哈希值,请参阅本节开头的说明。Calculates an MD5 128-bit checksum for the string. The value is returned as a string of 32 hexadecimal digits, orNULLif the argument wasNULL. The return value can, for example, be used as a hash key. See the notes at the beginning of this section about storing hash values efficiently.返回值是连接字符集中的字符串。The return value is a string in the connection character set.
如果启用 FIPS 模式,
MD5()将返回NULL。请参见 第 8.8 节,“FIPS 支持”。If FIPS mode is enabled,MD5()returnsNULL. See Section 8.8, “FIPS Support”.mysql>
SELECT MD5('testing');-> 'ae2b1fca515949e5d54fb22b8ed95575'这是 “RSA 数据安全公司 MD5 消息摘要算法。”This is the “RSA Data Security, Inc. MD5 Message-Digest Algorithm.”
请参阅本节开头关于 MD5 算法的说明。See the note regarding the MD5 algorithm at the beginning this section.
此函数返回一个包含
len个随机字节的二进制字符串,这些字节是使用 SSL 库的随机数生成器生成的。len的允许值范围是 1 到 1024。超出该范围的值将导致错误。如果len为NULL,则返回NULL。This function returns a binary string oflenrandom bytes generated using the random number generator of the SSL library. Permitted values oflenrange from 1 to 1024. For values outside that range, an error occurs. ReturnsNULLiflenisNULL.RANDOM_BYTES()可用于为AES_DECRYPT()和AES_ENCRYPT()函数提供初始化向量。在该上下文中使用时,len必须至少为 16。允许使用更大的值,但超过 16 的字节将被忽略。RANDOM_BYTES()can be used to provide the initialization vector for theAES_DECRYPT()andAES_ENCRYPT()functions. For use in that context,lenmust be at least 16. Larger values are permitted, but bytes in excess of 16 are ignored.RANDOM_BYTES()生成随机值,这使得其结果具有不确定性。因此,使用此函数的语句在基于语句的复制中是不安全的。RANDOM_BYTES()generates a random value, which makes its result nondeterministic. Consequently, statements that use this function are unsafe for statement-based replication.如果从 mysql 客户端内部调用
RANDOM_BYTES(),二进制字符串将根据--binary-as-hex的值以十六进制表示。有关该选项的更多信息,请参见 第 6.5.1 节,“mysql — MySQL 命令行客户端”。IfRANDOM_BYTES()is invoked from within the mysql client, binary strings display using hexadecimal notation, depending on the value of the--binary-as-hex. For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client”.计算字符串的 SHA-1 160 位校验和,如 RFC 3174 (安全哈希算法) 所述。该值以 40 个十六进制数字的字符串形式返回,如果参数为
NULL,则返回NULL。此函数的一个可能用途是作为哈希键。有关高效存储哈希值的说明,请参见本节开头的备注。SHA()与SHA1()同义。Calculates an SHA-1 160-bit checksum for the string, as described in RFC 3174 (Secure Hash Algorithm). The value is returned as a string of 40 hexadecimal digits, orNULLif the argument isNULL. One of the possible uses for this function is as a hash key. See the notes at the beginning of this section about storing hash values efficiently.SHA()is synonymous withSHA1().返回值是连接字符集中的字符串。The return value is a string in the connection character set.
mysql>
SELECT SHA1('abc');-> 'a9993e364706816aba3e25717850c26c9cd0d89d'SHA1()可以被认为是MD5()的加密上更安全的等效函数。不过,请参阅本节开头关于 MD5 和 SHA-1 算法的备注。SHA1()can be considered a cryptographically more secure equivalent ofMD5(). However, see the note regarding the MD5 and SHA-1 algorithms at the beginning this section.计算 SHA-2 系列哈希函数(SHA-224、SHA-256、SHA-384 和 SHA-512)。第一个参数是要进行哈希的明文字符串。第二个参数表示所需结果的比特长度,其值必须为 224、256、384、512 或 0(等同于 256)。如果任一参数为
NULL或哈希长度不是允许值之一,则返回值为NULL。否则,函数结果为包含所需比特数的哈希值。有关高效存储哈希值的说明,请参阅本节开头的说明。Calculates the SHA-2 family of hash functions (SHA-224, SHA-256, SHA-384, and SHA-512). The first argument is the plaintext string to be hashed. The second argument indicates the desired bit length of the result, which must have a value of 224, 256, 384, 512, or 0 (which is equivalent to 256). If either argument isNULLor the hash length is not one of the permitted values, the return value isNULL. Otherwise, the function result is a hash value containing the desired number of bits. See the notes at the beginning of this section about storing hash values efficiently.返回值是连接字符集中的字符串。The return value is a string in the connection character set.
mysql>
SELECT SHA2('abc', 224);-> '23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7'仅当 MySQL 配置了 SSL 支持时,此函数才能使用。请参阅 第 8.3 节,“使用加密连接”。This function works only if MySQL has been configured with SSL support. See Section 8.3, “Using Encrypted Connections”.
SHA2()可以被认为在密码学上比MD5()或SHA1()更安全。SHA2()can be considered cryptographically more secure thanMD5()orSHA1().给定一个作为字符串的 SQL 语句,返回该语句的摘要哈希值,类型为连接字符集中的字符串;如果参数为
NULL,则返回NULL。相关的STATEMENT_DIGEST_TEXT()函数返回规范化的语句摘要。有关语句摘要的信息,请参见 第 29.10 节,“性能模式语句摘要与采样”。Given an SQL statement as a string, returns the statement digest hash value as a string in the connection character set, orNULLif the argument isNULL. The relatedSTATEMENT_DIGEST_TEXT()function returns the normalized statement digest. For information about statement digesting, see Section 29.10, “Performance Schema Statement Digests and Sampling”.这两个函数都使用 MySQL 解析器来解析语句。如果解析失败,将会发生错误。仅当语句以字面字符串提供时,错误消息才会包含解析错误。Both functions use the MySQL parser to parse the statement. If parsing fails, an error occurs. The error message includes the parse error only if the statement is provided as a literal string.
max_digest_length系统变量决定这些函数用于计算规范化语句摘要的最大字节数。Themax_digest_lengthsystem variable determines the maximum number of bytes available to these functions for computing normalized statement digests.mysql>
SET @stmt = 'SELECT * FROM mytable WHERE cola = 10 AND colb = 20';mysql>SELECT STATEMENT_DIGEST(@stmt);+------------------------------------------------------------------+ | STATEMENT_DIGEST(@stmt) | +------------------------------------------------------------------+ | 3bb95eeade896657c4526e74ff2a2862039d0a0fe8a9e7155b5fe492cbd78387 | +------------------------------------------------------------------+ mysql>SELECT STATEMENT_DIGEST_TEXT(@stmt);+----------------------------------------------------------+ | STATEMENT_DIGEST_TEXT(@stmt) | +----------------------------------------------------------+ | SELECT * FROM `mytable` WHERE `cola` = ? AND `colb` = ? | +----------------------------------------------------------+STATEMENT_DIGEST_TEXT(statement)给定一个作为字符串的 SQL 语句,返回以连接字符集表示的规范化语句摘要字符串,如果参数为
NULL,则返回NULL。有关更多讨论和示例,请参阅相关STATEMENT_DIGEST()函数的描述。Given an SQL statement as a string, returns the normalized statement digest as a string in the connection character set, orNULLif the argument isNULL. For additional discussion and examples, see the description of the relatedSTATEMENT_DIGEST()function.UNCOMPRESS(string_to_uncompress)解压由
COMPRESS()函数压缩的字符串。如果参数不是压缩值,结果为NULL;如果string_to_uncompress为NULL,结果也为NULL。此函数要求 MySQL 必须使用如zlib之类的压缩库进行编译。否则,返回值始终为NULL。Uncompresses a string compressed by theCOMPRESS()function. If the argument is not a compressed value, the result isNULL; ifstring_to_uncompressisNULL, the result is alsoNULL. This function requires MySQL to have been compiled with a compression library such aszlib. Otherwise, the return value is alwaysNULL.mysql>
SELECT UNCOMPRESS(COMPRESS('any string'));-> 'any string' mysql>SELECT UNCOMPRESS('any string');-> NULLUNCOMPRESSED_LENGTH(compressed_string)返回压缩字符串在压缩前的长度。如果
compressed_string为NULL,则返回NULL。Returns the length that the compressed string had before being compressed. ReturnsNULLifcompressed_stringisNULL.mysql>
SELECT UNCOMPRESSED_LENGTH(COMPRESS(REPEAT('a',30)));-> 30VALIDATE_PASSWORD_STRENGTH(str)给定表示明文密码的参数,此函数返回一个整数以表示密码的强度,如果参数为
NULL,则返回NULL。返回值范围从 0(弱)到 100(强)。Given an argument representing a plaintext password, this function returns an integer to indicate how strong the password is, orNULLif the argument isNULL. The return value ranges from 0 (weak) to 100 (strong).通过
VALIDATE_PASSWORD_STRENGTH()进行的密码评估由validate_password组件完成。如果该组件未安装,该函数总是返回 0。有关安装validate_password的信息,请参阅 第 8.4.3 节,“密码验证组件”。要检查或配置影响密码测试的参数,请查看或设置由validate_password实现的系统变量。请参阅 第 8.4.3.2 节,“密码验证选项和变量”。Password assessment byVALIDATE_PASSWORD_STRENGTH()is done by thevalidate_passwordcomponent. If that component is not installed, the function always returns 0. For information about installingvalidate_password, see Section 8.4.3, “The Password Validation Component”. To examine or configure the parameters that affect password testing, check or set the system variables implemented byvalidate_password. See Section 8.4.3.2, “Password Validation Options and Variables”.密码会接受越来越严格的测试,返回值反映了满足哪些测试,如下表所示。此外,如果启用了
validate_password.check_user_name系统变量,并且密码与用户名匹配,VALIDATE_PASSWORD_STRENGTH()将返回 0,而不管其他validate_password系统变量如何设置。The password is subjected to increasingly strict tests and the return value reflects which tests were satisfied, as shown in the following table. In addition, if thevalidate_password.check_user_namesystem variable is enabled and the password matches the user name,VALIDATE_PASSWORD_STRENGTH()returns 0 regardless of how othervalidate_passwordsystem variables are set.密码测试Password Test 返回值Return Value 长度 < 4Length < 4 0 长度 ≥ 4 且 < validate_password.lengthLength ≥ 4 and <validate_password.length25 符合策略 1( LOW)Satisfies policy 1 (LOW)50 符合策略 2( MEDIUM)Satisfies policy 2 (MEDIUM)75 符合策略 3( STRONG)Satisfies policy 3 (STRONG)100