现在的位置: 首页 > 综合 > 正文

加密和解密(delphi实现)

2017年12月02日 ⁄ 综合 ⁄ 共 1075字 ⁄ 字号 评论关闭
//加密流程:先把每个字符与自己在字符串中的位置异或运算,然后再与密钥进行异或运算
//然后把密钥加在最后,最后把所得的结果进行base64编码
//解密时反之:先解码,再解密。
function TfrmClassRoom.CryptStr(const s: string; stype: smallint): string;
var
  i, fkey: integer;
  sInput:string;
  stream:TStringStream;
begin
  result := '';
  case stype of
    0: //加密
      begin
        randomize;
        fkey := random($FF);
        for i := 1 to length(s) do
          result := result + chr(ord(s[i]) xor i xor fkey);
        result := result + char(fkey);
        //Result := s;
        stream := TStringStream.Create(result);
        stream.Position :=0;
        Result := IdEncoderMIME1.Encode(stream);
        stream.Free;
        for i:=1 to length(result) do
          if Result[i]='/' then Result[i]:='_'
          else if Result[i]='+' then Result[i]:='!'
      end;
    1: //解密
      begin
        sInput := s;
        for i:=1 to length(sInput) do
          if sInput[i]='_' then sInput[i]:='/'
          else if sInput[i]='!' then sInput[i]:='+';
        sInput := IdDecoderMIME1.DecodeToString(sInput);
        //Result :=sinput;
        fkey := ord(sInput[length(sInput)]);
        for i := 1 to length(sInput) - 1 do
          result := result + chr(ord(sInput[i]) xor i xor fkey)
      end;
  end;
end; 

抱歉!评论已关闭.