本站源代码
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.

38 lines
1.0KB

  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
  5. import (
  6. "crypto/rsa"
  7. "crypto/x509"
  8. "encoding/pem"
  9. "errors"
  10. "fmt"
  11. )
  12. // ParseKey converts the binary contents of a private key file
  13. // to an *rsa.PrivateKey. It detects whether the private key is in a
  14. // PEM container or not. If so, it extracts the the private key
  15. // from PEM container before conversion. It only supports PEM
  16. // containers with no passphrase.
  17. func ParseKey(key []byte) (*rsa.PrivateKey, error) {
  18. block, _ := pem.Decode(key)
  19. if block != nil {
  20. key = block.Bytes
  21. }
  22. parsedKey, err := x509.ParsePKCS8PrivateKey(key)
  23. if err != nil {
  24. parsedKey, err = x509.ParsePKCS1PrivateKey(key)
  25. if err != nil {
  26. return nil, fmt.Errorf("private key should be a PEM or plain PKCS1 or PKCS8; parse error: %v", err)
  27. }
  28. }
  29. parsed, ok := parsedKey.(*rsa.PrivateKey)
  30. if !ok {
  31. return nil, errors.New("private key is invalid")
  32. }
  33. return parsed, nil
  34. }
上海开阖软件有限公司 沪ICP备12045867号-1