You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

secret.go 2.3KB

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