react-native 采用xxtea加密传值

来源:互联网 发布:影音先锋替代软件 编辑:程序博客网 时间:2024/06/07 08:00

在发应用的时候,有些数据需要加密post或get传递给服务器端,我们可以采用xxtea加密算法进行传递

先下载tea-block.js文件 点击下载   使用说明查看这里,

下载好文件之后,要在react-native引用,需要安装一个组件,命令如下

npm install buffer --save


在tea-block.js文件中引用刚才的组件,修改如下

var Buffer = require('buffer').Buffer


这样就可以使用xxtea加密传送了。

使用如下,在需要使用的文件里引用


import Tea from './tea-block';

使用如下:


let str='testname';//要加密的字符串let keys='123456';//加密密钥let code=Tea.encrypt(str,keys);


服务器端,我这里是php作为服务器端,解密如下


       $code=$_REQUEST['code'];        require_once 'Pwxxtea.class.php';        $keys='123456';        $Pwxxtea2=new Pwxxtea();        $rusult = $Pwxxtea2->decrypt (  base64_decode( $code ), $keys );


Pwxxtea.class.php 文件代码如下:

str2long($str, true);$k = $this->str2long($key, false);if (count($k) < 4) {for ($i = count($k); $i < 4; $i++) {$k[$i] = 0;}}$n = count($v) - 1;$z = $v[$n];$y = $v[0];$delta = 0x9E3779B9;$q = floor(6 + 52 / ($n + 1));$sum = 0;while (0 < $q--) {$sum = $this->int32($sum + $delta);$e = $sum >> 2 & 3;for ($p = 0; $p < $n; $p++) {$y = $v[$p + 1];$mx = $this->int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ $this->int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));$z = $v[$p] = $this->int32($v[$p] + $mx);}$y = $v[0];$mx = $this->int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ $this->int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));$z = $v[$n] = $this->int32($v[$n] + $mx);}return $this->long2str($v, false);}/* (non-PHPdoc) * @see IWindSecurity::decrypt() */public function decrypt($str, $key) {if ($str == '') return '';if (!$key || !is_string($key)) {return false;}$v = $this->str2long($str, false);$k = $this->str2long($key, false);if (count($k) < 4) {for ($i = count($k); $i < 4; $i++) {$k[$i] = 0;}}$n = count($v) - 1;$z = $v[$n];$y = $v[0];$delta = 0x9E3779B9;$q = floor(6 + 52 / ($n + 1));$sum = $this->int32($q * $delta);while ($sum != 0) {$e = $sum >> 2 & 3;for ($p = $n; $p > 0; $p--) {$z = $v[$p - 1];$mx = $this->int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ $this->int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));$y = $v[$p] = $this->int32($v[$p] - $mx);}$z = $v[$n];$mx = $this->int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ $this->int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));$y = $v[0] = $this->int32($v[0] - $mx);$sum = $this->int32($sum - $delta);}return $this->long2str($v, true);}/** * 长整型转换为字符串 * * @param long $v * @param boolean $w * @return string */private function long2str($v, $w) {$len = count($v);$s = array();for ($i = 0; $i < $len; $i++)$s[$i] = pack("V", $v[$i]);return $w ? substr(join('', $s), 0, $v[$len - 1]) : join('', $s);}/** * 字符串转化为长整型 * * @param string $s * @param boolean $w * @return Ambigous  */private function str2long($s, $w) {$v = unpack("V*", $s . str_repeat("\0", (4 - strlen($s) % 4) & 3));$v = array_values($v);if ($w) $v[count($v)] = strlen($s);return $v;}/** * @param int $n * @return number */private function int32($n) {while ($n >= 2147483648)$n -= 4294967296;while ($n <= -2147483649)$n += 4294967296;return (int) $n;}}?>


tea-block.js 代码如下

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  *//* Block TEA (xxtea) Tiny Encryption Algorithm                        (c) Chris Veness 2002-2017  *//*                                                                                   MIT Licence  *//* www.movable-type.co.uk/scripts/tea-block.html                                                  *//* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */'use strict';var Buffer = require('buffer').Buffer/** * Tiny Encryption Algorithm. David Wheeler & Roger Needham, Cambridge University Computer Lab. * * www.movable-type.co.uk/scripts/tea.pdf   - TEA, a Tiny Encryption Algorithm (1994) * www.movable-type.co.uk/scripts/xtea.pdf  - Tea extensions (1997) * www.movable-type.co.uk/scripts/xxtea.pdf - Correction to xtea (1998) */class Tea {    /**     * Encrypts text using Corrected Block TEA (xxtea) algorithm.     *     * @param   {string} plaintext - String to be encrypted (multi-byte safe).     * @param   {string} password - Password to be used for encryption (1st 16 chars).     * @returns {string} Encrypted text (encoded as base64).     */    static encrypt(plaintext, password) {        plaintext = String(plaintext);        password = String(password);        if (plaintext.length == 0) return(''); // nothing to encrypt        //  v is n-word data vector; converted to array of longs from UTF-8 string        const v = Tea.strToLongs(Tea.utf8Encode(plaintext));        //  k is 4-word key; simply convert first 16 chars of password as key        const k = Tea.strToLongs(Tea.utf8Encode(password).slice(0, 16));        const cipher = Tea.encode(v, k);        // convert array of longs to string        const ciphertext = Tea.longsToStr(cipher);        // convert binary string to base64 ascii for safe transport        const cipherbase64 = Tea.base64Encode(ciphertext);        return cipherbase64;    }    /**     * Decrypts text using Corrected Block TEA (xxtea) algorithm.     *     * @param   {string} ciphertext - String to be decrypted.     * @param   {string} password - Password to be used for decryption (1st 16 chars).     * @returns {string} Decrypted text.     * @throws  {Error}  Invalid ciphertext     */    static decrypt(ciphertext, password) {        ciphertext = String(ciphertext);        password = String(password);        if (ciphertext.length == 0) return('');  // nothing to decrypt        //  v is n-word data vector; converted to array of longs from base64 string        const v = Tea.strToLongs(Tea.base64Decode(ciphertext));        //  k is 4-word key; simply convert first 16 chars of password as key        const k = Tea.strToLongs(Tea.utf8Encode(password).slice(0,16));        const plain = Tea.decode(v, k);        const plaintext = Tea.longsToStr(plain);        // strip trailing null chars resulting from filling 4-char blocks:        const plainUnicode = Tea.utf8Decode(plaintext.replace(/\0+$/,''));        return plainUnicode;    }    /**     * XXTEA: encodes array of unsigned 32-bit integers using 128-bit key.     *     * @param   {number[]} v - Data vector.     * @param   {number[]} k - Key.     * @returns {number[]} Encoded vector.     */    static encode(v, k) {        if (v.length < 2) v[1] = 0;  // algorithm doesn't work for n<2 so fudge by adding a null        const n = v.length;        const delta = 0x9e3779b9;        let q = Math.floor(6 + 52/n);        let z = v[n-1], y = v[0];        let mx, e, sum = 0;        while (q-- > 0) {  // 6 + 52/n operations gives between 6 & 32 mixes on each word            sum += delta;            e = sum>>>2 & 3;            for (let p = 0; p < n; p++) {                y = v[(p+1)%n];                mx = (z>>>5 ^ y<<2) + (y>>>3 ^ z<<4) ^ (sum^y) + (k[p&3 ^ e] ^ z);                z = v[p] += mx;            }        }        return v;    }    /**     * XXTEA: decodes array of unsigned 32-bit integers using 128-bit key.     *     * @param   {number[]} v - Data vector.     * @param   {number[]} k - Key.     * @returns {number[]} Decoded vector.     */    static decode(v, k) {        const n = v.length;        const delta = 0x9e3779b9;        const q = Math.floor(6 + 52/n);        let z = v[n-1], y = v[0];        let mx, e, sum = q*delta;        while (sum != 0) {            e = sum>>>2 & 3;            for (let p = n-1; p >= 0; p--) {                z = v[p>0 ? p-1 : n-1];                mx = (z>>>5 ^ y<<2) + (y>>>3 ^ z<<4) ^ (sum^y) + (k[p&3 ^ e] ^ z);                y = v[p] -= mx;            }            sum -= delta;        }        return v;    }    /**     * Converts string to array of longs (each containing 4 chars).     * @private     */    static strToLongs(s) {        // note chars must be within ISO-8859-1 (Unicode code-point <= U+00FF) to fit 4/long        const l = new Array(Math.ceil(s.length/4));        for (let i=0; i>>8 & 0xff, l[i]>>>16 & 0xff, l[i]>>>24 & 0xff);        }        return str;    }    /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */    /**     * Encodes multi-byte string to utf8 - monsur.hossa.in/2012/07/20/utf-8-in-javascript.html     */    static utf8Encode(str) {        return unescape(encodeURIComponent(str));    }    /**     * Decodes utf8 string to multi-byte     */    static utf8Decode(utf8Str) {        try {            return decodeURIComponent(escape(utf8Str));        } catch (e) {            return utf8Str; // invalid UTF-8? return as-is        }    }    /**     * Encodes base64 - developer.mozilla.org/en-US/docs/Web/API/window.btoa, nodejs.org/api/buffer.html     */    static base64Encode(str) {        if (typeof btoa != 'undefined') return btoa(str); // browser        if (typeof Buffer != 'undefined') return new Buffer(str, 'binary').toString('base64'); // Node.js        throw new Error('No Base64 Encode');    }    /**     * Decodes base64     */    static base64Decode(b64Str) {        if (typeof atob == 'undefined' && typeof Buffer == 'undefined') throw new Error('No base64 decode');        try {            if (typeof atob != 'undefined') return atob(b64Str); // browser            if (typeof Buffer != 'undefined') return new Buffer(b64Str, 'base64').toString('binary'); // Node.js        } catch (e) {            throw new Error('Invalid ciphertext');        }    }}/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */if (typeof module != 'undefined' && module.exports) module.exports = Tea; // ≡ export default Tea


原创粉丝点击