public static string Decrypt(string orgidata, byte[] key = null, CryptoStringFormat format = CryptoStringFormat.Base64, string iv = null) { if (orgidata == null) { return null; } using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { key = GetCheckKey(key); aes.Key = key == null ? appkeykey : key; byte[] _iv = new byte[aes.BlockSize / 8]; if (string.IsNullOrEmpty(iv)) { Array.Copy(aes.Key, 0, _iv, 0, _iv.Length); } else { byte[] pIV = Encoding.GetBytes(iv); if (pIV.Length == _iv.Length) { _iv = pIV; } else if (pIV.Length > _iv.Length) { Array.Copy(pIV, 0, _iv, 0, _iv.Length); } else if (pIV.Length < _iv.Length) { Array.Copy(pIV, 0, _iv, 0, pIV.Length); for (int i = pIV.Length; i < _iv.Length; i++) { _iv[i] = 48; } } } aes.Mode = cipherMode; aes.Padding = paddingMode; aes.IV = _iv; using (ICryptoTransform transform = aes.CreateDecryptor()) { byte[] data = null; try { byte[] orgi = null; switch (format) { case CryptoStringFormat.Base64: orgi = Convert.FromBase64String(orgidata); break; case CryptoStringFormat.Encoding: orgi = Encoding.GetBytes(orgidata); break; } data = transform.TransformFinalBlock(orgi, 0, orgi.Length); } catch (Exception ex) { Log.WriteException(ex); return null; } aes.Clear(); if (data != null) return Encoding.GetString(data); return null; } } }
public static string Encrypt(string orgidata, byte[] key = null, CryptoStringFormat format = CryptoStringFormat.Base64, string iv = null) { if (orgidata == null) { return null; } try { byte[] orgi = Encoding.GetBytes(orgidata); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = GetCheckKey(key); des.IV = string.IsNullOrEmpty(iv) ? _iv : Encoding.GetBytes(iv); using (ICryptoTransform transform = des.CreateEncryptor()) { byte[] data = transform.TransformFinalBlock(orgi, 0, orgi.Length); if (data != null) { des.Clear(); switch (format) { case CryptoStringFormat.Base64: return Convert.ToBase64String(data); case CryptoStringFormat.Encoding: return Encoding.GetString(data); } } } } orgi = null; } catch (Exception ex) { Log.WriteException(ex); } return null; }