Delphi · 2025年2月19日

Delphi生成随机密钥

//ALen传入密钥长度;长度一般不要太短 一般6~8字符比较合适
function GenerateRandomPassword(ALen:Byte): string;
const
  SpecialChars = '~!@#$%^&*()_-+={}[]:;<>,.?/|'; // 特殊符号集合
var
  i: Integer;
begin
  SetLength(Result, ALen);
  for i := 1 to ALen do
  begin
    if i = 1 then
    begin
      //第一个字符只能是大写
      case Random(1) of // 随机选择生成数字、大写字母还是特殊符号
        0: Result[i] := Char(65 + Random(26)); // 大写字母: 65-90
      end;
    end
    else
    begin
      case Random(4) of // 随机选择生成数字、大写字母还是特殊符号
        0: Result[i] := Char(48 + Random(10)); // 数字: 48-57
        1: Result[i] := Char(65 + Random(26)); // 大写字母: 65-90
        2: Result[i] := Char(97 + Random(26)); // 小写字母: 97-123
        3: Result[i] := SpecialChars[1 + Random(SpecialChars.Length)]; // 特殊符号
      end;
    end;
  end;
end;
Python