GUID来的base64为URLGUID、URL

2023-09-02 01:46:04 作者:↪别低头皇冠会掉

问:有没有更好的方式来做到这一点。

VB.Net

 功能GuidToBase64(BYVAL的GUID GUID)作为字符串
    返回Convert.ToBase64String(guid.ToByteArray).Replace(/, - )。更换(+,_)替换(=,)
端功能

功能Base64ToGuid(BYVAL的base64作为字符串)作为的Guid
    暗淡的GUID的Guid
    的base64 = base64.Replace( - ,/").Replace("_,+)及==

    尝试
        GUID =新的GUID(Convert.FromBase64String的(Base64))
    抓住EX为例外
        抛出新的异常(坏的Base64转换为GUID,恩)
    结束尝试

    返回GUID
端功能
 

C#

 公共字符串GuidToBase64(GUID GUID)
{
    。返回Convert.ToBase64String(guid.ToByteArray).Replace(/, - )更换(+,_)替换(=,);
}

公众的Guid Base64ToGuid(字符串的base64)
{
   GUID GUID =默认(GUID);
   的base64 = base64.Replace( - ,/").Replace("_,+)+==;

   尝试 {
       GUID =新的GUID(Convert.FromBase64String的(Base64));
   }
   赶上(例外前){
       抛出新的异常(坏的Base64转换为GUID,前);
   }

   返回GUID;
}
 

解决方案

据我所知,你是剪裁==到底的原因是因为你可以肯定,对于GUID(16字节),EN codeD字符串的总是的一端与==。所以2个字符可以被保存在每次转换。

除了@Skurmedal已经提到的点(应以防无效的字符串作为输入,抛出一个异常),我认为您发布的code是刚刚好够了。

SQL注入之 base64注入攻击

Question: is there a better way to do that?

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

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

解决方案

I understand that the reason you are clipping == in the end is that because you can be certain that for GUID (of 16 bytes), encoded string will always end with ==. So 2 characters can be saved in every conversion.

Beside the point @Skurmedal already mentioned (should throw an exception in case of invalid string as input), I think the code you posted is just good enough.