...

Source file src/github.com/ory/x/tracing/traced_bcrypt.go

Documentation: github.com/ory/x/tracing

     1  package tracing
     2  
     3  import (
     4  	"context"
     5  
     6  	opentracing "github.com/opentracing/opentracing-go"
     7  	"github.com/opentracing/opentracing-go/ext"
     8  	"github.com/pkg/errors"
     9  	"golang.org/x/crypto/bcrypt"
    10  )
    11  
    12  const (
    13  	// BCryptHashOpName is the operation name for bcrypt hashing operations.
    14  	BCryptHashOpName = "bcrypt.hash"
    15  
    16  	// BCryptCompareOpName is the operation name for bcrypt comparation operations.
    17  	BCryptCompareOpName = "bcrypt.compare"
    18  
    19  	// BCryptWorkFactorTagName is the operation name for bcrypt workfactor settings.
    20  	BCryptWorkFactorTagName = "bcrypt.workfactor"
    21  )
    22  
    23  // TracedBCrypt implements the Hasher interface.
    24  type TracedBCrypt struct {
    25  	WorkFactor int
    26  }
    27  
    28  // Hash returns the hashed string or an error.
    29  func (b *TracedBCrypt) Hash(ctx context.Context, data []byte) ([]byte, error) {
    30  	span, _ := opentracing.StartSpanFromContext(ctx, BCryptHashOpName)
    31  	defer span.Finish()
    32  	span.SetTag(BCryptWorkFactorTagName, b.WorkFactor)
    33  
    34  	s, err := bcrypt.GenerateFromPassword(data, b.WorkFactor)
    35  	if err != nil {
    36  		ext.Error.Set(span, true)
    37  		return nil, errors.WithStack(err)
    38  	}
    39  	return s, nil
    40  }
    41  
    42  // Compare returns nil if hash and data match.
    43  func (b *TracedBCrypt) Compare(ctx context.Context, hash, data []byte) error {
    44  	span, _ := opentracing.StartSpanFromContext(ctx, BCryptCompareOpName)
    45  	defer span.Finish()
    46  	span.SetTag(BCryptWorkFactorTagName, b.WorkFactor)
    47  
    48  	if err := bcrypt.CompareHashAndPassword(hash, data); err != nil {
    49  		ext.Error.Set(span, true)
    50  		return errors.WithStack(err)
    51  	}
    52  	return nil
    53  }
    54  

View as plain text