service/library/mycrypto/sha256Crypto.go

40 lines
970 B
Go

package mycrypto
import (
"crypto/md5"
"crypto/sha256"
"fmt"
"service/library/configcenter"
"strconv"
"strings"
)
type Sha256Crypto struct {
salts []string
}
func NewSha256Crypto(cryptoConfig *configcenter.CryptoConfig) (sha256Crypto *Sha256Crypto, err error) {
sha256Crypto = &Sha256Crypto{}
//读取盐
sha256Crypto.readSha256Salts(cryptoConfig)
return
}
func (sha256Crypto *Sha256Crypto) readSha256Salts(cryptoConfig *configcenter.CryptoConfig) {
sha256Crypto.salts = strings.Split(cryptoConfig.SHA256Salts, " ")
}
func (sha256Crypto *Sha256Crypto) getSalt(data []byte) (salt string) {
hash := fmt.Sprintf("%x", md5.Sum(data))
value, _ := strconv.ParseInt(hash[:8], 10, 64)
idx := value % int64(len(sha256Crypto.salts))
return sha256Crypto.salts[idx]
}
func (sha256Crypto *Sha256Crypto) Encrypt(input []byte) string {
salt := sha256Crypto.getSalt(input)
hash := sha256.Sum256(append(input, []byte(salt)...))
return fmt.Sprintf("%X", hash)
}