Xxtea加解密

转自:http://www.cnblogs.com/luminji/p/3406407.html

很有意思的一件事情,当我想要找 Xxtea 加解密算法的时候,发现了前同事(likui318)的代码,不妨分享出来。此代码满足:

1:Xxtea支持中文;

2:支持 JS 和 C# 加解密之间的互转;

一:C#部分

class XXTEA2
{
    public static string Encrypt(string source, string key)
    {
        System.Text.Encoding encoder = System.Text.Encoding.UTF8;
        //UTF8==>BASE64==>XXTEA==>BASE64
        byte[] bytData = encoder.GetBytes(base64Encode(source));
        byte[] bytKey = encoder.GetBytes(key);
        if (bytData.Length == 0)
        {
            return "";
        }
        return System.Convert.ToBase64String(ToByteArray(Encrypt(ToUInt32Array(bytData, true), ToUInt32Array(bytKey, false)), false));
    }
    public static string Decrypt(string source, string key)
    {
        if (source.Length == 0)
        {
            return "";
        }
        // reverse
        System.Text.Encoding encoder = System.Text.Encoding.UTF8;
        byte[] bytData = System.Convert.FromBase64String(source);
        byte[] bytKey = encoder.GetBytes(key);

return base64Decode(encoder.GetString(ToByteArray(Decrypt(ToUInt32Array(bytData, false), ToUInt32Array(bytKey, 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;
    }

public static string base64Decode(string data)
    {
        try
        {
            var encoder = System.Text.Encoding.UTF8;

byte[] todecode_byte = Convert.FromBase64String(data);
            return encoder.GetString(todecode_byte);
        }
        catch (Exception e)
        {
            throw new Exception("Error in base64Decode" + e.Message);
        }
    }

public static string base64Encode(string data)
    {
        try
        {
            byte[] encData_byte = new byte[data.Length];
            encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
            string encodedData = Convert.ToBase64String(encData_byte);
            return encodedData;
        }
        catch (Exception e)
        {
            throw new Exception("Error in base64Encode" + e.Message);
        }
    }

二:JS部分

//***************************************************************************************
// Autor:Tecky
// Date:2008-06-03
// Desc:xxtea 算法的js加密处理类,还包含了UtfParser类,还包含了Base64类// e-mail:[email protected]
//
// var prefix = xt
//
//  update:
//
//
//***************************************************************************************

function Xxtea(privateKey) {
    this._keyString = privateKey;
}

//将长整形转换为string,private
Xxtea.prototype._long2str = function (v, w) {
    var vl = v.length;
    var n = (vl - 1) << 2;
    if (w) {
        var m = v[vl - 1];
        if ((m < n - 3) || (m > n)) return null;
        n = m;
    }
    for (var i = 0; i < vl; i++) {
        v[i] = String.fromCharCode(v[i] & 0xff,
                                   v[i] >>> 8 & 0xff,
                                   v[i] >>> 16 & 0xff,
                                   v[i] >>> 24 & 0xff);
    }
    if (w) {
        return v.join(‘‘).substring(0, n);
    }
    else {
        return v.join(‘‘);
    }
}

//将string转换为long,private
Xxtea.prototype._str2long = function (s, w) {
    var len = s.length;
    var v = [];
    for (var i = 0; i < len; i += 4) {
        v[i >> 2] = s.charCodeAt(i)
                  | s.charCodeAt(i + 1) << 8
                  | s.charCodeAt(i + 2) << 16
                  | s.charCodeAt(i + 3) << 24;
    }
    if (w) {
        v[v.length] = len;
    }
    return v;
}

//function: encrypt str with private key by xxtea
Xxtea.prototype.xxtea_encrypt = function (str) {
    if (str == "") {
        return "";
    }
    str = Base64.encode64(UtfParser.utf16to8(str));
    var v = this._str2long(str, true);
    var k = this._str2long(this._keyString, false);
    if (k.length < 4) {
        k.length = 4;
    }
    var n = v.length - 1;

var z = v[n], y = v[0], delta = 0x9E3779B9;
    var mx, e, p, q = Math.floor(6 + 52 / (n + 1)), sum = 0;
    while (0 < q--) {
        sum = sum + delta & 0xffffffff;
        e = sum >>> 2 & 3;
        for (p = 0; p < n; p++) {
            y = v[p + 1];
            mx = (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
            z = v[p] = v[p] + mx & 0xffffffff;
        }
        y = v[0];
        mx = (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
        z = v[n] = v[n] + mx & 0xffffffff;
    }

return Base64.encode64(this._long2str(v, false));
}

//function: decrypt str with private key by xxtea
Xxtea.prototype.xxtea_decrypt = function (str) {
    if (str == "") {
        return "";
    }
    str = Base64.decode64(str);
    var v = this._str2long(str, false);
    var k = this._str2long(this._keyString, false);
    if (k.length < 4) {
        k.length = 4;
    }
    var n = v.length - 1;

var z = v[n - 1], y = v[0], delta = 0x9E3779B9;
    var mx, e, p, q = Math.floor(6 + 52 / (n + 1)), sum = q * delta & 0xffffffff;
    while (sum != 0) {
        e = sum >>> 2 & 3;
        for (p = n; p > 0; p--) {
            z = v[p - 1];
            mx = (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
            y = v[p] = v[p] - mx & 0xffffffff;
        }
        z = v[n];
        mx = (z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z);
        y = v[0] = v[0] - mx & 0xffffffff;
        sum = sum - delta & 0xffffffff;
    }

return UtfParser.utf8to16(Base64.decode64(this._long2str(v, true)));
}

//Class:utf16 to utf8, utf8 ot utf16
//Author:Tecky
//Date:2008-06-03
function UtfParser() {
    //all method is static
}

//function:change utf16 to utf8
//parms(str):string that you want to change
UtfParser.utf16to8 = function (str) {
    var out, i, len, c;

out = "";
    len = str.length;
    for (i = 0; i < len; i++) {
        c = str.charCodeAt(i);
        if ((c >= 0x0001) && (c <= 0x007F)) {
            out += str.charAt(i);
        }
        else if (c > 0x07FF) {
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
            out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        }
        else {
            out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        }
    }
    return out;
}

//function:change utf8 to utf16
//parms(str):string that you want to change
UtfParser.utf8to16 = function (str) {
    str = str.toString();

var out, i, len, c;
    var char2, char3;

out = "";
    len = str.length;
    i = 0;
    while (i < len) {
        c = str.charCodeAt(i++);
        switch (c >> 4) {
            case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
                // 0xxxxxxx
                out += str.charAt(i - 1);
                break;
            case 12: case 13:
                // 110x xxxx   10xx xxxx
                char2 = str.charCodeAt(i++);
                out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
                break;
            case 14:
                // 1110 xxxx  10xx xxxx  10xx xxxx
                char2 = str.charCodeAt(i++);
                char3 = str.charCodeAt(i++);
                out += String.fromCharCode(((c & 0x0F) << 12) |
                               ((char2 & 0x3F) << 6) |
                               ((char3 & 0x3F) << 0));
                break;
        }
    }

return out;
}

// Class:base64 encode & decode
// Autor:Tecky
// Date:2008-06-03
function Base64() {
    //all method is static
}

//static
Base64._keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
Base64.encode64 = function (input) {
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;

do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

output = output +
           Base64._keyStr.charAt(enc1) +
           Base64._keyStr.charAt(enc2) +
           Base64._keyStr.charAt(enc3) +
           Base64._keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
    } while (i < input.length);

return output;
}

Base64.decode64 = function (input) {
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;

// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
    var base64test = /[^A-Za-z0-9\+\/\=\n]/g;
    if (base64test.exec(input)) {
        alert("There were invalid base64 characters in the input text.\n" +
              "Valid base64 characters are A-Z, a-z, 0-9, ‘+‘, ‘/‘,and ‘=‘\n" +
              "Expect errors in decoding.");
    }
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

do {
        enc1 = Base64._keyStr.indexOf(input.charAt(i++));
        enc2 = Base64._keyStr.indexOf(input.charAt(i++));
        enc3 = Base64._keyStr.indexOf(input.charAt(i++));
        enc4 = Base64._keyStr.indexOf(input.charAt(i++));

chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

output = output + String.fromCharCode(chr1);

if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";

} while (i < input.length);

return output;
}

时间: 2024-11-13 06:51:04

Xxtea加解密的相关文章

基于新唐M0的XXTEA加密解密算法源码

源:基于新唐M0的XXTEA加密解密算法源码 /*--------------------------------------------------------------------------------------------------------- 在数据的加解密领域,算法分为对称密钥与非对称密钥两种.对称密钥与非对称密钥由于各自的特点,所应用的领域是不尽相 同的.对称密钥加密算法由于其速度快,一般用于整体数据的加密,而非对称密钥加密算法的安全性能佳,在数字签名领域得到广 泛的应用.

在线加解密工具

推荐一个在线加解密的网站:http://tool.bugku.com/ 支持以下功能: 代码着色 凯撒栅栏维吉尼亚等密码 摩斯密码在线加解密 Brainfuck和Ook加解密 在线密码攻击器 XSS平台 JSFuck在线加解密工具 HTTPHeader信息检测 个人JS加解密 CSS压缩/格式化 Javascript工具 Javascript加密/解密 html代码在线调试 HTML/JS转换工具 base64加密 脚本密钥加密 散列/哈希加密解密 MD5网页加密 XXTEA网页加密 字串符脚本

超强php加解密扩展:cryptopp

cryptopp是一个用c++编写的超强加解密扩展.性能优异可靠.完全可以替换所有PHP编写的加解密类.不仅如此,它的提供的编程接口非常简明易用,可说是PHP程序员必备扩展. cryptopp扩展的接口如下: class cryptopp { public function __construct($param); public function setkey($param); public function encode($param); public function decode($par

【转】 Java 进行 RSA 加解密时不得不考虑到的那些事儿

[转] Java 进行 RSA 加解密时不得不考虑到的那些事儿 1. 加密的系统不要具备解密的功能,否则 RSA 可能不太合适 公钥加密,私钥解密.加密的系统和解密的系统分开部署,加密的系统不应该同时具备解密的功能,这样即使黑客攻破了加密系统,他拿到的也只是一堆无法破解的密文数据.否则的话,你就要考虑你的场景是否有必要用 RSA 了. 2. 可以通过修改生成密钥的长度来调整密文长度 生成密文的长度等于密钥长度.密钥长度越大,生成密文的长度也就越大,加密的速度也就越慢,而密文也就越难被破解掉.著名

aes加解密 Illegal key size

做aes加密时,发生一个奇怪的错误,在本地环境是好的,发布到测试环境就出问题, java.security.InvalidKeyException: Illegal key size 想到本地环境之前也是遇到加密问题,从oracle官网下载了两个文件,覆盖本地文件得到解决. 推测测试环境肯定也是此原因,照此方法,测试环境aes加解密问题得到解决,特此记录下来,避免下次再踩坑. 问题背景: Java几乎各种常用加密算法都能找到对应的实现.因为美国的出口限制,Sun通过权限文件(local_poli

rsa互通密钥对生成及互通加解密(c#,java,php)

摘要 在数据安全上rsa起着非常大的作用,特别是数据网络通讯的安全上.当异构系统在数据网络通讯上对安全性有所要求时,rsa将作为其中的一种选择,此时rsa的互通性就显得尤为重要了. 本文参考网络资料,提供了rsa互通性的一种可行的解决方案(c#,java,php),而这种互通性是在一定的局限性上达成的,比如密钥是1024位的(更高位没试过,应该也可行),基于PKCS1填充方式. 所编写的代码有一部分使用了硬编码,同时注重了功能的实现,在类结构设计上关注不多,有需要的可自行修改重构. 相关的程序集

DES加解密算法的简单实现

前几天刚写完一个简单的DES算法的实验,拿来作为第一次发到博客的随笔,填充一下空空如也的博客,献丑了 因为主要目的是Easy-To-Understand,再现一个直观的DES加解密的过程,所以很浪费地每一个数据位都用一个short整型存储,用来理ying解fu过zuo程ye就好(虽说DES这种对称加密算法十多年前就已经被淘汰了,现在一般建议用AES或者DES3 “1973 年,美国国家标准局(NBS)开始征集一种标准的数据加密标准算法(DES),以用于非机密性政府机构.商业部门和民间的对非机密的

实验五 TCP传输及加解密

北京电子科技学院(BESTI) 实     验    报     告 课程:Java程序设计                         班级:1353            姓名:陈巧然      学号:20135310 成绩:             指导教师:娄佳鹏              实验日期:2015.6.9 实验密级:         预习程度:             实验时间:15:20-18:00 仪器组次:10          必修/选修:            

openssl 加解密学习笔记

首先最近接到一个项目,这个项目中需要用到RSA的加密解密,因为之前没有接触过,在网上找了些资料,然后自己测试后发现其实使用openssl来进行加解密挺简单的,但是网上百度出来的很多又是一样的,有时候帮助不是很大,所以才想要写下来自己在搞整个加密过程遇到的一些问题,方便自己以后回头查看,也可能会帮到遇到同样的童鞋. 废话不多说,我接到的这个项目呢,有几个地方是需要用到RSA的加解密.1.使用.pfx格式的私钥签名.2.使用.cer的公钥文件进行加密操作.3.使用给定的指数与模进行公钥加密.下面有些