github.com/mundipagg/boleto-api@v0.0.0-20230620145841-3f9ec742599f/util/crypt.go (about)

     1  package util
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  	"crypto/rand"
     7  	"crypto/sha256"
     8  	"encoding/base64"
     9  	"encoding/hex"
    10  	"fmt"
    11  	"io"
    12  )
    13  
    14  const _key = "2131231231231234"
    15  
    16  //Encrypt encripta texto baseado na documentação do GO
    17  func Encrypt(s string) string {
    18  	key := []byte(_key)
    19  	plaintext := []byte(s)
    20  	block, err := aes.NewCipher(key)
    21  	if err != nil {
    22  		panic(err)
    23  	}
    24  	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    25  	iv := ciphertext[:aes.BlockSize]
    26  	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
    27  		panic(err)
    28  	}
    29  	stream := cipher.NewCFBEncrypter(block, iv)
    30  	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
    31  	// convert to base64
    32  	return base64.URLEncoding.EncodeToString(ciphertext)
    33  }
    34  
    35  //Decrypt decripta string encriptada
    36  func Decrypt(s string) string {
    37  	ciphertext, _ := base64.URLEncoding.DecodeString(s)
    38  
    39  	block, err := aes.NewCipher([]byte(_key))
    40  	if err != nil {
    41  		panic(err)
    42  	}
    43  
    44  	// The IV needs to be unique, but not secure. Therefore it's common to
    45  	// include it at the beginning of the ciphertext.
    46  	if len(ciphertext) < aes.BlockSize {
    47  		return ""
    48  	}
    49  	iv := ciphertext[:aes.BlockSize]
    50  	ciphertext = ciphertext[aes.BlockSize:]
    51  
    52  	stream := cipher.NewCFBDecrypter(block, iv)
    53  
    54  	// XORKeyStream can work in-place if the two arguments are the same.
    55  	stream.XORKeyStream(ciphertext, ciphertext)
    56  
    57  	return fmt.Sprintf("%s", ciphertext)
    58  }
    59  
    60  //Base64 converte um string para base64
    61  func Base64(s string) string {
    62  	sEnc := base64.StdEncoding.EncodeToString([]byte(s))
    63  	return sEnc
    64  }
    65  
    66  //Base64Decode converte uma string base64 para uma string normal
    67  func Base64Decode(s string) string {
    68  	sDec, _ := base64.StdEncoding.DecodeString(s)
    69  	return string(sDec)
    70  }
    71  
    72  //Sha256 converts string to hash sha256. Encode default: Base64
    73  func Sha256(s, e string) string {
    74  	var sEnc string
    75  
    76  	h := sha256.New()
    77  	h.Write([]byte(s))
    78  
    79  	switch e {
    80  	case "hex":
    81  		sEnc = hex.EncodeToString(h.Sum(nil))
    82  	default:
    83  		sEnc = base64.StdEncoding.EncodeToString(h.Sum(nil))
    84  	}
    85  	return sEnc
    86  }