찾다
백엔드 개발PHP 튜토리얼lua 与 php 经过AES数据加密进行通讯

lua 与 php 通过AES数据加密进行通讯

最近公司有款《围住神经猫》的微信小游戏火爆的不行!公司又决定开发一系列的神经猫的小游戏,于是,我被拉过来了。

后来使用cocos-2dx 开发一款小游戏,客户端用的是lua脚本,为了服务器与客户端交互的安全性,我们决定对API接口

传输的JSON数据进行加密、解密。一般情况就是客户端加密,服务器段进行解密:

lua客户端使用的是一个纯lua写的库:aeslua,下载地址:http://luaforge.net/projects/aeslua/

但是该库是有问题的:用该库加密解密是没有问题的,但是跟PHP通讯就存在问题了,因为该库加密后base64之后的

字符串PHP是无法解密的!为了这个问题,我查阅了好多资料,终于找到某个国外大神的解决办法:

http://chainans.blogspot.com/2012/09/working-with-lua-encryption.html(可能有些同学无法FQ,故把原文贴出来如下:)

Working with Lua encryption

Recently working with Corona SDK, I start to need some standard encryption/decryption algorithm in Lua. To start with, actually, it has rather small number of developers comparing to the Objective-C which I have been working with. Meaning that there are fewer 3rd party librarys you can rely upon. Luckily, I found one called AESLua which has some code to start. From there, my objective is to make a way to securely passing data between my client and server. (php on server-side) In fact, from what I'd read, my method is not very secure but it is better than nothing. Just for my reference, here are the list of issues along the way


Edited: Tested with iPhone 4... Input cipher text of 1280 characters. Take around 25 seconds. Unacceptable speed for general uses.


1) It requires Lua 5.2 feature which does not seem to be in Corona

Solution: Download LuaBit v0.4 and integrate it... You will need to make a mapping to allow API call to the proper place

2) Next you need to get Base64 library -- grab it here https://gist.github.com/2563975 -- It initially made to allow passing it over the URL (using '-' and '_' instead of '+' and '/') So, I change them to the latter one.

3) For AESLua, by default, it uses AES-128, CBC, some kind of random padding

http://www.unsw.adfa.edu.au/~lpb/src/AEScalc/AEScalc.html

http://www.tools4noobs.com/online_tools/decrypt/

Here are the things to do

3.1) In pwInKey function, comment the line out

 password = ciphermode.encryptString(pwBytes, password, ciphermode.encryptCBC);

3.2) In util.padByteString function, change it to

    local paddingLength = math.ceil(#data/16)*16 - #data;

    local padding = "";

    local paddingValue = string.char ( paddingLength )  -- PKCS7 padding

    for i=1,paddingLength do

padding = padding .. paddingValue;-- PKCS7 padding

    end 


    return data .. padding;


4) Set up web server for testing, you will need php / mcrypt mod to test.

5) Creating a php for testing... here is a code

Now, my plain text below is "1234567890123456ss@#%de".



$data = 'dXzNDNxckOrb7uz2ON0AAJp4BXgkYewblTNWBSAQSEw=';

$key128 = '1234567890123456';

$iv =  '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0';


echo mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key128, base64_decode($data), MCRYPT_MODE_CBC, $iv)



?>



That's it. The encryption backward to client machine should be a piece of cake. =)


*** By using these library, the user should be aware of the fact that Lua's performance is still far from native code. You may not want to use this algorithm to encrypt a large volume of data.

按照他的办法,一切都OK了。但是有以下几点需要说明以下:(本人摸索的)

1.利用CBC模式加密的字符串的key必须是16位,否则PHP无法解密!

2.明文字符串的必须把key作为前缀加进去

3.上面文章中没有把unpack函数写出来,本人查阅了一些资料,补充了,否则aeslua无法正常解密了!

util.lua中的下面这个函数改为如下:

function public.unpadByteString(data)
    local padLength = tonum((string.byte(data, #data)));
    return string.sub(data,1, #data-padLength)   --unpack
end

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
unset ()와 session_destroy ()의 차이점은 무엇입니까?unset ()와 session_destroy ()의 차이점은 무엇입니까?May 04, 2025 am 12:19 AM

thedifferencebetweenUnset () andsession_destroy () istssection_destroy () thinatesTheentiresession.1) TEREMOVECIFICESSESSION 'STERSESSIVEBLESSESSIVESTIETSTESTERSALLS'SSOVERSOLLS '를 사용하는 것들

로드 밸런싱의 맥락에서 스티커 세션 (세션 친화력)이란 무엇입니까?로드 밸런싱의 맥락에서 스티커 세션 (세션 친화력)이란 무엇입니까?May 04, 2025 am 12:16 AM

stickysessionsureSureSureRequestSaroutEdToTheSERSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESSESINCENSENCY

PHP에서 사용할 수있는 다른 세션 저장 핸들러는 무엇입니까?PHP에서 사용할 수있는 다른 세션 저장 핸들러는 무엇입니까?May 04, 2025 am 12:14 AM

phpoffersvarioussessionsaveAndlers : 1) 파일 : 기본, 단순, 단순한 BUTMAYBOTTLENECKONHIGH-TRAFFICSITES.2) MEMCACHED : 고성능, IdealForspeed-CriticalApplications.3) Redis : SimilartomemCached, WithaddedPersistence.4) 데이터베일 : OffforIntegrati

PHP의 세션은 무엇이며 왜 사용됩니까?PHP의 세션은 무엇이며 왜 사용됩니까?May 04, 2025 am 12:12 AM

PHP의 세션은 여러 요청간에 상태를 유지하기 위해 서버 측의 사용자 데이터를 저장하는 메커니즘입니다. 구체적으로, 1) 세션은 session_start () 함수에 의해 시작되며 데이터는 $ _session Super Global Array를 통해 저장되어 읽습니다. 2) 세션 데이터는 기본적으로 서버의 임시 파일에 저장되지만 데이터베이스 또는 메모리 스토리지를 통해 최적화 할 수 있습니다. 3) 세션은 사용자 로그인 상태 추적 및 쇼핑 카트 관리 기능을 실현하는 데 사용될 수 있습니다. 4) 세션의 보안 전송 및 성능 최적화에주의를 기울여 애플리케이션의 보안 및 효율성을 보장하십시오.

PHP 세션의 수명주기를 설명하십시오.PHP 세션의 수명주기를 설명하십시오.May 04, 2025 am 12:04 AM

phpsessionsStartWithSession_start (), whithesauniqueIdAndCreatesErverFile; thepersistacrossRequestSandCanBemanBledentSandwithSession_destroy ()

절대 세션 타임 아웃의 차이점은 무엇입니까?절대 세션 타임 아웃의 차이점은 무엇입니까?May 03, 2025 am 12:21 AM

절대 세션 시간 초과는 세션 생성시 시작되며, 유휴 세션 시간 초과는 사용자가 작동하지 않아 시작합니다. 절대 세션 타임 아웃은 금융 응용 프로그램과 같은 세션 수명주기의 엄격한 제어가 필요한 시나리오에 적합합니다. 유휴 세션 타임 아웃은 사용자가 소셜 미디어와 같이 오랫동안 세션을 활성화하려는 응용 프로그램에 적합합니다.

세션이 서버에서 작동하지 않으면 어떤 조치를 취 하시겠습니까?세션이 서버에서 작동하지 않으면 어떤 조치를 취 하시겠습니까?May 03, 2025 am 12:19 AM

서버 세션 고장은 다음 단계를 따라 해결할 수 있습니다. 1. 서버 구성을 확인하여 세션이 올바르게 설정되었는지 확인하십시오. 2. 클라이언트 쿠키를 확인하고 브라우저가 지원하는지 확인하고 올바르게 보내십시오. 3. Redis와 같은 세션 스토리지 서비스가 정상적으로 작동하는지 확인하십시오. 4. 올바른 세션 로직을 보장하기 위해 응용 프로그램 코드를 검토하십시오. 이러한 단계를 통해 대화 문제를 효과적으로 진단하고 수리 할 수 ​​있으며 사용자 경험을 향상시킬 수 있습니다.

session_start () 함수의 중요성은 무엇입니까?session_start () 함수의 중요성은 무엇입니까?May 03, 2025 am 12:18 AM

session_start () iscrucialinphpformanagingUsersessions.1) itiniteSanewsessionifnoneexists, 2) ResumesAnxistessions, and3) setSasessionCookieForContInuityAcrosrequests, enablingplicationsirecationSerauthenticationAndpersonalizestContent.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경