简体   繁体   English

在C#中使用sha1算法使用用户的秘密密钥进行哈希

[英]Hashing by sha1 algorithm with user's secret key in C#

I need to hash a string according to the sha1 algorithm, with the user's secret key, something like: hash = hash (string, secret_key). 我需要根据sha1算法使用用户的密钥对hash = hash (string, secret_key). ,例如: hash = hash (string, secret_key).

I use this code: 我使用以下代码:

byte[] data = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));

But I can not find how to use the secret key in this algorithm. 但是我找不到如何在此算法中使用秘密密钥。

The hash is the result of applying a hash function to data. 哈希是对数据应用哈希函数的结果。 It maps arbitrary data to fixed size value. 它将任意数据映射到固定大小的值。 This does not require any kind of secret. 这不需要任何秘密。

The cryptographic process which uses hashes and secret keys is signing data. 使用哈希和秘密密钥的加密过程是对数据进行签名。 You may want to create a hash of your data and a MAC (message authentication code) based on public/private key cryptography using the private key. 您可能希望使用私钥基于公钥/私钥加密来创建数据的哈希值和MAC(消息认证代码)。

A hash tells you only that data was modified or not. 哈希仅告诉您数据是否已修改。

A MAC uses any kind of secret, thus it protects also against manipulation. MAC使用任何类型的秘密,因此它也可以防止操纵。 Generally, MACs only work when the sender and receiver know each other. 通常,MAC仅在发送方和接收方相互了解时才能工作。

You could do something like: 您可以执行以下操作:

public string SignData(string message, string secret)
{
    var encoding = new System.Text.UTF8Encoding();
    var keyBytes = encoding.GetBytes(secret);
    var messageBytes = encoding.GetBytes(message);
    using (var hmacsha1 = new HMACSHA1(keyBytes))
    {
        var hashMessage = hmacsha1.ComputeHash(messageBytes);
        return Convert.ToBase64String(hashMessage);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM