简体   繁体   中英

How to encode a Javascript string to Unicode and decode it to utf-8 in PHP?

I have tried a couple of ways but it does't work.

Now I have 2 problems that I cannot figure out.

  1. I can't figure out how to encode a string in JavaScript to Unicode and decode using $value = iconv('UCS-2LE', 'UTF-8', $_GET["value"]); in PHP

  2. I encrypted a string in RC4 using JavaScript, encoded in base64, then transferred it to PHP. The result was garbled. I don't know why!

Where should I start?

I have solved the problem and I think it's a good way and I want to share. Javascript object is encode in USC-2. But RC4 is working in bytes.Firstly,I transfer string into bytes array using
var plainValueArray = TextEncoder("utf-16").encode(value); var keyArray=TextEncoder("utf8").encode(RC4Key); Secondly,RC4 as below var RC4={ crypt:function(rawBytes,keyBytes){

    var i;
    var sBuffer=new ArrayBuffer(256);
    var kBuffer=new ArrayBuffer(256);
    var cipherBuffer=new ArrayBuffer(rawBytes.length);
    var s=new Uint8Array(sBuffer);//box[]
    var k=new Uint8Array(kBuffer);//key[]
    var cipherBytes=new Uint8Array(cipherBuffer);
    for(i=0;i<rawBytes.length;i++)
    {
        cipherBytes[i]=0x00;
    }
    for(i=0;i<256;i++)
    {
        k[i]=keyBytes[i%keyBytes.length];
        s[i]=i;
    }
    var j=0;
    for(i=0;i<256;i++)
    {
        j=(j+s[i]+k[i])%256;
        x=s[i];
        s[i]=s[j];
        s[j]=x;
    }
    i=0;
    j=0;
    for(var y=0;y<rawBytes.length;y++)
    {
        i=(i+1)%256;
        j=(j+s[i])%256;
        x=s[i];
        s[i]=s[j];
        s[j]=x;
        key=s[(s[i]+s[j])%256]
        cipherBytes[y]=key^rawBytes[y];
    }
    return cipherBytes;

}

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM