md5算法go语言实现
时间: 2023-07-07 17:10:50 浏览: 52
以下是Go语言实现MD5算法的示例代码:
```go
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
)
func main() {
data := []byte("Hello, world!")
hash := md5.Sum(data)
md5str := hex.EncodeToString(hash[:])
fmt.Println(md5str)
}
```
这个程序将输出 "86fb269d190d2c85f6e0468ceca42a20",这就是 "Hello, world!" 字符串的MD5哈希值。在这个程序中,我们使用了Go语言标准库中的crypto/md5包,它提供了MD5哈希算法的实现。我们首先将要计算哈希值的数据转换成字节数组,然后调用md5.Sum函数计算哈希值。由于md5.Sum函数返回的是一个长度为16的字节数组,我们还需要使用encoding/hex包将其转换成16进制字符串,最后输出结果即可。
相关问题
go语言 pbe加密算法实现
以下是使用Go语言实现PBE加密算法的示例代码:
```go
package main
import (
"crypto/cipher"
"crypto/des"
"crypto/md5"
"encoding/base64"
"fmt"
)
func main() {
// 设置加密参数
password := "123456" // 密码
salt := "salt" // 盐值
iterations := 1000 // 迭代次数
// 生成密钥
key := pbkdf1([]byte(password), []byte(salt), iterations, 8)
// 加密明文
plaintext := "hello world"
ciphertext, err := pbeEncrypt([]byte(plaintext), key)
if err != nil {
panic(err)
}
// 输出加密结果
fmt.Println(base64.StdEncoding.EncodeToString(ciphertext))
// 解密密文
decrypted, err := pbeDecrypt(ciphertext, key)
if err != nil {
panic(err)
}
// 输出解密结果
fmt.Println(string(decrypted))
}
// PBE加密
func pbeEncrypt(plaintext []byte, key []byte) ([]byte, error) {
// 创建加密器
block, err := des.NewCipher(key)
if err != nil {
return nil, err
}
iv := make([]byte, block.BlockSize())
stream := cipher.NewCTR(block, iv)
// 加密明文
ciphertext := make([]byte, len(plaintext))
stream.XORKeyStream(ciphertext, plaintext)
return ciphertext, nil
}
// PBE解密
func pbeDecrypt(ciphertext []byte, key []byte) ([]byte, error) {
// 创建解密器
block, err := des.NewCipher(key)
if err != nil {
return nil, err
}
iv := make([]byte, block.BlockSize())
stream := cipher.NewCTR(block, iv)
// 解密密文
plaintext := make([]byte, len(ciphertext))
stream.XORKeyStream(plaintext, ciphertext)
return plaintext, nil
}
// PBKDF1算法
func pbkdf1(password []byte, salt []byte, iterations int, keyLen int) []byte {
key := password
for i := 0; i < iterations; i++ {
data := append(key, salt...)
hash := md5.Sum(data)
key = hash[:]
}
return key[:keyLen]
}
```
go语言PBEWithMD5AndDES加密算法
以下是Go语言中使用PBEWithMD5AndDES算法进行加密的示例代码:
```go
package main
import (
"crypto/cipher"
"crypto/des"
"crypto/md5"
"encoding/base64"
"fmt"
)
func main() {
key := []byte("password") // 设置口令
plaintext := []byte("hello world") // 设置明文
// 创建加密块
block, err := des.NewCipher(key)
if err != nil {
panic(err)
}
// 创建加密器
iv := md5.Sum(key)
stream := cipher.NewCFBEncrypter(block, iv[:])
// 加密明文
ciphertext := make([]byte, len(plaintext))
stream.XORKeyStream(ciphertext, plaintext)
// 对加密结果进行base64编码
encoded := base64.StdEncoding.EncodeToString(ciphertext)
fmt.Println(encoded) // 输出:QzJvZGJmZGJmZGJmZGJmZg==
}
```