/// <summary> /// Encodes a string to specified format encoding (base 32/64/etc), strings are first converted to a bom-free utf8 byte[] then to relevant encoding. /// </summary> /// <param name="type">encoding type</param> /// <param name="input">string to be encoded</param> /// <returns>Encoded string</returns> public static string EncodeString(EncodingType type, string input) { var enc = new UTF8Encoding(false, true); switch (type) { case EncodingType.Base64: return(Convert.ToBase64String(enc.GetBytes(input), Base64FormattingOptions.None)); case EncodingType.Base64Url: return(Base64Url.ToBase64ForUrlString(enc.GetBytes(input))); case EncodingType.Base32Url: return(Base32Url.ToBase32String(enc.GetBytes(input))); case EncodingType.ZBase32: return(new Base32Url(false, false, true, Base32Url.ZBase32Alphabet).Encode(enc.GetBytes(input))); case EncodingType.Base32LowProfanity: return(new Base32Url(false, true, true, Base32Url.Base32LowProfanityAlphabet).Encode(enc.GetBytes(input))); case EncodingType.Base32Crockford: return(new Base32Url(false, true, true, Base32Url.Base32CrockfordHumanFriendlyAlphabet).Encode(enc.GetBytes(input))); default: throw new NotImplementedException("Encoding type not implemented: " + type); } }
/// <summary> /// Decodes an encoded string to the original binary. /// </summary> /// <param name="type">Encoding type</param> /// <param name="input">Encoded string</param> /// <returns>Original byte[]</returns> /// <exception cref="ArgumentException">If encoding type is None, UriData, UriPathData or Uri</exception> public static byte[] Decode(EncodingType type, string input) { switch (type) { case EncodingType.Base64: return(Convert.FromBase64String(input)); case EncodingType.Base64Url: return(Base64Url.FromBase64ForUrlString(input)); case EncodingType.Base32Url: return(Base32Url.FromBase32String(input)); case EncodingType.ZBase32: return(new Base32Url(false, false, true, Base32Url.ZBase32Alphabet).Decode(input)); case EncodingType.Base32LowProfanity: return(new Base32Url(false, true, true, Base32Url.Base32LowProfanityAlphabet).Decode(input)); case EncodingType.Base32Crockford: return(new Base32Url(false, true, true, Base32Url.Base32CrockfordHumanFriendlyAlphabet).Decode(input)); default: throw new NotImplementedException("Encoding type not implemented: " + type); } }