using System; using System.Security.Cryptography; using System.Text; namespace OS.Common.Encrypt { /// /// /// public static class HmacSha1 { /// /// 返回加密后的 /// /// /// /// 如果为空,则默认Utf-8 /// 解密后的字节流通过Base64转化 public static string EncryptBase64(string data, string key, Encoding encoding = null) { if (encoding == null) encoding = Encoding.UTF8; var bytes = encoding.GetBytes(data); var keyBytes = encoding.GetBytes(key); byte[] resultbytes = Encrypt(keyBytes, encoding, bytes); return Convert.ToBase64String(resultbytes); } /// /// 返回加密后的 /// /// /// /// 如果为空,则默认Utf-8 /// public static string EncryptUtf8(string data, string key, Encoding encoding = null) { if (encoding == null) encoding = Encoding.UTF8; var bytes = encoding.GetBytes(data); var keyBytes = encoding.GetBytes(key); byte[] resultbytes = Encrypt(keyBytes, encoding, bytes); return Encoding.UTF8.GetString(resultbytes); } /// /// 加密 /// /// /// /// /// private static byte[] Encrypt(byte[] key, Encoding encoding, byte[] bytes) { byte[] resultbytes; using (HMACSHA1 hmac = new HMACSHA1(key)) { resultbytes = hmac.ComputeHash(bytes); } return resultbytes; } } }