/
util.go
64 lines (54 loc) · 1.28 KB
/
util.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
52
53
54
55
56
57
58
59
60
61
62
63
64
package security
import (
"encoding/base64"
"crypto"
"crypto/x509"
"fmt"
"encoding/hex"
)
func EncodeBase64(origdata []byte) []byte{
str := base64.StdEncoding.EncodeToString(origdata)
return []byte(str)
}
func DecodeBase64(cipherdata []byte) []byte {
orig, err := base64.StdEncoding.DecodeString(string(cipherdata))
if err != nil {
return nil
}
return orig
}
func Hash(algo int, hashbuf []byte) ([]byte, error) {
var hashType crypto.Hash
switch algo {
case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1:
hashType = crypto.SHA1
case SHA256WithRSA, DSAWithSHA256, ECDSAWithSHA256:
hashType = crypto.SHA256
case SHA384WithRSA, ECDSAWithSHA384:
hashType = crypto.SHA384
case SHA512WithRSA, ECDSAWithSHA512:
hashType = crypto.SHA512
case MD2WithRSA, MD5WithRSA:
return nil, x509.InsecureAlgorithmError(algo)
default:
return nil, fmt.Errorf("非法的签名算法:[%d]", algo)
}
if !hashType.Available() {
return nil, x509.ErrUnsupportedAlgorithm
}
h := hashType.New()
h.Write(hashbuf)
digest := h.Sum(nil)
return digest,nil
}
func EncodeHex(origdata []byte)[]byte {
str := hex.EncodeToString(origdata)
return []byte(str)
}
func DecodeHex(hexdata []byte) []byte{
data, err := hex.DecodeString(string(hexdata))
if err != nil {
return nil
}
return []byte(data)
}