前端代码:
function formencode() { var KEY = CryptoJS.enc.Utf8.parse("1234567890123456"); var IV = CryptoJS.enc.Utf8.parse('1234567890123456'); var key = KEY; var iv = IV; var content = $("#txtSmsContent").val(); var contentEncode = CryptoJS.enc.Utf8.parse(content); var encryptedContent = CryptoJS.AES.encrypt(contentEncode, key, { iv: iv, mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }); var encryptContentBase64 = CryptoJS.enc.Base64.stringify(encryptedContent.ciphertext); $("#txtSmsContent").val(encryptContentBase64); }
后端代码:
/// <summary> /// AES 解密 /// </summary> /// <param name="str">明文(待解密)</param> /// <param name="key">密文</param> /// <returns></returns> public static string AesDecrypt(string str, string key) { if (string.IsNullOrEmpty(str)) return null; Byte[] toEncryptArray = Convert.FromBase64String(str); RijndaelManaged rm = new RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; ICryptoTransform cTransform = rm.CreateDecryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Encoding.UTF8.GetString(resultArray); }
其中我采用的是ECB模式
后台加密,传到前台解密方法在下面
后台代码:
/// <summary> /// AES 加密 /// </summary> /// <param name="str">明文(待加密)</param> /// <param name="key">密文</param> /// <returns></returns> public static string AesEncrypt(string str, string key) { if (string.IsNullOrEmpty(str)) return null; Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); RijndaelManaged rm = new RijndaelManaged { Key = Encoding.UTF8.GetBytes(key), Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; ICryptoTransform cTransform = rm.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray); }
前端代码:
function formencode() { var src = $(this).text().trim(); var key = CryptoJS.enc.Utf8.parse("1234567890123456"); var decrypt = CryptoJS.AES.decrypt(src, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }); $(this).text(decrypt.toString(CryptoJS.enc.Utf8)); }