File: key.go

package info (click to toggle)
golang-github-zitadel-oidc 3.37.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 1,484 kB
  • sloc: makefile: 5
file content (45 lines) | stat: -rw-r--r-- 1,093 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package crypto

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/ed25519"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"errors"

	"github.com/go-jose/go-jose/v4"
)

var (
	ErrPEMDecode             = errors.New("PEM decode failed")
	ErrUnsupportedFormat     = errors.New("key is neither in PKCS#1 nor PKCS#8 format")
	ErrUnsupportedPrivateKey = errors.New("unsupported key type, must be RSA, ECDSA or ED25519 private key")
)

func BytesToPrivateKey(b []byte) (crypto.PublicKey, jose.SignatureAlgorithm, error) {
	block, _ := pem.Decode(b)
	if block == nil {
		return nil, "", ErrPEMDecode
	}

	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err == nil {
		return privateKey, jose.RS256, nil
	}
	key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		return nil, "", ErrUnsupportedFormat
	}
	switch privateKey := key.(type) {
	case *rsa.PrivateKey:
		return privateKey, jose.RS256, nil
	case ed25519.PrivateKey:
		return privateKey, jose.EdDSA, nil
	case *ecdsa.PrivateKey:
		return privateKey, jose.ES256, nil
	default:
		return nil, "", ErrUnsupportedPrivateKey
	}
}