c# – 将一串数字加密成一串字母数字
作者:互联网
我有一串数字,我想缩短在URL中使用.此字符串始终仅由数字组成.例如:9587661771112
理论上,将数字字符串加密为字母数字(0-9a-zA-Z)字符串应始终返回更短的结果,这就是我想要的.
我创建了一个执行以下操作的算法:
Encrypt ( string1 = numeric input string, string2 = alphanumeric return string)
- Takes the next two characters from string1 and converts them into a number, e.g 95 for the above example
- Checks if the number is less than 52(the combined length of a-z and A-Z)
- if so, adds (“abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”)[Number] to
string2 and jump forward by 2 characters- else, add (“0123456789)[First digit of Number) to string2 and jump forward by 1 character
在下一步中,数字将是58,依此类推.
通过一些调整,我可以获得的最短结果是:9587661771112> j9UQpjva
我的问题是,使用这种技术,结果可能会有很大差异.我也觉得这对我的问题不是一个干净的解决方案.
所以我需要一种加密算法,将一串数字转换成一个较短的大写字母,小写字母和数字串.它必须是可解密的,并且具有或多或少的一致结果.
知道怎么做到这一点?
解:
string Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
string Base10To62(long N)
{
string R = "";
while (N != 0)
{
R += Chars[(int)(N % 62)];
N /= 62;
}
return R;
}
long Base62To10(string N)
{
long R = 0;
int L = N.Length;
for (int i = 0; i < L; i++)
{
R += Chars.IndexOf(N[i]) * (long)Math.Pow(62, i);
}
return R;
}
奇迹般有效 :)
解决方法:
解:
string Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static string Base10To62(string S)
{
string R = "";
var N = long.Parse(S);
do { R += Chars[(int)(N % 0x3E)]; } while ((N /= 0x3E) != 0);
return R;
}
private static string Base62To10(string S)
{
long R = 0;
int L = S.Length;
for (int i = 0; i < L; i++) R += Chars.IndexOf(S[i]) * (long)(System.Math.Pow(0x3E, i));
return R.ToString();
}
标签:c,encoding,numeric,compression,alphanumeric 来源: https://codeday.me/bug/20190626/1289275.html