Encode and decode in c # asp.net?

I use encoding and decoding:

For coding:

private string EncodeServerName(string ServerName) { byte[] NameEncodein = new byte[ServerName.Length]; NameEncodein = System.Text.Encoding.UTF8.GetBytes(ServerName); string EcodedName = Convert.ToBase64String(NameEncodein); return EcodedName; } 

and decoding:

  public string DecoAndGetServerName(string Servername) { System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); System.Text.Decoder strDecoder = encoder.GetDecoder(); byte[] to_DecodeByte = Convert.FromBase64String(Servername); int charCount = strDecoder.GetCharCount(to_DecodeByte, 0, to_DecodeByte.Length); char[] decoded_char = new char[charCount]; strDecoder.GetChars(to_DecodeByte, 0, to_DecodeByte.Length, decoded_char,0); string Name = new string(decoded_char); return Name; } 

I am sending server_name: DEV-SQL1\SQL2008

It is encoded: REVWLVNRTDFcU1FMMjAwOA==

Again I want to decode, but I get an exception: in the line:

byte[] to_DecodeByte = Convert.FromBase64String(Servername);

IS exception:

`The input is not a valid Base-64 string, since it contains a non-base character 64,

more than two whitespace characters or a non-white space among whitespace characters.

How to solve this problem.

Please help me

+6
source share
2 answers

Your code seems too complicated :-), this is what works:

 public static string EncodeServerName(string serverName) { return Convert.ToBase64String(Encoding.UTF8.GetBytes(serverName)); } public static string DecodeServerName(string encodedServername) { return Encoding.UTF8.GetString(Convert.FromBase64String(encodedServername)); } 
+16
source

the same code that you wrote in DecoAndGetServerName() works for me.

thing, you need to pass ENCODED STRING to your DecoAndGetServerName() function,

which can be encoded as:

 string Servername=Convert.ToBase64String(Encoding.UTF8.GetBytes("serverName")); 

That's why you got this error. The input is not a valid Base-64 string as it contains a non-base 64 character,...

0
source

Source: https://habr.com/ru/post/895833/


All Articles