OpenSSL encryption padding issue

被刻印的时光 ゝ 提交于 2019-12-12 02:07:32

问题


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.

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¿

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¿

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

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

Thanks for your reply.


回答1:


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

  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¿€@¸>

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

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

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

  4. 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.



来源:https://stackoverflow.com/questions/25278307/openssl-encryption-padding-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!