yunion.io/x/cloudmux@v0.3.10-0-alpha.1/pkg/multicloud/ecloud/signer.go (about)

     1  // Copyright 2019 Yunion
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package ecloud
    16  
    17  import (
    18  	"crypto/hmac"
    19  	"crypto/sha1"
    20  	"encoding/hex"
    21  
    22  	"yunion.io/x/pkg/util/stringutils"
    23  )
    24  
    25  type ISigner interface {
    26  	GetName() string
    27  	GetVersion() string
    28  	GetAccessKeyId() string
    29  	GetNonce() string
    30  	Sign(stringToSign, secretPrefix string) string
    31  }
    32  
    33  type SRamRoleSigner struct {
    34  	accessKeyId     string
    35  	accessKeySecret string
    36  }
    37  
    38  func NewRamRoleSigner(accessKeyId, accessKeySecret string) *SRamRoleSigner {
    39  	return &SRamRoleSigner{
    40  		accessKeyId:     accessKeyId,
    41  		accessKeySecret: accessKeySecret,
    42  	}
    43  }
    44  
    45  func (s *SRamRoleSigner) GetName() string {
    46  	return "HmacSHA1"
    47  }
    48  
    49  func (s *SRamRoleSigner) GetVersion() string {
    50  	return "V2.0"
    51  }
    52  
    53  func (s *SRamRoleSigner) GetAccessKeyId() string {
    54  	return s.accessKeyId
    55  }
    56  
    57  func (s *SRamRoleSigner) GetNonce() string {
    58  	return stringutils.UUID4()
    59  }
    60  
    61  func (s *SRamRoleSigner) Sign(stringToSign, secretPrefix string) string {
    62  	secret := secretPrefix + s.accessKeySecret
    63  	return shaHmac1(stringToSign, secret)
    64  }
    65  
    66  func shaHmac1(source, secret string) string {
    67  	key := []byte(secret)
    68  	hmac := hmac.New(sha1.New, key)
    69  	hmac.Write([]byte(source))
    70  	signedBytes := hmac.Sum(nil)
    71  	return hex.EncodeToString(signedBytes)
    72  }