-
Notifications
You must be signed in to change notification settings - Fork 156
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
134 additions
and
37 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,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) (*rsa.PrivateKey, error) { | ||
func BytesToPrivateKey(b []byte) (crypto.PublicKey, jose.SignatureAlgorithm, error) { | ||
block, _ := pem.Decode(b) | ||
if block == nil { | ||
return nil, errors.New("PEM decode failed") | ||
return nil, "", ErrPEMDecode | ||
} | ||
|
||
key, err := x509.ParsePKCS1PrivateKey(block.Bytes) | ||
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, err | ||
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 | ||
} | ||
|
||
return key, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters