go实现 hmac sha1 返回16进制的函数
时间: 2023-12-09 08:03:08 浏览: 32
下面是一个使用Go语言实现HMAC-SHA1并返回16进制字符串的示例代码:
```go
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"fmt"
)
func main() {
message := "hello world"
key := "mykey"
mac := hmac.New(sha1.New, []byte(key))
mac.Write([]byte(message))
expectedMAC := mac.Sum(nil)
hexString := hex.EncodeToString(expectedMAC)
fmt.Println(hexString)
}
```
在此示例中,我们使用crypto/hmac和crypto/sha1包来执行HMAC-SHA1哈希。我们使用hmac.New()函数创建一个新的HMAC对象,其中的第一个参数是哈希函数,第二个参数是密钥。然后,我们使用mac.Write()函数输入我们要哈希的消息。最后,我们使用mac.Sum(nil)获取哈希值,并将其传递给hex.EncodeToString()函数,以将其转换为16进制字符串。
运行此程序将输出以下内容:
```
104fb0e174f9d55c9f9e0b3eabe53908290b6cd5
```
这是使用HMAC-SHA1算法生成的16进制字符串哈希值。
相关问题
实现 hmac sha1 返回16进制的函数
以下是 Python 中实现 HMAC-SHA1 返回 16 进制的函数:
```python
import hmac
import hashlib
def hmac_sha1(key, message):
return hmac.new(key.encode(), message.encode(), hashlib.sha1).hexdigest()
```
其中,`key` 为密钥字符串,`message` 为消息字符串。该函数返回 HMAC-SHA1 计算结果的 16 进制表示字符串。
在不使用库的情况下用原生javaScript语法实现HMAC-SHA256
HMAC-SHA256是一种基于哈希函数和密钥的消息认证码算法。在JavaScript中,可以使用Crypto API实现HMAC-SHA256。以下是一个示例代码:
```javascript
function sha256(message) {
// convert message to array buffer
const msgBuffer = new TextEncoder().encode(message);
// hash the message using SHA-256
return crypto.subtle.digest('SHA-256', msgBuffer);
}
async function hmacSha256(key, message) {
// convert key and message to array buffers
const keyBuffer = new TextEncoder().encode(key);
const msgBuffer = new TextEncoder().encode(message);
// import the key and generate the HMAC using SHA-256
const importedKey = await crypto.subtle.importKey('raw', keyBuffer, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
const hmac = await crypto.subtle.sign('HMAC', importedKey, msgBuffer);
// convert HMAC to hex string
return Array.from(new Uint8Array(hmac)).map(b => b.toString(16).padStart(2, '0')).join('');
}
// example usage
const key = 'secret';
const message = 'hello world';
hmacSha256(key, message).then(console.log);
```
在上面的代码中,`sha256()`函数使用Crypto API中的`crypto.subtle.digest()`方法实现SHA-256哈希函数。`hmacSha256()`函数首先将密钥和消息转换为数组缓冲区,然后使用`crypto.subtle.importKey()`方法导入密钥并生成HMAC。最后,使用`Array.from()`方法将HMAC转换为16进制字符串。