title: Code for decoding/encoding a modified base64 URL (in ASP.NET Framework)
body: <p>I want to base64 encode data to put it in a URL and then decode it within my HttpHandler.</p>
  
  <p>I have found that <a href="http://en.wikipedia.org/wiki/Base64" rel="noreferrer">Base64 Encoding</a> allows for a '/' character which will mess up my UriTemplate matching.  Then I found that there is a concept of a "modified Base64 for URL" from wikipedia:</p>
  
  <p>A modified Base64 for URL variant exists, where no padding '=' will be used, and the '+' and '/' characters of standard Base64 are respectively replaced by '-' and '_', so that using URL encoders/decoders is no longer necessary and has no impact on the length of the encoded value, leaving the same encoded form intact for use in relational databases, web forms, and object identifiers in general.</p>
  
  <p>Using .NET I want to modify my current code from doing basic base64 encoding and decoding to using the "modified base64 for URL" method.  Has anyone done this?</p>
  
  <p>To decode, I know it starts out with something like:</p>
  
  <pre><code>string base64EncodedText = base64UrlEncodedText.Replace('-', '+').Replace('_', '/');
  
  // Append '=' char(s) if necessary - how best to do this?
  
  // My normal base64 decoding now uses encodedText
  </code></pre>
  
  <p>But, I need to potentially add one or two '=' chars to the end which looks a little more complex.</p>
  
  <p>My encoding logic should be a little simpler:</p>
  
  <pre><code>// Perform normal base64 encoding
  byte[] encodedBytes = Encoding.UTF8.GetBytes(unencodedText);
  string base64EncodedText = Convert.ToBase64String(encodedBytes);
  
  // Apply URL variant
  string base64UrlEncodedText = base64EncodedText.Replace("=", String.Empty).Replace('+', '-').Replace('/', '_');
  </code></pre>
  
  <p>I have seen the <a href="https://stackoverflow.com/questions/1032376/guid-to-base64-for-url">Guid to Base64 for URL</a> StackOverflow entry, but that has a known length and therefore they can hardcode the number of equal signs needed at the end.</p>