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.1k views
in Technique[技术] by (71.8m points)

php - How do I make openssl_encrypt pad the input to the required block size?

My code works if I manually pad my string to the length of 32.
My question is: Is there a way to make the openSSL pad the data, or do I always have to do it for it?

Working:

 openssl_encrypt ("my baba is over the ocean1111111", 'AES-256-CBC', $MY_SECRET_KEY,OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING,$MY_IV);

Not working:

openssl_encrypt ("my baba is over the ocean", 'AES-256-CBC', $MY_SECRET_KEY,OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING,$MY_IV);

I solve this currently by self padding:

$pad = 32 - (strlen("my baba is over the ocean") % 32);
$clear = "my baba is over the ocean" . str_repeat(chr($pad), $pad); //encrypt this string
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As Luke Park said, instead of explicitly telling openssl_encrypt to use OPENSSL_ZERO_PADDING, simply remove that option from the parameter and it will default to the PKCS #7 padding scheme (fills the rest of the block with 0x0n where n is the number of bytes necessary; + 16 0x00 if the block is already complete). Note: PKCS #5 as referenced by Luke and PKCS #7 are effectively identical in this scenario.

From PHP docs:

Without using OPENSSL_ZERO_PADDING, you will automatically get PKCS#7 padding.

So you should be calling:

openssl_encrypt("my baba is over the ocean", 'AES-256-CBC', $MY_SECRET_KEY, OPENSSL_RAW_DATA, $MY_IV);

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

...