首先这个是我12年写的,那个时候AS3还是比较流行的,不过现在回头看来已经成了历史,
XXTEA加密不多绍,最后做游戏用到了,后台是C#,前端是用AS3,网上也找了一些AS3版的XXTEA加密,但是用起来总是有麻烦,C# 版的和AS3的不通用。加密弄啥还不是为了通信。于是直接按照网上C#版的翻译来一个,网上的C#上找了几个版本,加密后都一样。

C#加密是从网上找的 网址:http://www.cnblogs.com/gfsov/archive/2009/02/05/984952.html

想看js的和另一个cs版本的如下:http://blog.csdn.net/thinmichael/article/details/751905 两个其实一样的。
我做了一点点改动,把字符串类型的参数方法加了进去。

XXTEA加密算法 for C#

/// <summary>  
    /// 加密算法  
    /// </summary>  
    public class XXTEA  
    {  
        /// <summary>  
        /// 加密字符串  
        /// </summary>  
        /// <param name="Str">传入的明文</param>  
        /// <param name="Key">密钥</param>  
        /// <returns>返回密文</returns>  
        public static String Encrypt(string Str, string Key)  
        {  
            System.Text.Encoding encoder = System.Text.Encoding.UTF8;  
            string result = string.Empty;  
            try 
            {  
                result = System.Convert.ToBase64String(Encrypt(encoder.GetBytes(Str), encoder.GetBytes(Key)));  
            }  
            catch (Exception)  
            {  
                return null;   
            }  
            return result;  
        }  
        /// <summary>  
        /// 解密字符串  
        /// </summary>  
        /// <param name="Str">传入的加密字符串</param>  
        /// <param name="Key">密钥</param>  
        /// <returns>返回明文</returns>  
        public <span style="background-color: rgb(255, 255, 255); ">static </span>string Decrypt(string Str, string Key)  
        {  
            System.Text.Encoding encoder = System.Text.Encoding.UTF8;  
            string result = string.Empty;  
            try 
            {  
                result = encoder.GetString(Decrypt(System.Convert.FromBase64String(Str), encoder.GetBytes(Key)));  
            }  
            catch (Exception)  
            {  
                return null;  
            }  
            return result;  
        }  
   
        private static Byte[] Encrypt(Byte[] Data, Byte[] Key)  
        {  
            if (Data.Length == 0)  
            {  
                return Data;  
            }  
            return ToByteArray(Encrypt(ToUInt32Array(Data, true), ToUInt32Array(Key, false)), false);  
        }  
        private static Byte[] Decrypt(Byte[] Data, Byte[] Key)  
        {  
            if (Data.Length == 0)  
            {  
                return Data;  
            }  
            return ToByteArray(Decrypt(ToUInt32Array(Data, false), ToUInt32Array(Key, false)), true);  
        }  
        private static UInt32[] Encrypt(UInt32[] v, UInt32[] k)  
        {  
            Int32 n = v.Length - 1;  
            if (n < 1)  
            {  
                return v;  
            }  
            if (k.Length < 4)  
            {  
                UInt32[] Key = new UInt32[4];  
                k.CopyTo(Key, 0);  
                k = Key;  
            }  
            UInt32 z = v[n], y = v[0], delta = 0x9E3779B9, sum = 0, e;  
            Int32 p, q = 6 + 52 / (n + 1);  
            while (q-- > 0)  
            {  
                sum = unchecked(sum + delta);  
                e = sum >> 2 & 3;  
                for (p = 0; p < n; p++)  
                {  
                    y = v[p + 1];  
                    z = unchecked(v[p] += (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z));  
                }  
                y = v[0];  
                z = unchecked(v[n] += (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z));  
            }  
            return v;  
        }  
        private static UInt32[] Decrypt(UInt32[] v, UInt32[] k)  
        {  
            Int32 n = v.Length - 1;  
            if (n < 1)  
            {  
                return v;  
            }  
            if (k.Length < 4)  
            {  
                UInt32[] Key = new UInt32[4];  
                k.CopyTo(Key, 0);  
                k = Key;  
            }  
            UInt32 z = v[n], y = v[0], delta = 0x9E3779B9, sum, e;  
            Int32 p, q = 6 + 52 / (n + 1);  
            sum = unchecked((UInt32)(q * delta));  
            while (sum != 0)  
            {  
                e = sum >> 2 & 3;  
                for (p = n; p > 0; p--)  
                {  
                    z = v[p - 1];  
                    y = unchecked(v[p] -= (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z));  
                }  
                z = v[n];  
                y = unchecked(v[0] -= (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z));  
                sum = unchecked(sum - delta);  
            }  
            return v;  
        }  
        private static UInt32[] ToUInt32Array(Byte[] Data, Boolean IncludeLength)  
        {  
            Int32 n = (((Data.Length & 3) == 0) ? (Data.Length >> 2) : ((Data.Length >> 2) + 1));  
            UInt32[] Result;  
            if (IncludeLength)  
            {  
                Result = new UInt32[n + 1];  
                Result[n] = (UInt32)Data.Length;  
            }  
            else 
            {  
                Result = new UInt32[n];  
            }  
            n = Data.Length;  
            for (Int32 i = 0; i < n; i++)  
            {  
                Result[i >> 2] |= (UInt32)Data[i] << ((i & 3) << 3);  
            }  
            return Result;  
        }  
        private static Byte[] ToByteArray(UInt32[] Data, Boolean IncludeLength)  
        {  
            Int32 n;  
            if (IncludeLength)  
            {  
                n = (Int32)Data[Data.Length - 1];  
            }  
            else 
            {  
                n = Data.Length << 2;  
            }  
            Byte[] Result = new Byte[n];  
            for (Int32 i = 0; i < n; i++)  
            {  
                Result[i] = (Byte)(Data[i >> 2] >> ((i & 3) << 3));  
            }  
            return Result;  
        }  
    }  

在写AS3加密之前先准备一下这个 AS3的 Base64,为的就是传输方便的需要。

package {     
     
    import flash.utils.ByteArray;     
          
    public class Base64 {     
              
        private static const BASE64_CHARS:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";     
     
        public static const version:String = "1.0.0";  
     
        public static function encode(data:String):String {     
            // Convert string to ByteArray     
            var bytes:ByteArray = new ByteArray();     
            bytes.writeUTFBytes(data);     
                  
            // Return encoded ByteArray     
            return encodeByteArray(bytes);     
        }  
              
        public static function encodeByteArray(data:ByteArray):String {     
            // Initialise output     
            var output:String = "";     
                  
            // Create data and output buffers     
            var dataBuffer:Array;     
            var outputBuffer:Array = new Array(4);     
                  
            // Rewind ByteArray     
            data.position = 0;     
                  
            // while there are still bytes to be processed     
            while (data.bytesAvailable > 0) {     
                // Create new data buffer and populate next 3 bytes from data     
                dataBuffer = new Array();     
                for (var i:uint = 0; i < 3 && data.bytesAvailable > 0; i++) {     
                    dataBuffer[i] = data.readUnsignedByte();     
                }     
                      
                // Convert to data buffer Base64 character positions and      
                // store in output buffer     
                outputBuffer[0] = (dataBuffer[0] & 0xfc) >> 2;     
                outputBuffer[1] = ((dataBuffer[0] & 0x03) << 4) | ((dataBuffer[1]) >> 4);     
                outputBuffer[2] = ((dataBuffer[1] & 0x0f) << 2) | ((dataBuffer[2]) >> 6);     
                outputBuffer[3] = dataBuffer[2] & 0x3f;     
                      
                // If data buffer was short (i.e not 3 characters) then set     
                // end character indexes in data buffer to index of '=' symbol.     
                // This is necessary because Base64 data is always a multiple of     
                // 4 bytes and is basses with '=' symbols.     
                for (var j:uint = dataBuffer.length; j < 3; j++) {     
                    outputBuffer[j + 1] = 64;     
                }     
                      
                // Loop through output buffer and add Base64 characters to      
                // encoded data string for each character.     
                for (var k:uint = 0; k < outputBuffer.length; k++) {     
                    output += BASE64_CHARS.charAt(outputBuffer[k]);     
                }     
            }     
                  
            // Return encoded data     
            return output;     
        }     
              
        public static function decode(data:String):String {     
            // Decode data to ByteArray     
            var bytes:ByteArray = decodeToByteArray(data);     
                  
            // Convert to string and return     
            return bytes.readUTFBytes(bytes.length);     
        }     
              
        public static function decodeToByteArray(data:String):ByteArray {     
            // Initialise output ByteArray for decoded data     
            var output:ByteArray = new ByteArray();     
                  
            // Create data and output buffers     
            var dataBuffer:Array = new Array(4);     
            var outputBuffer:Array = new Array(3);     
     
            // While there are data bytes left to be processed     
            for (var i:uint = 0; i < data.length; i += 4) {     
                // Populate data buffer with position of Base64 characters for     
                // next 4 bytes from encoded data     
                for (var j:uint = 0; j < 4 && i + j < data.length; j++) {     
                    dataBuffer[j] = BASE64_CHARS.indexOf(data.charAt(i + j));     
                }     
                      
                // Decode data buffer back into bytes     
                outputBuffer[0] = (dataBuffer[0] << 2) + ((dataBuffer[1] & 0x30) >> 4);     
                outputBuffer[1] = ((dataBuffer[1] & 0x0f) << 4) + ((dataBuffer[2] & 0x3c) >> 2);             
                outputBuffer[2] = ((dataBuffer[2] & 0x03) << 6) + dataBuffer[3];     
                      
                // Add all non-padded bytes in output buffer to decoded data     
                for (var k:uint = 0; k < outputBuffer.length; k++) {     
                    if (dataBuffer[k+1] == 64) break;     
                    output.writeByte(outputBuffer[k]);     
                }     
            }     
                  
            // Rewind decoded data ByteArray     
            output.position = 0;     
                  
            // Return decoded data     
            return output;     
        }  
              
        public function Base64() {     
            throw new Error("Base64 class is static container only");     
        }     
    }     
}   

以下是AS3 的,是直接按照C#翻译过来的,应该和js也通用

下午努力用ByteArray 来代替Array 没有成功,原来ByteArray 的储存方式和Array 有本质的区别,大侠们有更好的办法么?我再改。

代码如下:(点击捐赠按钮查看更多内容)

 

💰 此内容为付费阅读 请先登录