将密码学 vb.net 转换为 C#

convert cryptography vb.net to c#

我在 Vb.net 中有一个密码学 class 可以正常工作,但我需要在 c# 代码中进行转换。 我的 Vb.net 方法是这样的:

   Public Shared Function CryptSenha(ByVal strCdSenha As String) As String


        Dim Chave As String

        Const MIN_ASC = 48
        Const MAX_ASC = 126
        Const NUM_ASC = MAX_ASC - MIN_ASC + 1

        Chave = 2001 

        Dim offset As Long
        Dim str_len As Integer
        Dim i As Integer
        Dim ch As Integer
        Dim to_text As String

        Try
            to_text = ""
            offset = NumericPassword(Chave)
            Rnd(-1)
            Randomize(offset)
            str_len = Len(strCdSenha)

            For i = 1 To str_len 'Faça 1 até str_len
                ch = Asc(Mid$(strCdSenha, i, 1))

                'Início do If
                If ch >= MIN_ASC And ch <= MAX_ASC Then
                    ch = ch - MIN_ASC
                    offset = Int((NUM_ASC + 1) * Rnd())
                    ch = ((ch + offset) Mod NUM_ASC)
                    ch = ch + MIN_ASC
                    to_text = to_text & Chr(ch)
                End If

            Next i
            Return to_text
        Catch ex As Exception
            Throw ex
        End Try
    End Function

我的 C# 代码是这样的:

 public static string CryptSenha(string strCdSenha)
    {
    string Chave = null;

    const int MIN_ASC = 48;
    const int MAX_ASC = 126;
    const int NUM_ASC = MAX_ASC - MIN_ASC + 1;

    Chave = "2001";
    long offset = 0;
    int str_len = 0;
    int i = 0;
    int ch = 0;
    string to_text = null;

    try
    {
        to_text = "";
        offset = NumericPassword(Chave);
        VBMath.Rnd(-1);
        VBMath.Randomize(offset);
        str_len = Strings.Len(strCdSenha);

        for (i = 1; i <= str_len; i++)
        {
            ch = Strings.Asc(Strings.Mid(strCdSenha, i, 1));

            if (ch >= MIN_ASC & ch <= MAX_ASC)
            {
                ch = ch - MIN_ASC;
                offset = Convert.ToInt64((NUM_ASC + 1) * VBMath.Rnd());
                ch = Convert.ToInt16((ch + offset) % NUM_ASC);
                ch = ch + MIN_ASC;
                to_text = to_text + Strings.Chr(ch);
            }
        }

        return to_text;
}
catch (Exception ex)
{
    throw ex;
}

}

所以当我在 vb.net 中使用我的函数时,像 'Igor' 这样的简单词等于 "iLCA"

并且在函数 c# 中,单词 'Igor' 等于 "iLDB",我猜想转换

在 c# 代码的这一行中:

offset = Convert.ToInt64((NUM_ASC + 1) * VBMath.Rnd());

有人可以帮助我吗?

您对 'Int' 的转换不正确 - 'Int' 被截断了。替换下面两行代码:

offset = Convert.ToInt32(Math.Floor(Convert.ToDouble((NUM_ASC + 1) * VBMath.Rnd())));
ch = (int)((ch + offset) % NUM_ASC);