public static string ProtectData(string encryptKey, string validateKey, string clearData, string ivStr = null) { using (var rj = new RijndaelManaged()) { rj.Padding = PaddingMode.PKCS7; rj.Mode = CipherMode.CBC; rj.KeySize = 256;// 128; rj.BlockSize = 128; rj.Key = CryptoExtensions.HexToBinary(encryptKey); byte[] iv; if (ivStr == null) { rj.GenerateIV(); iv = rj.IV; } else { iv = CryptoExtensions.HexToBinary(ivStr); rj.IV = iv; } var data = Encoding.UTF8.GetBytes(clearData); using (var memoryStream = new MemoryStream()) { //先将向量写入加密流头部 memoryStream.Write(iv, 0, iv.Length); using (var encryptor = rj.CreateEncryptor()) using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { //写入加密字节流 cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); //计算当前字节流的Hash值,并写入流末端 using (KeyedHashAlgorithm validationAlgorithm = new HMACSHA256(CryptoExtensions.HexToBinary(validateKey))) { var hash = validationAlgorithm.ComputeHash( memoryStream.GetBuffer(), 0, checked ((int)memoryStream.Length)); memoryStream.Write(hash, 0, 8); return(CryptoExtensions.BinaryToHex(memoryStream.ToArray())); } } } } }
static string GetMD5String(string original) { var encrypted = md5.ComputeHash(Encoding.ASCII.GetBytes(original)); return(CryptoExtensions.BinaryToHex(encrypted).ToLower()); }