C# Byte[] 到 URL 友好字符串

发布于 2024-08-14 12:44:26 字数 729 浏览 7 评论 0原文

我正在为一个简单的网站开发一个快速验证码生成器,我希望在页面的 URL 中传递一个加密密钥。我可能可以很容易地将其作为查询字符串参数来执行,但我希望不要太简单(只是因为查询字符串中没有其他内容)...

我的加密代码生成一个 byte[],然后使用 Convert 对其进行转换。 ToBase64String(byte[]) 转换为字符串。然而,这个字符串仍然不太适合 url,因为它可以包含“/”和“=”等内容。有谁知道 .NET 框架中有更好的函数可以将字节数组转换为 url 友好的字符串吗?

我了解有关 System.Web.HttpUtility.UrlEncode() 及其等效项的所有信息,但是,它们只能与查询字符串参数一起正常工作。如果我对路径内的“=”进行 url 编码,我的 Web 服务器会返回 400 Bad Request 错误。

无论如何,这不是一个关键问题,但希望有人能给我一个很好的解决方案

**编辑:为了绝对确定我正在对字符串做什么,我想我会提供更多信息。

我的加密算法产生的 byte[] 应该通过某种算法输入,使其成为 url 友好的字符串。此后,它成为 XElement 的内容,然后用作 XSLT 转换的源文档,并用作锚点的 href 属性的一部分。我不认为 xslt 转换会导致问题,因为路径上通过的内容似乎是编码的查询字符串参数,但会导致 HTTP 400

我还在 base64 字符串上尝试过 HttpUtility.UrlPathEncode() ,但这似乎也不起作用(我的网址中仍然有“/”)**

I'm working on a quick captcha generator for a simple site I'm putting together, and I'm hoping to pass an encrypted key in the url of the page. I could probably do this as a query string parameter easy enough, but I'm hoping not too (just because nothing else runs off the query string)...

My encryption code produces a byte[], which is then transformed using Convert.ToBase64String(byte[]) into a string. This string, however, is still not quite url friendly, as it can contain things like '/' and '='. Does anyone know of a better function in the .NET framework to convert a byte array to a url friendly string?

I know all about System.Web.HttpUtility.UrlEncode() and its equivalents, however, they only work properly with query string parameters. If I url encode an '=' inside of the path, my web server brings back a 400 Bad Request error.

Anyways, not a critical issue, but hoping someone can give me a nice solution

**EDIT: Just to be absolutely sure exactly what I'm doing with the string, I figured I would supply a little more information.

The byte[] that results from my encryption algorithm should be fed through some sort of algorithm to make it into a url friendly string. After this, it becomes the content of an XElement, which is then used as the source document for an XSLT transformation, and is used as a part of the href attribute for an anchor. I don't believe the xslt transformation is causing the issues, since what is coming through on the path appears to be an encoded query string parameter, but causes the HTTP 400

I've also tried HttpUtility.UrlPathEncode() on a base64 string, but that doesn't seem to do the trick either (I still end up with '/'s in my url)**

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

温柔一刀 2024-08-21 12:44:26

您正在 System.Web 中查找 HttpServerUtility.UrlTokenEncodeHttpServerUtility.UrlTokenDecode

它们以 Base64 进行编码,将潜在危险的“+”和“/”字符替换为“-”和“_”。

MSDN 文档

You're looking for HttpServerUtility.UrlTokenEncode and HttpServerUtility.UrlTokenDecode, in System.Web.

They encode in base64, replacing the potentially dangerous '+' and '/' chars with '-' and '_' instead.

MSDN documentation

深府石板幽径 2024-08-21 12:44:26

对于 ASP.NET Core 6.0+ 使用 Microsoft.AspNetCore.WebUtilities .WebEncoders

byte[] bytes = RandomNumberGenerator.GetBytes(64);

string encoded = WebEncoders.Base64UrlEncode(bytes);
byte[] decoded = WebEncoders.Base64UrlDecode(encoded);

For ASP.NET Core 6.0+ use Microsoft.AspNetCore.WebUtilities.WebEncoders:

byte[] bytes = RandomNumberGenerator.GetBytes(64);

string encoded = WebEncoders.Base64UrlEncode(bytes);
byte[] decoded = WebEncoders.Base64UrlDecode(encoded);
鲜肉鲜肉永远不皱 2024-08-21 12:44:26

看看 System.BitConverter.ToString(myByteArray)

对于哈希之类的东西进行一种方式编码很方便,但正如 ssg 指出的那样,它不是很有效。对于大量数据,我不推荐它。

Have a look at System.BitConverter.ToString(myByteArray)

Handy for one way encoding for things like hashes but as pointed out by ssg it's not very efficient. I wouldn't recommend it for large amounts of data.

陈甜 2024-08-21 12:44:26

自 .NET 6 起,HttpServerUtility.UrlTokenEncode 及类似内容在 .NET Core 中不再可用。
以下方法应基于快速读取提供符合 RFC4648§5 的 base64 字符串。

此代码在堆上分配至少四个对象,因此超高性能用例应该稍微调整它,也许等待 .NET 7,它预计会引入一种将随机字节放入 Span 中以进行堆栈分配的方法。

private string GetUrlSafeRandomBytes(int byteCount)
{
    var salt = new byte[byteCount];
    using var rng = RandomNumberGenerator.Create();
    rng.GetBytes(salt);
    var asBase64 = Convert.ToBase64String(salt);
    var asUrlSafeString = asBase64.Replace('+', '-').Replace('/', '_');
    return asUrlSafeString;
}

HttpServerUtility.UrlTokenEncode and similar are no longer available in .NET Core as of .NET 6.
The following method should provide an RFC4648§5-compliant base64 string based on a quick reading.

This code allocates at least four objects on the heap, so ultra-high performance use cases should tune it a bit and perhaps wait for .NET 7, which is expected to introduce a means to get the random bytes into a Span for stack allocation.

private string GetUrlSafeRandomBytes(int byteCount)
{
    var salt = new byte[byteCount];
    using var rng = RandomNumberGenerator.Create();
    rng.GetBytes(salt);
    var asBase64 = Convert.ToBase64String(salt);
    var asUrlSafeString = asBase64.Replace('+', '-').Replace('/', '_');
    return asUrlSafeString;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文