加密解密 Delphi C# 兼容互转

来源:互联网 发布:淘宝网能不能微信支付 编辑:程序博客网 时间:2024/05/16 08:32
Delphi:

function strtohstr(s: string): string;
var
  i: integer;
  r: byte;
begin
  Randomize;
  r := Random(60) + 35;
  result := '';
  for i := 1 to length(s) do
  begin
    s[i] := chr(ord(s[i]) xor r);
    s[i] := chr(ord(s[i]) xor (i and $FF));
    result := result + chr(((ord(s[i]) and $F0) shr 4) + 80) + chr(((ord(s[i]) and $F)) + 89);
  end;
  result := result + chr(r);
end;

//字符解密

function hstrtostr(s: string): string;
var i: integer;
  c: char;
  r: byte;
begin
  result := '';
  if s = '' then exit;
  r := ord(s[length(s)]);
  for i := 1 to length(s) shr 1 do
  begin
    c := chr(((ord(s[i * 2 - 1]) - 80) shl 4) + (ord(s[i * 2]) - 89));
    c := chr(ord(c) xor (i and $FF));
    c := chr(ord(c) xor r);
    result := result + c;
  end;
end;

C#:
   
        //解密
        public static string HStrToStr(String sInfo)
        {
            string sResult = "";
            if (String.IsNullOrEmpty(sInfo))
            {
                return sResult = "";
            }
            int iValue = 0; byte rValue = 0;
            int iResultLen=(sInfo.Length >> 1);

            //随机密匙取出来
            rValue = (byte)(sInfo[sInfo.Length - 1]);
            for (int i = 0; i < iResultLen; i++)
            {
                //奇数数列
                int iOS = (i + 1) * 2 - 1;
                int iJS = (i) * 2;
                char cValue = (char)((((byte)(sInfo[iJS]) - 80) << 4) + ((byte)(sInfo[iOS]) - 89));
                cValue = (char)((byte)(cValue) ^ ((i+1) & 0xFF));
                cValue = (char)((byte)(cValue) ^ rValue);

                sResult += "" + cValue;
            }

            return sResult;
        }

        //加密
        public static string StrToHStr(String sInfo)
        {
            string sResult = "";
            if (String.IsNullOrEmpty(sInfo))
            {
                return sResult = "";
            }

            int iValue = 0; byte rValue = 0;
            char[] sDeal = new char[sInfo.Length];
            Random rnd = new Random();
            rValue = (byte)(rnd.Next(60) + 35);
            for (int i = 0; i < sInfo.Length; i++)
            {
                sDeal[i]=(char)((byte)sInfo[i] ^ rValue);
                sDeal[i] = (char)(((byte)sDeal[i]) ^ ((i + 1) & 0xFF));

                sResult += "" +(char)((((byte)(sDeal[i]) & 0xF0) >> 4) + 80) +(char)((((byte)(sDeal[i]) & 0x0F)) + 89);
            }
            //随机密匙放在最后一位。
            sResult += "" + (char)rValue;
            return sResult;
        }
0 0
原创粉丝点击