github.com/n00py/Slackor@v0.0.0-20200610224921-d007fcea1740/internal/crypto/decrypt.go (about)

     1  package crypto
     2  
     3  import (
     4  	"crypto/aes"
     5  	"crypto/cipher"
     6  	"encoding/base64"
     7  
     8  	"github.com/n00py/Slackor/internal/config"
     9  )
    10  
    11  func PKCS5UnPadding(origData []byte) []byte { //Used for Crypto
    12  	length := len(origData)
    13  	unpadding := int(origData[length-1])
    14  	return origData[:(length - unpadding)]
    15  }
    16  
    17  func DecryptFile(crypted []byte) (string, error) { // Decrypt a file (currently unused)
    18  	decodeData := []byte(crypted)
    19  	block, err := aes.NewCipher(config.CipherKeyBytes)
    20  	if err != nil {
    21  		return "", err
    22  	}
    23  	blockMode := cipher.NewCBCDecrypter(block, config.CipherIV)
    24  	origData := make([]byte, len(decodeData))
    25  	blockMode.CryptBlocks(origData, decodeData)
    26  	origData = PKCS5UnPadding(origData)
    27  	return string(origData), nil
    28  }
    29  
    30  func Decrypt(crypted string) (string, error) { // decrypt a string
    31  	decodeData, err := base64.StdEncoding.DecodeString(crypted)
    32  	if err != nil {
    33  		return "", err
    34  	}
    35  	block, err := aes.NewCipher(config.CipherKeyBytes)
    36  	if err != nil {
    37  		return "", err
    38  	}
    39  	blockMode := cipher.NewCBCDecrypter(block, config.CipherIV)
    40  	origData := make([]byte, len(decodeData))
    41  	blockMode.CryptBlocks(origData, decodeData)
    42  	origData = PKCS5UnPadding(origData)
    43  	return string(origData), nil
    44  }