本文整理汇总了Golang中crypto.Hash函数的典型用法代码示例。如果您正苦于以下问题:Golang Hash函数的具体用法?Golang Hash怎么用?Golang Hash使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Hash函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Encode
//you need set packet before encode
func (a *PasswordAVP) Encode() (b []byte, err error) {
m := crypto.Hash(crypto.MD5).New()
m.Write(a.packet.Secret)
m.Write(a.packet.Authenticator[:])
md := m.Sum(nil)
if len(a.Value) > 128 {
return nil, fmt.Errorf("[PasswordAVP.Encode] len(data)[%d]>128", len(a.Value))
}
inPassLen := len(a.Value) / 16 * 16
if len(a.Value)%16 != 0 {
inPassLen += 16
}
pass := make([]byte, inPassLen)
outPass := make([]byte, inPassLen)
copy(pass, a.Value)
blockNum := inPassLen / 16
for i := 0; i < blockNum; i++ {
for j := 0; j < 16; j++ {
outPass[i*16+j] = pass[i*16+j] ^ md[j]
}
m := crypto.Hash(crypto.MD5).New()
m.Write(a.packet.Secret)
m.Write(outPass[i*16 : i*16+16])
md = m.Sum(nil)
}
return encodeWithByteSlice(AVPTypeUserPassword, outPass)
}
示例2: avpPassword
func avpPassword(p *Packet, typ AVPType, data []byte) (avp AVP, err error) {
fmt.Printf("%#v\n", data)
if len(data) < 16 {
return nil, fmt.Errorf("[avpPassword] len(data)[%d]<16", len(data))
}
if len(data) > 128 {
return nil, fmt.Errorf("[avpPassword] len(data)[%d]>128", len(data))
}
//Decode password. XOR against md5(p.server.secret+Authenticator)
m := crypto.Hash(crypto.MD5).New()
m.Write(p.Secret)
m.Write(p.Authenticator[:])
md := m.Sum(nil)
pass := append([]byte(nil), data...)
blockNum := len(pass) / 16
if len(pass)%16 != 0 {
return nil, fmt.Errorf("[avpPassword] blockNum[%d]%%16!=0", blockNum)
}
outputPass := make([]byte, len(pass))
for i := 0; i < blockNum; i++ {
for j := 0; j < 16; j++ {
outputPass[i*16+j] = pass[i*16+j] ^ md[j]
}
m := crypto.Hash(crypto.MD5).New()
m.Write(p.Secret)
m.Write(pass[i*16 : i*16+16])
md = m.Sum(nil)
}
outputPass = bytes.TrimRight(outputPass, string([]rune{0}))
avpP := &PasswordAVP{
Value: string(outputPass),
}
avpP.SetPacket(p)
return avpP, nil
}
示例3: fetchCert
func fetchCert(address string) (*cert, error) {
//fetch cert over network
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
return nil, err
}
netCon, err := net.DialTCP("tcp", nil, addr)
if err != nil {
return nil, err
}
host := strings.Split(address, ":")[0]
config := &tls.Config{
NextProtos: []string{"http"},
ServerName: host,
InsecureSkipVerify: true,
}
log.Println("getting cert for: ", host)
client := tls.Client(netCon, config)
err = client.Handshake()
if err != nil {
return nil, err
}
state := client.ConnectionState()
if len(state.PeerCertificates) == 0 {
return nil, errors.New("no cert recieved from host")
}
for i := range state.PeerCertificates {
log.Println(state.PeerCertificates[i].Subject)
certRaw := state.PeerCertificates[i].Raw
sha := crypto.Hash(crypto.SHA1).New()
sha.Write(certRaw)
myFP := hex.EncodeToString(sha.Sum(nil))
myFP = fingerPrintStr(myFP).String()
log.Println(myFP)
log.Println("---")
}
certRaw := state.PeerCertificates[0].Raw
sha := crypto.Hash(crypto.SHA1).New()
sha.Write(certRaw)
client.Close()
netCon.Close()
c := &cert{state.PeerCertificates[0], sha.Sum(nil)}
return c, nil
}
示例4: prfAndHashForVersion
func prfAndHashForVersion(version uint16, suite *cipherSuite) (func(result, secret, label, seed []byte), crypto.Hash) {
switch version {
case VersionSSL30:
return prf30, crypto.Hash(0)
case VersionTLS10, VersionTLS11:
return prf10, crypto.Hash(0)
case VersionTLS12:
if suite.flags&suiteSHA384 != 0 {
return prf12(sha512.New384), crypto.SHA384
}
return prf12(sha256.New), crypto.SHA256
default:
panic("unknown version")
}
}
示例5: signResponse
func (r NotaryResponse) signResponse(response []byte) ([]byte, error) {
hash := crypto.Hash(crypto.SHA1).New()
hash.Write(response)
hashed := hash.Sum(nil)
return rsa.SignPKCS1v15(rand.Reader, r.privateKey, crypto.SHA1, hashed)
}
示例6: Sign
// Sign signs the given message with priv.
// Ed25519 performs two passes over messages to be signed and therefore cannot
// handle pre-hashed messages. Thus opts.HashFunc() must return zero to
// indicate the message hasn't been hashed. This can be achieved by passing
// crypto.Hash(0) as the value for opts.
func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) {
if opts.HashFunc() != crypto.Hash(0) {
return nil, errors.New("ed25519: cannot sign hashed message")
}
return Sign(priv, message), nil
}
示例7: getHashForOID
func getHashForOID(oid asn1.ObjectIdentifier) (crypto.Hash, error) {
switch {
case oid.Equal(oidDigestAlgorithmSHA1):
return crypto.SHA1, nil
}
return crypto.Hash(0), ErrUnsupportedAlgorithm
}
示例8: Encode
func (p *Packet) Encode(b []byte) (n int, ret []byte, err error) {
b[0] = uint8(p.Code)
b[1] = uint8(p.Identifier)
copy(b[4:20], p.Authenticator[:])
written := 20
bb := b[20:]
for i, _ := range p.AVPs {
n, err = p.AVPs[i].Encode(bb)
written += n
if err != nil {
return written, nil, err
}
bb = bb[n:]
}
//check if written too big.
binary.BigEndian.PutUint16(b[2:4], uint16(written))
// fix up the authenticator
hasher := crypto.Hash(crypto.MD5).New()
hasher.Write(b[:written])
hasher.Write([]byte(p.server.secret))
copy(b[4:20], hasher.Sum(nil))
return written, b, err
}
示例9: getHashName
// this is ugly.
func getHashName(h hash.Hash) string {
hn := reflect.TypeOf(h).String()
fields := strings.Split(hn, ".")
var hashName string
hashName = fields[0]
if strings.HasPrefix(fields[0], "*") {
hashName = fields[0][1:]
}
elem := reflect.ValueOf(h).Elem()
switch hashName {
case "sha256":
f := elem.FieldByName("is224")
if f.IsValid() {
if f.Bool() {
hashName = "sha224"
}
}
break
case "sha512":
f := elem.FieldByName("function")
if f.IsValid() {
if crypto.Hash(f.Uint()) == crypto.SHA384 {
hashName = "sha384"
}
}
break
}
return hashName
}
示例10: appleResponse
// appleResponse takes an Apple-Challenge header value, and constructs a response for it.
// To derive the response, the IP and MAC of the connection are needed, so the local address
// has to be passed in.
func appleResponse(challenge string, addr net.Addr) (c64 string, err error) {
// iTunes seems to not pad things. Let's fix that.
p64 := base64pad(challenge)
ptext, err := base64.StdEncoding.DecodeString(p64)
if err != nil {
return
}
ptext = append(ptext, GetIP(addr)...)
ptext = append(ptext, GetMAC(addr)...)
for len(ptext) < 0x20 {
ptext = append(ptext, 0)
}
ctext, err := rsa.SignPKCS1v15(nil, rsaPrivKey, crypto.Hash(0), ptext)
if err != nil {
return
}
c64 = base64.StdEncoding.EncodeToString(ctext)
// We should respond in kind to iTunes
if len(p64) != len(challenge) {
c64 = base64unpad(c64)
}
return
}
示例11: ParseRequest
// ParseRequest parses an OCSP request in DER form. It only supports
// requests for a single certificate. Signed requests are not supported.
// If a request includes a signature, it will result in a ParseError.
func ParseRequest(bytes []byte) (*Request, error) {
var req ocspRequest
rest, err := asn1.Unmarshal(bytes, &req)
if err != nil {
return nil, err
}
if len(rest) > 0 {
return nil, ParseError("trailing data in OCSP request")
}
if len(req.TBSRequest.RequestList) == 0 {
return nil, ParseError("OCSP request contains no request body")
}
innerRequest := req.TBSRequest.RequestList[0]
hashFunc := getHashAlgorithmFromOID(innerRequest.Cert.HashAlgorithm.Algorithm)
if hashFunc == crypto.Hash(0) {
return nil, ParseError("OCSP request uses unknown hash function")
}
return &Request{
HashAlgorithm: hashFunc,
IssuerNameHash: innerRequest.Cert.NameHash,
IssuerKeyHash: innerRequest.Cert.IssuerKeyHash,
SerialNumber: innerRequest.Cert.SerialNumber,
}, nil
}
示例12: Restore
// Restore resets the digest to the given state.
func (d *digest) Restore(state []byte) error {
decoder := gob.NewDecoder(bytes.NewReader(state))
var function uint
// We decode this way so that we do not have
// to export these fields of the digest struct.
vals := []interface{}{
&d.h, &d.x, &d.nx, &d.len, &function,
}
for _, val := range vals {
if err := decoder.Decode(val); err != nil {
return err
}
}
switch crypto.Hash(function) {
case crypto.SHA224:
d.is224 = true
case crypto.SHA256:
d.is224 = false
default:
return resumable.ErrBadState
}
return nil
}
示例13: getHashAlgorithmFromOID
// TODO(rlb): This is not taken from crypto/x509, but it's of the same general form.
func getHashAlgorithmFromOID(target asn1.ObjectIdentifier) crypto.Hash {
for hash, oid := range hashOIDs {
if oid.Equal(target) {
return hash
}
}
return crypto.Hash(0)
}
示例14: TestResultUnsupportedAlgorithmWillCauseNewHmacAuthToPanic
func TestResultUnsupportedAlgorithmWillCauseNewHmacAuthToPanic(t *testing.T) {
defer func() {
err := recover()
assert.Equal(t, err,
"hmacauth: hash algorithm #0 is unavailable")
}()
NewHmacAuth(crypto.Hash(0), nil, "", nil)
}
示例15: TestUnsupportedHashAlgorithm
func TestUnsupportedHashAlgorithm(t *testing.T) {
algorithm, err := DigestNameToCryptoHash("unsupported")
assert.NotEqual(t, err, nil)
assert.Equal(t, err.Error(),
"hmacauth: hash algorithm not supported: unsupported")
assert.Equal(t, algorithm, crypto.Hash(0))
assert.Equal(t, algorithm.Available(), false)
}