最近在做一个关于密码加密和解密的winform,要求对密码的TextBox输入的字符串进行加密,同时传值得时候也要解析出来,于是就写了一个demo,仅供参考。
EncryptOrDecryptPassword类包含加密和解密两个简单的方法,这个方法是根据字符的Encoding来加密的,然后在main函数中调用。
EncryptOrDecryptPassword类如下:
1 public class EncryptOrDecryptPassword 2 { 3 public string DecryptPassword(string password) 4 { 5 try 6 { 7 UTF8Encoding encode = new UTF8Encoding(); 8 Decoder utf8Decode = encode.GetDecoder(); 9 byte[] decodeByte = Convert.FromBase64String(password); 10 int charCount = utf8Decode.GetCharCount(decodeByte, 0, decodeByte.Length); 11 char[] decodeChar = new char[charCount]; 12 utf8Decode.GetChars(decodeByte, 0, decodeByte.Length, decodeChar, 0); 13 string result = new String(decodeChar); 14 return result; 15 } 16 catch (Exception ex) 17 { 18 throw new Exception("Error in decoding password:" + ex.Message); 19 } 20 } 21 22 public string EncryptedPwd(string password) 23 { 24 try 25 { 26 byte[] en_Data = new byte[password.Length]; 27 en_Data = Encoding.UTF8.GetBytes(password); 28 string encodedData = Convert.ToBase64String(en_Data); 29 return encodedData; 30 } 31 catch (Exception ex) 32 { 33 throw new Exception("Error in encode password: " + ex.Message); 34 } 35 36 } 37 }
Program 类如下:
1 class Program 2 { 3 static string inPassword = string.Empty; 4 static string outPassword = string.Empty; 5 static void Main(string[] args) 6 { 7 Console.WriteLine("Please input your password:"); 8 inPassword = Console.ReadLine(); 9 EncryptOrDecryptPassword encrytOrDecryptPassword = new EncryptOrDecryptPassword(); 10 string tempPWD = encrytOrDecryptPassword.EncryptedPwd(inPassword); 11 Console.WriteLine(tempPWD); 12 outPassword = encrytOrDecryptPassword.DecryptPassword(tempPWD); 13 Console.WriteLine(outPassword); 14 Console.ReadKey(); 15 } 16 }
随便输入字符串Debug:
时间: 2024-10-05 23:46:22