guid到base64,用于URL

Fre*_*dou 45 .net c# vb.net base64 guid

问题:有更好的方法吗?

VB.Net

Function GuidToBase64(ByVal guid As Guid) As String
    Return Convert.ToBase64String(guid.ToByteArray).Replace("/", "-").Replace("+", "_").Replace("=", "")
End Function

Function Base64ToGuid(ByVal base64 As String) As Guid
    Dim guid As Guid
    base64 = base64.Replace("-", "/").Replace("_", "+") & "=="

    Try
        guid = New Guid(Convert.FromBase64String(base64))
    Catch ex As Exception
        Throw New Exception("Bad Base64 conversion to GUID", ex)
    End Try

    Return guid
End Function
Run Code Online (Sandbox Code Playgroud)

C#

public string GuidToBase64(Guid guid)
{
    return Convert.ToBase64String(guid.ToByteArray()).Replace("/", "-").Replace("+", "_").Replace("=", "");
}

public Guid Base64ToGuid(string base64)
{
   Guid guid = default(Guid);
   base64 = base64.Replace("-", "/").Replace("_", "+") + "==";

   try {
       guid = new Guid(Convert.FromBase64String(base64));
   }
   catch (Exception ex) {
       throw new Exception("Bad Base64 conversion to GUID", ex);
   }

   return guid;
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*ead 25

您可以查看此站点:http://prettycode.org/2009/11/12/short-guid/

它看起来非常接近你正在做的事情.

public class ShortGuid
{
    private readonly Guid guid;
    private readonly string value;

    /// <summary>Create a 22-character case-sensitive short GUID.</summary>
    public ShortGuid(Guid guid)
    {
        if (guid == null)
        {
            throw new ArgumentNullException("guid");
        }

        this.guid = guid;
        this.value = Convert.ToBase64String(guid.ToByteArray())
            .Substring(0, 22)
            .Replace("/", "_")
            .Replace("+", "-");
    }

    /// <summary>Get the short GUID as a string.</summary>
    public override string ToString()
    {
        return this.value;
    }

    /// <summary>Get the Guid object from which the short GUID was created.</summary>
    public Guid ToGuid()
    {
        return this.guid;
    }

    /// <summary>Get a short GUID as a Guid object.</summary>
    /// <exception cref="System.ArgumentNullException"></exception>
    /// <exception cref="System.FormatException"></exception>
    public static ShortGuid Parse(string shortGuid)
    {
        if (shortGuid == null)
        {
            throw new ArgumentNullException("shortGuid");
        }
        else if (shortGuid.Length != 22)
        {
            throw new FormatException("Input string was not in a correct format.");
        }

        return new ShortGuid(new Guid(Convert.FromBase64String
            (shortGuid.Replace("_", "/").Replace("-", "+") + "==")));
    }

    public static implicit operator String(ShortGuid guid)
    {
        return guid.ToString();
    }

    public static implicit operator Guid(ShortGuid shortGuid)
    {
        return shortGuid.guid;
    }
}
Run Code Online (Sandbox Code Playgroud)


Joe*_*Joe 17

使用此技术格式化GUID以在URL或文件名中使用的一个问题是,两个不同的GUID可以生成两个仅在大小写不同的值,例如:

    var b1 = GuidToBase64(new Guid("c9d045f3-e21c-46d0-971d-b92ebc2ab83c"));
    var b2 = GuidToBase64(new Guid("c9d045f3-e21c-46d0-971d-b92ebc2ab8a4"));
    Console.WriteLine(b1);  // 80XQyRzi0EaXHbkuvCq4PA
    Console.WriteLine(b2);  // 80XQyRzi0EaXHbkuvCq4pA
Run Code Online (Sandbox Code Playgroud)

由于URL和文件名通常被解释为不区分大小写,因此可能会导致冲突.

  • @RogerSpurrell - 关于 URL 的好点子,但我更多的是考虑应用程序特定的 URL 处理,例如 `http://.../user/{id}`,其中 `{id}` 可能是随机的类似 guid 的 id 以避免 OWASP Brute Force Predictable Resource Location 漏洞,并且 id 可能会在不区分大小写的数据库中查找。 (3认同)
  • 这对于 URL 来说是不正确的。根据 [RFC 3986](https://tools.ietf.org/html/rfc3986#section-6.2.2.1),只有方案和主机应被视为不区分大小写。查询、片段甚至路径都应该被视为区分大小写。当然,这完全取决于您的代码/服务器实现来遵守这一点。 (2认同)

Hem*_*ant 14

我理解你最后剪切==的原因是因为你可以确定对于GUID(16字节),编码字符串总是以==结束.因此,每次转换都可以保存2个字符.

除了@Skurmedal已经提到的那一点(如果输入无效字符串应该抛出异常),我认为你发布的代码就足够了.