|
| 1 | +// Copyright 2021 The Gitea Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a MIT-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package secrets |
| 6 | + |
| 7 | +import ( |
| 8 | + "crypto/aes" |
| 9 | + "crypto/cipher" |
| 10 | + "crypto/rand" |
| 11 | + "encoding/base64" |
| 12 | + "fmt" |
| 13 | + "io" |
| 14 | +) |
| 15 | + |
| 16 | +type aesEncryptionProvider struct { |
| 17 | +} |
| 18 | + |
| 19 | +func NewAesEncryptionProvider() EncryptionProvider { |
| 20 | + return &aesEncryptionProvider{} |
| 21 | +} |
| 22 | + |
| 23 | +func (e *aesEncryptionProvider) Encrypt(secret, key []byte) ([]byte, error) { |
| 24 | + block, err := aes.NewCipher(key) |
| 25 | + if err != nil { |
| 26 | + return nil, err |
| 27 | + } |
| 28 | + |
| 29 | + c, err := cipher.NewGCM(block) |
| 30 | + if err != nil { |
| 31 | + return nil, err |
| 32 | + } |
| 33 | + |
| 34 | + nonce := make([]byte, c.NonceSize(), c.NonceSize()+c.Overhead()+len(secret)) |
| 35 | + if _, err = io.ReadFull(rand.Reader, nonce); err != nil { |
| 36 | + return nil, err |
| 37 | + } |
| 38 | + out := c.Seal(nil, nonce, secret, nil) |
| 39 | + |
| 40 | + return append(nonce, out...), nil |
| 41 | +} |
| 42 | + |
| 43 | +func (e *aesEncryptionProvider) EncryptString(secret string, key []byte) (string, error) { |
| 44 | + out, err := e.Encrypt([]byte(secret), key) |
| 45 | + if err != nil { |
| 46 | + return "", err |
| 47 | + } |
| 48 | + return base64.StdEncoding.EncodeToString(out), nil |
| 49 | +} |
| 50 | + |
| 51 | +func (e *aesEncryptionProvider) Decrypt(enc, key []byte) ([]byte, error) { |
| 52 | + block, err := aes.NewCipher(key) |
| 53 | + if err != nil { |
| 54 | + return nil, err |
| 55 | + } |
| 56 | + |
| 57 | + c, err := cipher.NewGCM(block) |
| 58 | + if err != nil { |
| 59 | + return nil, err |
| 60 | + } |
| 61 | + |
| 62 | + if len(enc) < c.NonceSize() { |
| 63 | + return nil, fmt.Errorf("encrypted value too short") |
| 64 | + } |
| 65 | + |
| 66 | + nonce := enc[:c.NonceSize()] |
| 67 | + ciphertext := enc[c.NonceSize():] |
| 68 | + |
| 69 | + out, err := c.Open(nil, nonce, ciphertext, nil) |
| 70 | + if err != nil { |
| 71 | + return nil, err |
| 72 | + } |
| 73 | + |
| 74 | + return out, nil |
| 75 | +} |
| 76 | + |
| 77 | +func (e *aesEncryptionProvider) DecryptString(enc string, key []byte) (string, error) { |
| 78 | + encb, err := base64.StdEncoding.DecodeString(enc) |
| 79 | + if err != nil { |
| 80 | + return "", err |
| 81 | + } |
| 82 | + |
| 83 | + out, err := e.Encrypt(encb, key) |
| 84 | + if err != nil { |
| 85 | + return "", err |
| 86 | + } |
| 87 | + |
| 88 | + return string(out), nil |
| 89 | +} |
0 commit comments