oauth2.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package internal contains support packages for oauth2 package.
  5. package internal
  6. import (
  7. "bufio"
  8. "crypto/rsa"
  9. "crypto/x509"
  10. "encoding/pem"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "strings"
  15. )
  16. // ParseKey converts the binary contents of a private key file
  17. // to an *rsa.PrivateKey. It detects whether the private key is in a
  18. // PEM container or not. If so, it extracts the the private key
  19. // from PEM container before conversion. It only supports PEM
  20. // containers with no passphrase.
  21. func ParseKey(key []byte) (*rsa.PrivateKey, error) {
  22. block, _ := pem.Decode(key)
  23. if block != nil {
  24. key = block.Bytes
  25. }
  26. parsedKey, err := x509.ParsePKCS8PrivateKey(key)
  27. if err != nil {
  28. parsedKey, err = x509.ParsePKCS1PrivateKey(key)
  29. if err != nil {
  30. return nil, fmt.Errorf("private key should be a PEM or plain PKSC1 or PKCS8; parse error: %v", err)
  31. }
  32. }
  33. parsed, ok := parsedKey.(*rsa.PrivateKey)
  34. if !ok {
  35. return nil, errors.New("private key is invalid")
  36. }
  37. return parsed, nil
  38. }
  39. func ParseINI(ini io.Reader) (map[string]map[string]string, error) {
  40. result := map[string]map[string]string{
  41. "": map[string]string{}, // root section
  42. }
  43. scanner := bufio.NewScanner(ini)
  44. currentSection := ""
  45. for scanner.Scan() {
  46. line := strings.TrimSpace(scanner.Text())
  47. if strings.HasPrefix(line, ";") {
  48. // comment.
  49. continue
  50. }
  51. if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
  52. currentSection = strings.TrimSpace(line[1 : len(line)-1])
  53. result[currentSection] = map[string]string{}
  54. continue
  55. }
  56. parts := strings.SplitN(line, "=", 2)
  57. if len(parts) == 2 && parts[0] != "" {
  58. result[currentSection][strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
  59. }
  60. }
  61. if err := scanner.Err(); err != nil {
  62. return nil, fmt.Errorf("error scanning ini: %v", err)
  63. }
  64. return result, nil
  65. }
  66. func CondVal(v string) []string {
  67. if v == "" {
  68. return nil
  69. }
  70. return []string{v}
  71. }