github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/cry/rc4.go (about)

     1  package cry
     2  
     3  import (
     4  	"crypto/rc4"
     5  	"encoding/hex"
     6  )
     7  
     8  // RC4Opt is tructure of aes option
     9  type RC4Opt struct {
    10  	secret []byte
    11  }
    12  
    13  // NewRC4Opt is function to create new configuration of aes algorithm option
    14  // the secret must be hexa a-f & 0-9
    15  func NewRC4Opt(secret string) (*RC4Opt, error) {
    16  	return &RC4Opt{
    17  		secret: []byte(secret),
    18  	}, nil
    19  }
    20  
    21  // Encrypt encrypts the first block in src into dst.
    22  // Dst and src may point at the same memory.
    23  func (rc4Opt *RC4Opt) Encrypt(src []byte) (string, error) {
    24  	/* #nosec */
    25  	cipher, err := rc4.NewCipher(rc4Opt.secret)
    26  	if err != nil {
    27  		return "", err
    28  	}
    29  	dst := make([]byte, len(src))
    30  	cipher.XORKeyStream(dst, src)
    31  	return hex.EncodeToString(dst), nil
    32  }
    33  
    34  // Decrypt decrypts the first block in src into dst.
    35  // Dst and src may point at the same memory.
    36  func (rc4Opt *RC4Opt) Decrypt(disini []byte) (string, error) {
    37  	src, err := hex.DecodeString(string(disini))
    38  	if err != nil {
    39  		return "", err
    40  	}
    41  
    42  	/* #nosec */
    43  	cipher, err := rc4.NewCipher(rc4Opt.secret)
    44  	if err != nil {
    45  		return "", err
    46  	}
    47  	dst := make([]byte, len(src))
    48  	cipher.XORKeyStream(dst, src)
    49  	return string(dst), nil
    50  }