forked from nsjok/gossr
/
encrypt.go
51 lines (43 loc) · 1020 Bytes
/
encrypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package tools
import (
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
)
func HmacMD5(key []byte, data []byte) []byte {
hmacMD5 := hmac.New(md5.New, key)
hmacMD5.Write(data)
return hmacMD5.Sum(nil)[:10]
}
func HmacSHA1(key []byte, data []byte) []byte {
hmacSHA1 := hmac.New(sha1.New, key)
hmacSHA1.Write(data)
return hmacSHA1.Sum(nil)[:10]
}
func MD5Sum(d []byte) []byte {
h := md5.New()
h.Write(d)
return h.Sum(nil)
}
func SHA1Sum(d []byte) []byte {
h := sha1.New()
h.Write(d)
return h.Sum(nil)
}
func EVPBytesToKey(password string, keyLen int) (key []byte) {
const md5Len = 16
cnt := (keyLen-1)/md5Len + 1
m := make([]byte, cnt*md5Len)
copy(m, MD5Sum([]byte(password)))
// Repeatedly call md5 until bytes generated is enough.
// Each call to md5 uses data: prev md5 sum + password.
d := make([]byte, md5Len+len(password))
start := 0
for i := 1; i < cnt; i++ {
start += md5Len
copy(d, m[start-md5Len:start])
copy(d[md5Len:], password)
copy(m[start:], MD5Sum(d))
}
return m[:keyLen]
}