dubbo.apache.org/dubbo-go/v3@v3.1.1/filter/auth/sign_util.go (about)

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   * contributor license agreements.  See the NOTICE file distributed with
     4   * this work for additional information regarding copyright ownership.
     5   * The ASF licenses this file to You under the Apache License, Version 2.0
     6   * (the "License"); you may not use this file except in compliance with
     7   * the License.  You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package auth
    19  
    20  import (
    21  	"crypto/hmac"
    22  	"crypto/sha256"
    23  	"encoding/base64"
    24  	"encoding/json"
    25  	"errors"
    26  	"strings"
    27  )
    28  
    29  import (
    30  	"github.com/dubbogo/gost/log/logger"
    31  )
    32  
    33  // Sign gets a signature string with given bytes
    34  func Sign(metadata, key string) string {
    35  	return doSign([]byte(metadata), key)
    36  }
    37  
    38  // SignWithParams returns a signature with giving params and metadata.
    39  func SignWithParams(params []interface{}, metadata, key string) (string, error) {
    40  	if len(params) == 0 {
    41  		return Sign(metadata, key), nil
    42  	}
    43  
    44  	data := append(params, metadata)
    45  	if bytes, err := toBytes(data); err != nil {
    46  		// TODO
    47  		return "", errors.New("data convert to bytes failed")
    48  	} else {
    49  		return doSign(bytes, key), nil
    50  	}
    51  }
    52  
    53  func toBytes(data []interface{}) ([]byte, error) {
    54  	if bytes, err := json.Marshal(data); err != nil {
    55  		return nil, errors.New("")
    56  	} else {
    57  		return bytes, nil
    58  	}
    59  }
    60  
    61  func doSign(bytes []byte, key string) string {
    62  	mac := hmac.New(sha256.New, []byte(key))
    63  	if _, err := mac.Write(bytes); err != nil {
    64  		logger.Error(err)
    65  	}
    66  	signature := mac.Sum(nil)
    67  	return base64.URLEncoding.EncodeToString(signature)
    68  }
    69  
    70  // IsEmpty verify whether the inputted string is empty
    71  func IsEmpty(s string, allowSpace bool) bool {
    72  	if len(s) == 0 {
    73  		return true
    74  	}
    75  	if !allowSpace {
    76  		return strings.TrimSpace(s) == ""
    77  	}
    78  	return false
    79  }