OpenSSL加密填充问题 [英] OpenSSL encryption padding issue

查看:518
本文介绍了OpenSSL加密填充问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从使用PHP的服务器向iOS发送openssl加密的字符串,反之亦然,在使用PHP的服务器中,我需要对字符串进行加密/解密,并且与iOS相同,除了从iOS接收到的字符串包含多余的字符之后,一切正常经过几次搜索,我了解到RSA加密默认情况下会应用PKCS1填充,例如,它将额外的字符附加到加密的字符串中.

I am sending openssl encrypted string from server using PHP to iOS and vice versa, in server using PHP i need to encrypt/decrypt the string and same with iOS, everything works fine except the string received from iOS contains extra characters, after few searches i came to understand that RSA encryption applies PKCS1 padding by default, which appends extra characters to encrypted string for example.

加密的字符串foo在解密后得到此输出.

The encrypted string foo is getting this output after decryption.

foo¤º   ¤º  äØKŒCarrier+†7†ÐHÀ€ôa$aLa°aTa(aX¿€<a@aèaaTwaØwaäwa0®50‡4€B4ÀB4°†4ð†4þ;Ð}2}20¸>@¸> ¸>LGa¿

我希望PHP能够从字符串中删除那些不需要的填充,但是不幸的是,我没有想到,唯一可以想到的解决方法是沿着字符串和这些不需要的字符的条带发送长度,例如添加长度后,解密后的字符串将如下所示.

I was expecting PHP to take care of removing those unwanted padding from the string, but unfortunately it doesn't, the only workaround i can think of is to send the length along the string and strip of those unwanted characters, for example the decrypted string will look like this after adding the length.

3_foo¤º   ¤º  äØKŒCarrier+†7†ÐHÀ€ôa$aLa°aTa(aX¿€<a@aèaaTwaØwaäwa0®50‡4€B4ÀB4°†4ð†4þ;Ð}2}20¸>@¸> ¸>LGa¿

我可以得到初始的3_,它是字符串的长度,然后除去其余部分.

I can get the initial 3_ which is the length of the string, and remove the rest.

我想向您询问是否可以采用这种方法,或者是否有其他替代方法,或者PHP是否应该自动为我执行此操作.

I want to know from you if this is okay to go approach or if there is any other alternative or if PHP should be doing this for me automatically.

如果要查看我使用的代码,请参见另一篇文章:

If you want to have a look at the code i am using, here it is in another post : Openssl decryption displays extra characters

感谢您的答复.

推荐答案

对于那些在删除填充方面遇到麻烦的人,我在这里做了解决方法.

For those having trouble with removing padding here is what i did for the solution.

  1. 我在每个字符串的开头添加了字符串长度,我的字符串看起来像:

  1. I added string length at the beginning of each string, my string looked like :

9_foostring交ºäŒKŒCarrier+†7†ÐHÀ€a $ aL°aTa(aX¿€@¸>

9_foostring¤º ¤º äØKŒCarrier+†7†ÐHÀ€ôa$aL°aTa(aX¿€@¸>

在这种情况下,从字符串的开头获取长度前缀9_

Get the length prefix from beginning of the string in this case 9_

将字符串拆分成不带长度前缀的字符串,现在我的字符串看起来像:

Split the string without the length prefix, now my string looked like :

foostring交ºäØKŒCarrier+†7†ÐHÀ€a $ aL°aTa(aX¿€@¸>

foostring¤º ¤º äØKŒCarrier+†7†ÐHÀ€ôa$aL°aTa(aX¿€@¸>

获取字符串的前9个字符,并去除其余字符.

Get the first 9 character of the string and strip the rest.

这解决了我的问题,希望这对遇到类似问题的人也有所帮助.

This solved my issue, hope this helps someone too with the similar problem.

这篇关于OpenSSL加密填充问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆