本文整理汇总了Golang中crypto/hmac.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: Sign
func Sign(credentials *BceCredentials, timestamp, httpMethod, path, query string,
headers map[string]string) string {
if path[0] != '/' {
path = "/" + path
}
var expirationPeriodInSeconds = 1800
authStringPrefix := fmt.Sprintf("bce-auth-v1/%s/%s/%d", credentials.AccessKeyId,
timestamp, expirationPeriodInSeconds)
//fmt.Println(authStringPrefix)
mac := hmac.New(sha256.New, []byte(credentials.SecretAccessKey))
mac.Write([]byte(authStringPrefix))
signingKey := fmt.Sprintf("%x", mac.Sum(nil))
//fmt.Printf(signingKey)
CanonicalURI := utils.UriEncodeExceptSlash(path)
CanonicalQueryString := getCannonicalQuery(query)
CanonicalHeaders, signedHeaders := getCanonicalHeaders(headers, nil)
CanonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s", httpMethod, CanonicalURI,
CanonicalQueryString, CanonicalHeaders)
mac = hmac.New(sha256.New, []byte(signingKey))
mac.Write([]byte(CanonicalRequest))
signature := fmt.Sprintf("%x", mac.Sum(nil))
//fmt.Println(signature)
authorization := fmt.Sprintf("%s/%s/%s", authStringPrefix, signedHeaders, signature)
if Debug {
fmt.Println(CanonicalRequest)
fmt.Println(authorization)
}
return authorization
}
开发者ID:WilliamKyle,项目名称:baidubce,代码行数:35,代码来源:bce_v1_signer.go
示例2: Password
//Password returns the password for the given website, password version and templates
func (algo *Algorithm) Password(site string, version string, templates []string) (string, error) {
if len(templates) < 1 {
return "", fmt.Errorf("%s", "invalid template")
}
h := hmac.New(sha512.New, algo.key)
if algo.variant == 0 {
h = hmac.New(sha256.New, algo.key)
}
_, err := h.Write([]byte(fmt.Sprint(string(algo.saltPrefix), uint32(len(site)), site, version)))
if err != nil {
return "", err
}
seed := h.Sum(nil)
template := templates[uint32(seed[0])%uint32(len(templates))]
password := []byte(template)
for i, tplRune := range template {
var passchars string
switch tplRune {
case 'V':
passchars = V
case 'C':
passchars = C
case 'v':
passchars = v
case 'c':
passchars = c
case 'A':
passchars = A
case 'a':
passchars = a
case 'n':
passchars = n
case 'o':
passchars = o
case 'X':
passchars = X
case 'x':
passchars = x
case 'p':
passchars = p
default:
return "", fmt.Errorf("%s", "invalid template")
}
if i+1 < len(seed) {
password[i] = passchars[uint32(seed[i+1])%uint32(len(passchars))]
} else {
password[i] = passchars[0]
}
}
return string(password), err
}
开发者ID:henderjon,项目名称:statelessPassword,代码行数:61,代码来源:algorithm.go
示例3: getSignature
func getSignature(b []byte, secret []byte) []byte {
keym := hmac.New(sha256.New, secret)
keym.Write(b)
m := hmac.New(sha256.New, keym.Sum(nil))
m.Write(b)
return m.Sum(nil)
}
开发者ID:Jyggafey,项目名称:drone,代码行数:7,代码来源:passwordreset.go
示例4: lionessDecode
// lionDecode performs the inverse operation of lionessEncode. Namely,
// decrypting a previously generated cipher text, returning the original plaintext.
func lionessDecode(key [securityParameter]byte, cipherText [messageSize]byte) [messageSize]byte {
var message [messageSize]byte
copy(message[:], cipherText[:])
L := message[:securityParameter]
R := message[securityParameter:]
// Round 4.
// R = R XOR S(L XOR K_4)
var k4 [securityParameter]byte
xor(k4[:], L[:], key[:])
xor(R[:], R[:], generateCipherStream(k4, uint(len(R))))
// Round 3.
// L = L XOR H_k3(R)
h := hmac.New(sha256.New, append(key[:], 0x03))
h.Write(R)
xor(L[:], h.Sum(nil)[:securityParameter], L[:])
// Round 2.
// R = R XOR S(L XOR K_2)
var k2 [securityParameter]byte
xor(k2[:], L[:], key[:])
xor(R[:], R[:], generateCipherStream(k2, uint(len(R))))
// Round 1.
// L = L XOR H_k1(R)
h = hmac.New(sha256.New, append(key[:], 0x01))
h.Write(R)
xor(L[:], h.Sum(nil)[:securityParameter], L[:])
return message
}
开发者ID:DeniseTerry1,项目名称:lightning-onion,代码行数:35,代码来源:lionness.go
示例5: authenticateMessage
// Returns true if the provided message is unsigned or has a valid signature
// from one of the provided signers.
func authenticateMessage(signers map[string]Signer, header *Header, msg []byte) bool {
digest := header.GetHmac()
if digest != nil {
var key string
signer := fmt.Sprintf("%s_%d", header.GetHmacSigner(),
header.GetHmacKeyVersion())
if s, ok := signers[signer]; ok {
key = s.HmacKey
} else {
return false
}
var hm hash.Hash
switch header.GetHmacHashFunction() {
case Header_MD5:
hm = hmac.New(md5.New, []byte(key))
case Header_SHA1:
hm = hmac.New(sha1.New, []byte(key))
}
hm.Write(msg)
expectedDigest := hm.Sum(nil)
if subtle.ConstantTimeCompare(digest, expectedDigest) != 1 {
return false
}
}
return true
}
开发者ID:RogerBai,项目名称:heka,代码行数:29,代码来源:net_utils.go
示例6: addRemoteKey
func (p *PrivateKeys) addRemoteKey(remote []byte, clientPacket []byte, serverPacket []byte) SharedKeys {
remote_be := new(big.Int)
remote_be.SetBytes(remote)
shared_key := powm(remote_be, p.privateKey, p.prime)
data := make([]byte, 0, 100)
mac := hmac.New(sha1.New, shared_key.Bytes())
for i := 1; i < 6; i++ {
mac.Write(clientPacket)
mac.Write(serverPacket)
mac.Write([]byte{uint8(i)})
data = append(data, mac.Sum(nil)...)
mac.Reset()
}
mac = hmac.New(sha1.New, data[0:0x14])
mac.Write(clientPacket)
mac.Write(serverPacket)
return SharedKeys{
challenge: mac.Sum(nil),
sendKey: data[0x14:0x34],
recvKey: data[0x34:0x54],
}
}
开发者ID:alvislin,项目名称:spotcontrol,代码行数:26,代码来源:keys.go
示例7: CheckMAC
// CheckMAC returns true if messageMAC is a valid HMAC tag for message.
func CheckMAC(message []byte, messageMAC string, key string) bool {
var err error
var mac hash.Hash
var macdata []byte
var macparts = strings.Split(messageMAC, "=")
macdata, err = hex.DecodeString(macparts[1])
if err != nil {
log.Print("Error decoding hex digest: ", err)
return false
}
switch macparts[0] {
case "md5":
mac = hmac.New(md5.New, []byte(key))
case "sha1":
mac = hmac.New(sha1.New, []byte(key))
case "sha256":
mac = hmac.New(sha256.New, []byte(key))
case "sha512":
mac = hmac.New(sha512.New, []byte(key))
default:
log.Print("Unsupported hash: ", macparts[0])
return false
}
mac.Write(message)
expectedMAC := mac.Sum(nil)
return hmac.Equal(macdata, expectedMAC)
}
开发者ID:tonnerre,项目名称:justanotherircbot,代码行数:28,代码来源:github.go
示例8: authenticateMessage
func authenticateMessage(signers map[string]Signer, header *Header,
pack *PipelinePack) bool {
digest := header.GetHmac()
if digest != nil {
var key string
signer := fmt.Sprintf("%s_%d", header.GetHmacSigner(),
header.GetHmacKeyVersion())
if s, ok := signers[signer]; ok {
key = s.HmacKey
} else {
return false
}
var hm hash.Hash
switch header.GetHmacHashFunction() {
case Header_MD5:
hm = hmac.New(md5.New, []byte(key))
case Header_SHA1:
hm = hmac.New(sha1.New, []byte(key))
}
hm.Write(pack.MsgBytes)
expectedDigest := hm.Sum(nil)
if bytes.Compare(digest, expectedDigest) != 0 {
return false
}
pack.Signer = header.GetHmacSigner()
}
return true
}
开发者ID:hellcoderz,项目名称:heka,代码行数:29,代码来源:inputs.go
示例9: TsigVerify
// TsigVerify verifies the TSIG on a message.
// If the signature does not validate err contains the
// error, otherwise it is nil.
func TsigVerify(msg []byte, secret, requestMAC string, timersOnly bool) error {
rawsecret, err := packBase64([]byte(secret))
if err != nil {
return err
}
// Srtip the TSIG from the incoming msg
stripped, tsig, err := stripTsig(msg)
if err != nil {
return err
}
buf := tsigBuffer(stripped, tsig, requestMAC, timersOnly)
ti := uint64(time.Now().Unix()) - tsig.TimeSigned
if uint64(tsig.Fudge) < ti {
return ErrTime
}
var h hash.Hash
switch tsig.Algorithm {
case HmacMD5:
h = hmac.New(md5.New, []byte(rawsecret))
case HmacSHA1:
h = hmac.New(sha1.New, []byte(rawsecret))
case HmacSHA256:
h = hmac.New(sha256.New, []byte(rawsecret))
default:
return ErrKeyAlg
}
io.WriteString(h, string(buf))
if strings.ToUpper(hex.EncodeToString(h.Sum(nil))) != strings.ToUpper(tsig.MAC) {
return ErrSig
}
return nil
}
开发者ID:avalanche123,项目名称:dns,代码行数:38,代码来源:tsig.go
示例10: TestDerivededSigningKey
func TestDerivededSigningKey(t *testing.T) {
t.Parallel()
os.Setenv("PWNIE_SECRET_KEY", "foobar")
os.Setenv("PWNIE_REGION", "us-east-1")
req := newRequest()
mac := hmac.New(sha256.New, []byte("AWS4foobar"))
mac.Write([]byte(formatShortDate(time.Now().UTC())))
kDate := mac.Sum(nil)
mac = hmac.New(sha256.New, kDate)
mac.Write([]byte(viper.GetString("region")))
kRegion := mac.Sum(nil)
mac = hmac.New(sha256.New, kRegion)
mac.Write([]byte("www"))
kService := mac.Sum(nil)
mac = hmac.New(sha256.New, kService)
mac.Write([]byte("aws4_request"))
kSigning := mac.Sum(nil)
expected := kSigning
actual := req.DerivedSigningKey()
if !hmac.Equal(expected, actual) {
t.Errorf("\n%v\n != \n%v", actual, expected)
}
}
开发者ID:totallymike,项目名称:fetch,代码行数:30,代码来源:signature_test.go
示例11: makeBlob
func makeBlob(blobPart []byte, keys privateKeys, publicKey string) string {
part := []byte(base64.StdEncoding.EncodeToString(blobPart))
sharedKey := keys.SharedKey(publicKey)
iv := randomVec(16)
key := sha1.Sum(sharedKey)
base_key := key[:16]
hash := hmac.New(sha1.New, base_key)
hash.Write([]byte("checksum"))
checksum_key := hash.Sum(nil)
hash.Reset()
hash.Write([]byte("encryption"))
encryption_key := hash.Sum(nil)
hash.Reset()
block, _ := aes.NewCipher(encryption_key[0:16])
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(part, part)
macHash := hmac.New(sha1.New, checksum_key)
macHash.Write(part)
mac := macHash.Sum(nil)
part = append(iv, part...)
part = append(part, mac...)
return base64.StdEncoding.EncodeToString(part)
}
开发者ID:badfortrains,项目名称:spotcontrol,代码行数:31,代码来源:blob.go
示例12: Child
// Child returns the ith child of wallet w. Values of i >= 2^31
// signify private key derivation. Attempting private key derivation
// with a public key will throw an error.
func (w *HDWallet) Child(i uint32) (*HDWallet, error) {
var fingerprint, I, newkey []byte
switch {
case bytes.Compare(w.Vbytes, Private) == 0, bytes.Compare(w.Vbytes, TestPrivate) == 0:
pub := privToPub(w.Key)
mac := hmac.New(sha512.New, w.Chaincode)
if i >= uint32(0x80000000) {
mac.Write(append(w.Key, uint32ToByte(i)...))
} else {
mac.Write(append(pub, uint32ToByte(i)...))
}
I = mac.Sum(nil)
iL := new(big.Int).SetBytes(I[:32])
if iL.Cmp(curve.N) >= 0 || iL.Sign() == 0 {
return &HDWallet{}, errors.New("Invalid Child")
}
newkey = addPrivKeys(I[:32], w.Key)
fingerprint = hash160(privToPub(w.Key))[:4]
case bytes.Compare(w.Vbytes, Public) == 0, bytes.Compare(w.Vbytes, TestPublic) == 0:
mac := hmac.New(sha512.New, w.Chaincode)
if i >= uint32(0x80000000) {
return &HDWallet{}, errors.New("Can't do Private derivation on Public key!")
}
mac.Write(append(w.Key, uint32ToByte(i)...))
I = mac.Sum(nil)
iL := new(big.Int).SetBytes(I[:32])
if iL.Cmp(curve.N) >= 0 || iL.Sign() == 0 {
return &HDWallet{}, errors.New("Invalid Child")
}
newkey = addPubKeys(privToPub(I[:32]), w.Key)
fingerprint = hash160(w.Key)[:4]
}
return &HDWallet{w.Vbytes, w.Depth + 1, fingerprint, uint32ToByte(i), I[32:], newkey}, nil
}
开发者ID:n1rvana,项目名称:go-hdwallet,代码行数:38,代码来源:hdwallet.go
示例13: kdf
func (conn *obfs3Conn) kdf(sharedSecret []byte) error {
// Using that shared-secret each party derives its encryption keys as
// follows:
//
// INIT_SECRET = HMAC(SHARED_SECRET, "Initiator obfuscated data")
// RESP_SECRET = HMAC(SHARED_SECRET, "Responder obfuscated data")
// INIT_KEY = INIT_SECRET[:KEYLEN]
// INIT_COUNTER = INIT_SECRET[KEYLEN:]
// RESP_KEY = RESP_SECRET[:KEYLEN]
// RESP_COUNTER = RESP_SECRET[KEYLEN:]
initHmac := hmac.New(sha256.New, sharedSecret)
initHmac.Write([]byte(initiatorKdfString))
initSecret := initHmac.Sum(nil)
initHmac.Reset()
initHmac.Write([]byte(initiatorMagicString))
initMagic := initHmac.Sum(nil)
respHmac := hmac.New(sha256.New, sharedSecret)
respHmac.Write([]byte(responderKdfString))
respSecret := respHmac.Sum(nil)
respHmac.Reset()
respHmac.Write([]byte(responderMagicString))
respMagic := respHmac.Sum(nil)
// The INIT_KEY value keys a block cipher (in CTR mode) used to
// encrypt values from initiator to responder thereafter. The counter
// mode's initial counter value is INIT_COUNTER. The RESP_KEY value
// keys a block cipher (in CTR mode) used to encrypt values from
// responder to initiator thereafter. That counter mode's initial
// counter value is RESP_COUNTER.
//
// Note: To have this be the last place where the shared secret is used,
// also generate the magic value to send/scan for here.
initBlock, err := aes.NewCipher(initSecret[:keyLen])
if err != nil {
return err
}
initStream := cipher.NewCTR(initBlock, initSecret[keyLen:])
respBlock, err := aes.NewCipher(respSecret[:keyLen])
if err != nil {
return err
}
respStream := cipher.NewCTR(respBlock, respSecret[keyLen:])
if conn.isInitiator {
conn.tx = &cipher.StreamWriter{S: initStream, W: conn.Conn}
conn.rx = &cipher.StreamReader{S: respStream, R: conn.rxBuf}
conn.txMagic = initMagic
conn.rxMagic = respMagic
} else {
conn.tx = &cipher.StreamWriter{S: respStream, W: conn.Conn}
conn.rx = &cipher.StreamReader{S: initStream, R: conn.rxBuf}
conn.txMagic = respMagic
conn.rxMagic = initMagic
}
return nil
}
开发者ID:OperatorFoundation,项目名称:obfs4,代码行数:59,代码来源:obfs3.go
示例14: MAC
func (creds *Credentials) MAC() hash.Hash {
if creds.Hash != nil {
return hmac.New(creds.Hash, []byte(creds.Key))
} else {
// use a default hash
return hmac.New(sha256.New, []byte(creds.Key))
}
}
开发者ID:mozilla-services,项目名称:hawk-go,代码行数:8,代码来源:hawk.go
示例15: TestTOTP
func TestTOTP(t *testing.T) {
keySha1, err := hex.DecodeString(sha1KeyHex)
checkError(t, err)
keySha256, err := hex.DecodeString(sha256KeyHex)
checkError(t, err)
keySha512, err := hex.DecodeString(sha512KeyHex)
checkError(t, err)
// create the OTP
otp := new(Totp)
otp.digits = 8
otp.issuer = "Sec51"
otp.account = "[email protected]"
// Test SHA1
otp.key = keySha1
for index, ts := range timeCounters {
counter := increment(ts, 30)
otp.counter = bigendian.ToUint64(counter)
hash := hmac.New(sha1.New, otp.key)
token := calculateToken(otp.counter[:], otp.digits, hash)
expected := sha1TestData[index]
if token != expected {
t.Errorf("SHA1 test data, token mismatch. Got %s, expected %s\n", token, expected)
}
}
// Test SHA256
otp.key = keySha256
for index, ts := range timeCounters {
counter := increment(ts, 30)
otp.counter = bigendian.ToUint64(counter)
hash := hmac.New(sha256.New, otp.key)
token := calculateToken(otp.counter[:], otp.digits, hash)
expected := sha256TestData[index]
if token != expected {
t.Errorf("SHA256 test data, token mismatch. Got %s, expected %s\n", token, expected)
}
}
// Test SHA512
otp.key = keySha512
for index, ts := range timeCounters {
counter := increment(ts, 30)
otp.counter = bigendian.ToUint64(counter)
hash := hmac.New(sha512.New, otp.key)
token := calculateToken(otp.counter[:], otp.digits, hash)
expected := sha512TestData[index]
if token != expected {
t.Errorf("SHA512 test data, token mismatch. Got %s, expected %s\n", token, expected)
}
}
}
开发者ID:sec51,项目名称:twofactor,代码行数:57,代码来源:totp_test.go
示例16: makeMac
func makeMac(hashType string, key []byte) (hash.Hash, int) {
switch hashType {
case "SHA1":
return hmac.New(sha1.New, key), sha1.Size
case "SHA512":
return hmac.New(sha512.New, key), sha512.Size
default:
return hmac.New(sha256.New, key), sha256.Size
}
}
开发者ID:mappum,项目名称:go-ipfs,代码行数:10,代码来源:identify.go
示例17: New
// New returns a new HKDF using the given hash, the secret keying material to expand
// and optional salt and info fields.
func New(hash func() hash.Hash, secret, salt, info []byte) io.Reader {
if salt == nil {
salt = make([]byte, hash().Size())
}
extractor := hmac.New(hash, salt)
extractor.Write(secret)
prk := extractor.Sum(nil)
return &hkdf{hmac.New(hash, prk), extractor.Size(), info, 1, nil, nil}
}
开发者ID:conseweb,项目名称:golangcrypto,代码行数:12,代码来源:hkdf.go
示例18: macHash
// MAC hash helper function
func macHash(algo, secKey, normalized string) []byte {
var h hash.Hash
if algo == "sha1" {
h = hmac.New(sha1.New, []byte(secKey))
} else {
h = hmac.New(sha256.New, []byte(secKey))
}
h.Write([]byte(normalized))
return h.Sum(nil)
}
开发者ID:codehalla,项目名称:valkyrie,代码行数:11,代码来源:hawk.go
示例19: callbackGoogleGet
func callbackGoogleGet(c *gin.Context) {
db := c.MustGet("db").(*database.Database)
params := utils.ParseParams(c.Request)
state := params.GetByName("state")
code := params.GetByName("code")
authErr := params.GetByName("error")
switch authErr {
case "":
if state == "" || code == "" {
c.AbortWithStatus(400)
return
}
case "access_denied":
// TODO Redirect to base callback url
c.Redirect(301, "https://pritunl.com/")
return
default:
c.AbortWithStatus(400)
return
}
acct, tokn, err := google.Authorize(db, state, code)
if err != nil {
c.AbortWithError(500, err)
return
}
if tokn.Version == 1 {
query := fmt.Sprintf("state=%s&username=%s", tokn.RemoteState,
url.QueryEscape(acct.Id))
hashFunc := hmac.New(sha512.New, []byte(tokn.RemoteSecret))
hashFunc.Write([]byte(query))
rawSignature := hashFunc.Sum(nil)
sig := base64.URLEncoding.EncodeToString(rawSignature)
url := fmt.Sprintf("%s?%s&sig=%s",
tokn.RemoteCallback, query, url.QueryEscape(sig))
c.Redirect(301, url)
} else {
hashFunc := hmac.New(sha256.New, []byte(tokn.RemoteSecret))
hashFunc.Write([]byte(tokn.RemoteState + acct.Id))
rawSignature := hashFunc.Sum(nil)
sig := base64.URLEncoding.EncodeToString(rawSignature)
c.Redirect(301, fmt.Sprintf("%s?state=%s&user=%s&sig=%s",
tokn.RemoteCallback, tokn.RemoteState,
url.QueryEscape(acct.Id), sig))
}
}
开发者ID:postfix,项目名称:pritunl-auth,代码行数:54,代码来源:callback.go
示例20: serverSignature
func (c *connectionHandshakeV1_0) serverSignature(saltedPass []byte) string {
mac := hmac.New(c.hashFunc(), saltedPass)
mac.Write([]byte("Server Key"))
serverKey := mac.Sum(nil)
mac = hmac.New(c.hashFunc(), serverKey)
mac.Write([]byte(c.authMsg))
serverSignature := mac.Sum(nil)
return base64.StdEncoding.EncodeToString(serverSignature)
}
开发者ID:freedmand,项目名称:doc.vu,代码行数:11,代码来源:connection_handshake.go
注:本文中的crypto/hmac.New函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论