/// <summary> /// Aes 加密,随机生成16位IV。 /// </summary> /// <param name="val"></param> /// <returns></returns> public static string EncryptWithKey(string enKey, string val) { // LogUtil.HWLogger.DEFAULT.InfoFormat("EncryptWithKey->enKey={0},val={1}", enKey, val); if (string.IsNullOrEmpty(val)) { return(val); } try { using (AesManaged aes = new AesManaged()) { var toEncryptBytes = Encoding.UTF8.GetBytes(val); byte[] enKeyByte = Convert.FromBase64String(enKey); aes.Key = enKeyByte; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.Zeros; aes.IV = GetSafeRandomIV(); using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV)) { using (CustomeStream ms = new CustomeStream()) { ms.Write(aes.IV, 0, 16); using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(toEncryptBytes, 0, toEncryptBytes.Length); cs.FlushFinalBlock(); byte[] bytes = (byte[])ms.ToArray(); return(Convert.ToBase64String(bytes)); } } } } } catch (CryptographicException e) { LogUtil.HWLogger.DEFAULT.Error("A Cryptographic error occurred:", e); if (string.IsNullOrWhiteSpace(val)) { return(""); } else { return(val); } } catch (FormatException fe) { LogUtil.HWLogger.DEFAULT.Error("A FormatException error occurred:", fe); if (string.IsNullOrWhiteSpace(val)) { return(""); } else { return(val); } } }
/// <summary> /// Aes解密。 /// </summary> /// <param name="val">需要解密的字符串</param> /// <returns></returns> public static string DecryptWithKey(string enKey, string val) { try { String retVal = ""; if (string.IsNullOrEmpty(val)) { return(""); } using (AesManaged aes = new AesManaged()) { byte[] inputByteArray = Convert.FromBase64String(val.Trim()); byte[] enKeyByte = Convert.FromBase64String(enKey); aes.Key = enKeyByte; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.Zeros; using (CustomeStream ms = new CustomeStream(inputByteArray)) { byte[] iv = new byte[16]; ms.Read(iv, 0, iv.Length); // Array.Copy(inputByteArray, 0, iv, 0, iv.Length); aes.IV = iv; using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV)) { using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) { using (var sr = new StreamReader(cs)) { retVal = sr.ReadToEnd().Trim('\0'); } } } } } //LogUtil.HWLogger.DEFAULT.InfoFormat("DecryptWithKey->enKey={0},val={1},retVal={2}", enKey, val, retVal); return(retVal); } catch (CryptographicException e) { LogUtil.HWLogger.DEFAULT.Error("A Cryptographic error occurred:", e); if (string.IsNullOrWhiteSpace(val)) { return(""); } else { return(val); } } catch (FormatException fe) { LogUtil.HWLogger.DEFAULT.Error("A FormatException error occurred:", fe); if (string.IsNullOrWhiteSpace(val)) { return(""); } else { return(val); } } }