C#加密算法HmacSHA256,SHA256

本文介绍了一种使用SHA256算法进行字符串加密的方法,包括SHA256的直接应用、HMAC-SHA256签名算法及Base64编码的实现。通过具体的代码示例展示了如何将原始字符串转换为安全的密文形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static string SHA256Encrypt(string strIN)
{
    //string strIN = getstrIN(strIN);
    byte[] tmpByte;
    SHA256 sha256 = new SHA256Managed();
    tmpByte = sha256.ComputeHash(GetKeyByteArray(strIN));

    StringBuilder rst = new StringBuilder();
    for(int i = 0; i<tmpByte.Length; i++)
    {
        rst.Append(tmpByte[i].ToString("x2"));   
    }
    sha256.Clear();
    return rst.ToString();
    //return GetStringValue(tmpByte);
}

private static string GetStringValue(byte[] Byte)
{
    string tmpString = "";
    UTF8Encoding Asc = new UTF8Encoding();
    tmpString = Asc.GetString(Byte);
    return tmpString;
}

private static byte[] GetKeyByteArray(string strKey)
{
    UTF8Encoding Asc = new UTF8Encoding();
    int tmpStrLen = strKey.Length;
    byte[] tmpByte = new byte[tmpStrLen - 1];
    tmpByte = Asc.GetBytes(strKey);
    return tmpByte;
}

private static string HmacSHA256(string message, string secret)
{
    secret = secret ?? "";
    var encoding = new System.Text.UTF8Encoding();
    byte[] keyByte = encoding.GetBytes(secret);
    byte[] messageBytes = encoding.GetBytes(message);
    using (var hmacsha256 = new HMACSHA256(keyByte))
    {
        byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
        return Convert.ToBase64String(hashmessage);
    }
}

private static string Base64(string message)
{
    System.Text.Encoding encode = System.Text.Encoding.UTF8;
    byte[] bytedata = encode.GetBytes(message);
    string strPath = Convert.ToBase64String(bytedata, 0, bytedata.Length);
    return strPath;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值