code.gitea.io/gitea@v1.19.3/modules/secret/secret.go (about)

     1  // Copyright 2019 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package secret
     5  
     6  import (
     7  	"crypto/aes"
     8  	"crypto/cipher"
     9  	"crypto/rand"
    10  	"crypto/sha256"
    11  	"encoding/base64"
    12  	"encoding/hex"
    13  	"errors"
    14  	"io"
    15  )
    16  
    17  // AesEncrypt encrypts text and given key with AES.
    18  func AesEncrypt(key, text []byte) ([]byte, error) {
    19  	block, err := aes.NewCipher(key)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	b := base64.StdEncoding.EncodeToString(text)
    24  	ciphertext := make([]byte, aes.BlockSize+len(b))
    25  	iv := ciphertext[:aes.BlockSize]
    26  	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
    27  		return nil, err
    28  	}
    29  	cfb := cipher.NewCFBEncrypter(block, iv)
    30  	cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
    31  	return ciphertext, nil
    32  }
    33  
    34  // AesDecrypt decrypts text and given key with AES.
    35  func AesDecrypt(key, text []byte) ([]byte, error) {
    36  	block, err := aes.NewCipher(key)
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  	if len(text) < aes.BlockSize {
    41  		return nil, errors.New("ciphertext too short")
    42  	}
    43  	iv := text[:aes.BlockSize]
    44  	text = text[aes.BlockSize:]
    45  	cfb := cipher.NewCFBDecrypter(block, iv)
    46  	cfb.XORKeyStream(text, text)
    47  	data, err := base64.StdEncoding.DecodeString(string(text))
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	return data, nil
    52  }
    53  
    54  // EncryptSecret encrypts a string with given key into a hex string
    55  func EncryptSecret(key, str string) (string, error) {
    56  	keyHash := sha256.Sum256([]byte(key))
    57  	plaintext := []byte(str)
    58  	ciphertext, err := AesEncrypt(keyHash[:], plaintext)
    59  	if err != nil {
    60  		return "", err
    61  	}
    62  	return hex.EncodeToString(ciphertext), nil
    63  }
    64  
    65  // DecryptSecret decrypts a previously encrypted hex string
    66  func DecryptSecret(key, cipherhex string) (string, error) {
    67  	keyHash := sha256.Sum256([]byte(key))
    68  	ciphertext, err := hex.DecodeString(cipherhex)
    69  	if err != nil {
    70  		return "", err
    71  	}
    72  	plaintext, err := AesDecrypt(keyHash[:], ciphertext)
    73  	if err != nil {
    74  		return "", err
    75  	}
    76  	return string(plaintext), nil
    77  }