Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

mysql - Why is AES_DECRYPT returning null?

I've found similar questions, but no clear answer for this question. I have this table:

CREATE DATABASE testDB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; 

CREATE TABLE testTable
(
firstName binary(32) not null,
lastName binary(32) not null
/* Other non-binary fields omitted */
)
engine=INNODB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

This statement executes just fine:

INSERT INTO testTable (firstName) VALUES (AES_ENCRYPT('Testname', 'test'));

But, this returns NULL:

SELECT AES_DECRYPT(firstName, 'test') FROM testTable;

Why does this return NULL?

Fwiw, this returns "testValue" as expected:

SELECT AES_DECRYPT(AES_ENCRYPT('testValue','thekey'), 'thekey');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The answer is that the columns are binary when they should be varbinary. This article explains it:

Because if AES_DECRYPT() detects invalid data or incorrect padding, it will return NULL.

With binary column types being fixed length, the length of the input value must be known to ensure correct padding. For unknown length values, use varbinary to avoid issues with incorrect padding resulting from differing value lengths.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...