-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathFastGuid.String.cs
More file actions
66 lines (53 loc) · 2.6 KB
/
FastGuid.String.cs
File metadata and controls
66 lines (53 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Runtime.InteropServices;
namespace SecurityDriven
{
public static partial class FastGuid
{
// Copyright (c) 2025 Stan Drapkin
// LICENSE: https://github.com/sdrapkin/SecurityDriven.FastGuid
/// <summary>Generates random text strings using Base16/Base32/Base64/Base64Url alphabets.</summary>
public static class StringGen
{
// RFC 4648 alphabets
const string Base16 = "0123456789ABCDEF";
const string Base32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
const string Base32c = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; // Crockford Base32
const string Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const string Base64Url = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
// Repeat the alphabets to 256 bytes
const string Base16_256 =
Base16 + Base16 + Base16 + Base16 +
Base16 + Base16 + Base16 + Base16 +
Base16 + Base16 + Base16 + Base16 +
Base16 + Base16 + Base16 + Base16;
const string Base32_256 =
Base32 + Base32 + Base32 + Base32 +
Base32 + Base32 + Base32 + Base32;
const string Base32c_256 =
Base32c + Base32c + Base32c + Base32c +
Base32c + Base32c + Base32c + Base32c;
const string Base64_256 = Base64 + Base64 + Base64 + Base64;
const string Base64Url_256 = Base64Url + Base64Url + Base64Url + Base64Url;
static string TextAlphabet256(int length, string alphabet256) =>
string.Create(length, alphabet256,
static (charSpan, _alphabet256) =>
{
Span<byte> byteSpan = MemoryMarshal.AsBytes(charSpan).Slice(charSpan.Length);
FastGuid.Fill(byteSpan);
for (int i = 0; i < charSpan.Length; ++i)
charSpan[i] = _alphabet256[byteSpan[i]];
});
/// <summary>Generates a random text string using Base16 alphabet.</summary>
public static string Text16(int length) => TextAlphabet256(length, Base16_256);
/// <summary>Generates a random text string using Base32 alphabet.</summary>
public static string Text32(int length) => TextAlphabet256(length, Base32_256);
/// <summary>Generates a random text string using Base32 Crockford alphabet.</summary>
public static string Text32c(int length) => TextAlphabet256(length, Base32c_256);
/// <summary>Generates a random text string using Base64 alphabet.</summary>
public static string Text64(int length) => TextAlphabet256(length, Base64_256);
/// <summary>Generates a random text string using Base64Url alphabet.</summary>
public static string Text64Url(int length) => TextAlphabet256(length, Base64Url_256);
}// static class StringGen
}//class FastGuid
}//ns