English 中文(简体)
C# Byte[] to Url Friendly String
原标题:

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)**

最佳回答

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

问题回答

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);

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.

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;
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签