github.com/wfusion/gofusion@v1.1.14/common/utils/cipher/mode_enum.go (about)

     1  package cipher
     2  
     3  import (
     4  	"github.com/spf13/cast"
     5  
     6  	"github.com/wfusion/gofusion/common/utils"
     7  )
     8  
     9  //go:generate stringer -type=Mode -trimprefix=Mode
    10  type Mode uint8
    11  
    12  const (
    13  	ModeUnknown Mode = iota
    14  	ModeECB
    15  	ModeCBC
    16  	ModeCFB
    17  	ModeCTR
    18  	ModeOFB
    19  	ModeGCM
    20  	// modeStream may be ECB but not, it is unnecessary for padding like ECB or CBC
    21  	modeStream
    22  )
    23  
    24  var (
    25  	modeEnum = utils.NewEnumString[Mode, []Mode](
    26  		map[Mode]string{
    27  			ModeECB:    "ecb",
    28  			ModeCBC:    "cbc",
    29  			ModeCFB:    "cfb",
    30  			ModeCTR:    "ctr",
    31  			ModeOFB:    "ofb",
    32  			ModeGCM:    "gcm",
    33  			modeStream: "stream",
    34  		},
    35  	)
    36  	ivMode      = utils.NewSet(ModeCBC, ModeCFB, ModeCTR, ModeOFB)
    37  	streamMode  = utils.NewSet(ModeCFB, ModeCTR, ModeOFB, ModeGCM, modeStream)
    38  	paddingMode = utils.NewSet(ModeECB, ModeCBC)
    39  )
    40  
    41  func (m Mode) Value() uint8 {
    42  	return uint8(m)
    43  }
    44  
    45  func (m Mode) String() string {
    46  	return modeEnum.String(m)
    47  }
    48  
    49  func (m Mode) IsValid() bool {
    50  	return modeEnum.IsValid(m)
    51  }
    52  
    53  func (m Mode) ShouldPadding() bool {
    54  	return paddingMode.Contains(m)
    55  }
    56  
    57  func (m Mode) NeedIV() bool {
    58  	return ivMode.Contains(m)
    59  }
    60  
    61  func (m Mode) SupportStream() bool {
    62  	return streamMode.Contains(m)
    63  }
    64  
    65  func ParseMode(s any) Mode {
    66  	switch v := s.(type) {
    67  	case string:
    68  		if enumList := modeEnum.Enum(v); len(enumList) > 0 {
    69  			return enumList[0]
    70  		}
    71  	case Mode:
    72  		return v
    73  	default:
    74  		return Mode(cast.ToInt(s))
    75  	}
    76  	return ModeUnknown
    77  }