我可以使用哪些编码压缩一个数字,URL和Cookie安全吗? [英] What encoding can I use to compact a number that is URL and Cookie safe?
问题描述
我试图找到一种方法,把一些在URL和/或饼干也是目前唯一的方法我是用普通十六进制编码( 00-01 -...- FF
)。我打算用Base64的,但发现它不是安全的网址或饼干。
I'm trying to find a way to place a number in a URL and/or cookie and currently the only method I have is using regular hex encoding (00-01-...-FF
). I was going to use Base64 but discovered that it's not safe in URLs or cookies.
什么是编码类似的base64我可以使用的URL和cookie的安全吗? (只使用0-9,AZ,AZ)另外,加分对他们是一间codeR /日codeR在.NET库:)编码
What is an encoding similar to base64 I can use that is URL and cookie safe? (using only 0-9,a-z,A-Z) Also, bonus points for their being an encoder/decoder for the encoding in the .Net library :)
推荐答案
为什么不使用Base64的,但转换 +
和 /
字符 -
和 _
,分别是多少?请参见 http://en.wikipedia.org/wiki/Base64#Variants_summary_table 的说明
Why not use Base64, but convert the +
and /
characters to -
and _
, respectively? See http://en.wikipedia.org/wiki/Base64#Variants_summary_table for a description.
这是pretty的常用的,也许是最有名的由YouTube对他们的视频的ID。
This is pretty commonly used, perhaps most famously by YouTube for their video ids.
这code变为一个64位的值转换成一个base64连接codeD密钥,使用该转换:
This code turns a 64-bit value into a base64 encoded key, using that conversion:
public static string Base64EncodeKey(ulong key)
{
// get bytes
byte[] keyBytes = BitConverter.GetBytes(key);
// get base64 value
string keyString = Convert.ToBase64String(keyBytes);
// The base64 encoding has a trailing = sign, and + and - characters.
// Strip the trailing =.
keyString = keyString.Substring(0, keyString.Length - 1);
// convert + to - (dash) and / to _ (underscore)
keyString = keyString.Replace('+', '-');
keyString = keyString.Replace('/', '_');
return keyString;
}
反向转动的EN codeD密钥回到 ULONG
:
public static ulong Base64DecodeKey(string keyString)
{
// convert - to +, and _ to /
keyString = keyString.Replace('-', '+');
keyString = keyString.Replace('_', '/');
// add the trailing =
keyString += '=';
// convert to bytes
byte[] keyBytes = Convert.FromBase64String(keyString);
// get the encoded key
ulong encodedKey = BitConverter.ToUInt64(keyBytes, 0);
return encodedKey;
}
您可以做的32位密钥类似的东西。
You can do something similar with 32-bit keys.
更新:
我看到你说有一个不同的字节数。如果您知道该值始终是32位或更少(或64位或更少),你可能会更好用我上面描述的技术。如果你真的需要连接codeA变长字符串,你仍然可以使用替换修改后的base64编码方案 +
和 /
与 -
和 _
。请参见 RFC 4648 获得其他建议。
I see that you said there's a varying number of bytes. If you know that the value is always 32 bits or less (or 64 bits or less), you're probably better off using the technique I described above. If you really need to encode a varying length string, you can still use the modified base64 encoding scheme that replaces +
and /
with -
and _
. See RFC 4648 for other recommendations.
这篇关于我可以使用哪些编码压缩一个数字,URL和Cookie安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!