code学习

在C#中实现Java中Base64.encodeBase64URLSafe

public class ConvertHelper
{
    /// <summary>
    /// 将Java安全的base64字符串转换为byte数组
    /// </summary>
    /// <param name="convert"></param>
    /// <param name="javaURLSafeString"></param>
    /// <returns></returns>
    public static byte[] FromBase64StringURLSafe(string javaURLSafeString)
    {
        javaURLSafeString = javaURLSafeString.Replace("-", "+").Replace("_", "/");
        var base64 = Encoding.ASCII.GetBytes(javaURLSafeString);
        var padding = base64.Length * 3 % 4;//(base64.Length*6 % 8)/2
        if (padding != 0)
        {
            javaURLSafeString = javaURLSafeString.PadRight(javaURLSafeString.Length + padding, '=');
        }
        return Convert.FromBase64String(javaURLSafeString);
    }

    /// <summary>
    /// 将byte数组转换为java安全的base64字符串
    /// </summary>
    /// <param name="convert"></param>
    /// <param name="bytes"></param>
    /// <returns></returns>
    public static string ToBase64StringURLSafe(byte[] bytes)
    {
        string base64String = Convert.ToBase64String(bytes);
        return base64String.Replace("+", "-")
            .Replace("/", "_")
            .Replace("=", "");
    }
}      

通过代码我们可以明显看出,实际上就是对+、/、=进行了特殊处理。

原文地址:https://www.cnblogs.com/duanjt/p/13339438.html

http://t.zoukankan.com/duanjt-p-13339438.html

继续阅读