zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#,整数转为短字符串(Short string)的加解密算法与源代码

c#算法 string 字符串 源代码 整数 转为 加解密
2023-09-11 14:15:49 时间

网站生成的动态 URL 往往以内容序列号id为标识与参数,比如:

http://www.jerry.com/tom.aspx?id=1

使用 Web Rewrite,可以实现网页静态化,称为:

http://www.jerry.com/content/1.html

对于爬虫软件而言,这最好不过了。

即使中学生也可以从 id=1 爬到 id=10000 ,分分钟爬你个底掉。

对策之一,就是把 id  隐藏起来,转为“短字符串”就是技术之一。

http://www.jerry.com/content/9Rus3d.html

源程序:

using System;   
using System.Text;   
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// 整数转为“短字符串”
/// </summary>
public static class ShortHelper
{
    // 修改这个字符串,就可以生成与别人不同的结果!!!
    private static string cs = "m65pKkCes8VzxhGby9XNcfqPaWuE2jFYnUDT104LOdA3HIZoSvBigMwlrQ7JRt";
    private static Hashtable hash = new Hashtable();
    private static uint offset = (uint)cs.Length / 2;

    public static uint begin = 1020304050;

    public static string Encode(int v)
    {
        StringBuilder sb = new StringBuilder();
        uint va = (uint)v;
        va += begin;
        uint lastv = 0;
        while (va > 0)
        {
            uint vb = va % offset;
            va = (va - vb) / offset;
            if (sb.Length == 0) lastv = vb;
            sb.Append((sb.Length == 0) ? cs.Substring((int)vb, 1) : cs.Substring((int)(vb + lastv), 1));
        }
        return sb.ToString();
    }

    private static void Init()
    {
        for (int i = 0; i < cs.Length; i++)
        {
            hash.Add(cs.Substring(i, 1), i);
        }
    }

    public static int Decode(string s)
    {
        if (hash.Count == 0) Init();
        if (s.Length < 2) return 0;
        uint v = 0;
        uint lastv = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (i == 0) { v = (uint)((int)hash[s.Substring(i, 1)]); lastv = v; continue; }
            else { v += ((uint)((int)hash[s.Substring(i, 1)] - lastv)) * (uint)Math.Pow(offset, i); }
        }
        v -= begin;
        return (int)v;
    }
}

POWER BY TRUFFER.CN
BY 315SOFT.COM