github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/encrypt/encrypt.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  // Copyright 2019 Drone IO, Inc.
     7  //
     8  // Licensed under the Apache License, Version 2.0 (the "License");
     9  // you may not use this file except in compliance with the License.
    10  // You may obtain a copy of the License at
    11  //
    12  //      http://www.apache.org/licenses/LICENSE-2.0
    13  //
    14  // Unless required by applicable law or agreed to in writing, software
    15  // distributed under the License is distributed on an "AS IS" BASIS,
    16  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    17  // See the License for the specific language governing permissions and
    18  // limitations under the License.
    19  
    20  package encrypt
    21  
    22  import (
    23  	"crypto/aes"
    24  	"errors"
    25  )
    26  
    27  // indicates key size is too small.
    28  var errKeySize = errors.New("encryption key must be 32 bytes")
    29  
    30  // Encrypter provides database field encryption and decryption.
    31  // Encrypted values are currently limited to strings, which is
    32  // reflected in the interface design.
    33  type Encrypter interface {
    34  	Encrypt(plaintext string) ([]byte, error)
    35  	Decrypt(ciphertext []byte) (string, error)
    36  }
    37  
    38  // New provides a new database field encrypter.
    39  func New(key string) (Encrypter, error) {
    40  	if len(key) != 32 {
    41  		return nil, errKeySize
    42  	}
    43  	b := []byte(key)
    44  	block, err := aes.NewCipher(b)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	return &Aesgcm{block: block}, nil
    49  }