|
15 | 15 | package com
|
16 | 16 |
|
17 | 17 | import (
|
| 18 | + "bufio" |
18 | 19 | "bytes"
|
19 | 20 | "crypto/hmac"
|
20 | 21 | "crypto/md5"
|
@@ -70,6 +71,24 @@ func Md5file(file string) string {
|
70 | 71 | return ByteMd5(barray)
|
71 | 72 | }
|
72 | 73 |
|
| 74 | +func Md5Reader(r io.Reader) (string, error) { |
| 75 | + h := md5.New() |
| 76 | + reader := bufio.NewReader(r) |
| 77 | + buf := make([]byte, 4096) // 4KB的缓冲区 |
| 78 | + for { |
| 79 | + n, err := reader.Read(buf) |
| 80 | + if err != nil && err != io.EOF { |
| 81 | + return ``, err |
| 82 | + } |
| 83 | + if n == 0 { |
| 84 | + break |
| 85 | + } |
| 86 | + h.Write(buf[:n]) |
| 87 | + } |
| 88 | + md5sum := h.Sum(nil) |
| 89 | + return hex.EncodeToString(md5sum), nil |
| 90 | +} |
| 91 | + |
73 | 92 | func Token(key string, val []byte, args ...string) string {
|
74 | 93 | hm := hmac.New(sha1.New, []byte(key))
|
75 | 94 | hm.Write(val)
|
@@ -230,25 +249,30 @@ func Reverse(s string) string {
|
230 | 249 | return string(runes[n:])
|
231 | 250 | }
|
232 | 251 |
|
| 252 | +func NewRand() *r.Rand { |
| 253 | + return r.New(r.NewSource(time.Now().UnixNano())) |
| 254 | +} |
| 255 | + |
233 | 256 | // RandomCreateBytes generate random []byte by specify chars.
|
234 | 257 | func RandomCreateBytes(n int, alphabets ...byte) []byte {
|
235 | 258 | const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
236 | 259 | var bytes = make([]byte, n)
|
237 | 260 | var randby bool
|
| 261 | + var rd *r.Rand |
238 | 262 | if num, err := rand.Read(bytes); num != n || err != nil {
|
239 |
| - r.Seed(time.Now().UnixNano()) |
| 263 | + rd = NewRand() |
240 | 264 | randby = true
|
241 | 265 | }
|
242 | 266 | for i, b := range bytes {
|
243 | 267 | if len(alphabets) == 0 {
|
244 | 268 | if randby {
|
245 |
| - bytes[i] = alphanum[r.Intn(len(alphanum))] |
| 269 | + bytes[i] = alphanum[rd.Intn(len(alphanum))] |
246 | 270 | } else {
|
247 | 271 | bytes[i] = alphanum[b%byte(len(alphanum))]
|
248 | 272 | }
|
249 | 273 | } else {
|
250 | 274 | if randby {
|
251 |
| - bytes[i] = alphabets[r.Intn(len(alphabets))] |
| 275 | + bytes[i] = alphabets[rd.Intn(len(alphabets))] |
252 | 276 | } else {
|
253 | 277 | bytes[i] = alphabets[b%byte(len(alphabets))]
|
254 | 278 | }
|
|
0 commit comments