如何将整数加密为一个五个字符的字符串? [英] How do you encrypt an integer to a string of five characters?
问题描述
我需要一个C#方法将一个整数加密到一个字符串的五个字符,其中有效的字符是az,AZ,0-9
I need a C# method to encrypt an integer to a string of five characters where valid characters are a-z, A-Z, 0-9
我需要这样做,因为我发送的URL给这样的用户...
I need to do this because I am sending URLs to users that look like this...
http://www.website.com.au/3
用户将在此URL查看特定于此的URL的数据。数据不是超敏感的,但是通过输入下一个数字来查看别人的广播是不可接受的:
Users will see data at this URL that is specific to them. The data is not ultra sensitive, but it is seen as unacceptable to view someone else's broadcast simply by entering the next number:
http://www.website.com.au/4
然而,还需要保留URL的缩写可读,因为URL可以通过短信向您发送,我们不想通过大量长的加密值来消除文本消息空间,因此
However there is also a need to keep the URL's short and readable as the URLs could reach you via a text message and we don't want to loose text message space by a massively long encrypted value so
http://www.website.com.au/3
可能成为
http://www.website.com.au/a6Yqo
我意识到这个级别的加密相当薄弱,但对于这些广播来说这是非常好的
I realise this level of encryption is quite weak but it is good enough for these broadcasts
public string Encrypt(int number)
{
}
public int Decrypt(string encrypted)
{
}
我从哪里开始?
推荐答案
不完全是你需要的,但会做这个工作/ p>
Not exactly what you need but will do the job
public static string Encrypt(int value)
{
return Convert.ToBase64String(BitConverter.GetBytes(value)).Replace("==","");
}
public static int Decrypt(string value)
{
if(value.Length!=6)
throw new ArgumentException("Invalid length.");
return BitConverter.ToInt32(Convert.FromBase64String(value + "=="),0);
}
结果:
0 : AAAAAA
1 : AQAAAA
2 : AgAAAA
3 : AwAAAA
4 : BAAAAA
5 : BQAAAA
6 : BgAAAA
7 : BwAAAA
8 : CAAAAA
9 : CQAAAA
10 : CgAAAA
11 : CwAAAA
12 : DAAAAA
13 : DQAAAA
14 : DgAAAA
15 : DwAAAA
16 : EAAAAA
17 : EQAAAA
18 : EgAAAA
19 : EwAAAA
20 : FAAAAA
21 : FQAAAA
22 : FgAAAA
23 : FwAAAA
24 : GAAAAA
这篇关于如何将整数加密为一个五个字符的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!