decrypt.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package template
  14. import (
  15. "crypto"
  16. "crypto/rsa"
  17. "crypto/sha256"
  18. "crypto/sha512"
  19. "encoding/pem"
  20. "errors"
  21. "fmt"
  22. "hash"
  23. )
  24. var (
  25. errParsePK = errors.New("could not parse private key")
  26. errRSADecrypt = errors.New("error decrypting data with RSA")
  27. )
  28. const (
  29. errSchemeNotSupported = "decryption scheme %v is not supported"
  30. errParseRSAPK = "could not parse RSA private key"
  31. errDecodePEM = "failed to decode PEM block"
  32. errWrap = "%w: %v"
  33. )
  34. func rsaDecrypt(scheme, hash, in, privateKey string) (string, error) {
  35. switch scheme {
  36. case "None":
  37. return in, nil
  38. case "RSA-OAEP":
  39. pemBlock, _ := pem.Decode([]byte(privateKey))
  40. if pemBlock == nil {
  41. return "", fmt.Errorf(errDecodePEM)
  42. }
  43. parsedPrivateKey, err := parsePrivateKey(pemBlock.Bytes)
  44. if err != nil {
  45. return "", fmt.Errorf(errWrap, errParsePK, err)
  46. }
  47. rsaPrivateKey, isValid := parsedPrivateKey.(*rsa.PrivateKey)
  48. if !isValid {
  49. return "", fmt.Errorf(errParseRSAPK)
  50. }
  51. out, err := rsa.DecryptOAEP(getHash(hash), nil, rsaPrivateKey, []byte(in), nil)
  52. if err != nil {
  53. return "", fmt.Errorf(errWrap, errRSADecrypt, err)
  54. }
  55. return string(out), nil
  56. default:
  57. return "", fmt.Errorf(errSchemeNotSupported, scheme)
  58. }
  59. }
  60. func getHash(hash string) hash.Hash {
  61. switch hash {
  62. case "None":
  63. return sha256.New()
  64. case "SHA1":
  65. return crypto.SHA1.New()
  66. case "SHA256":
  67. return sha256.New()
  68. case "SHA512":
  69. return sha512.New()
  70. default:
  71. return sha256.New()
  72. }
  73. }