feat: add LoadRSACrt
This commit is contained in:
69
tool/rsa.go
69
tool/rsa.go
@@ -184,3 +184,72 @@ func RSADecrypt(encryptedBase64 string, cfg *tls.Config) ([]byte, error) {
|
||||
|
||||
return decrypted, nil
|
||||
}
|
||||
|
||||
func LoadRSACertificate(pubKeyBytes, priKeyBytes []byte) (*rsa.PublicKey, *rsa.PrivateKey, error) {
|
||||
var (
|
||||
err error
|
||||
pubKey *rsa.PublicKey
|
||||
priKey *rsa.PrivateKey
|
||||
)
|
||||
|
||||
if len(pubKeyBytes) == 0 && len(priKeyBytes) == 0 {
|
||||
return nil, nil, errors.New("both public and private key bytes are empty")
|
||||
}
|
||||
|
||||
if len(pubKeyBytes) > 0 {
|
||||
pubKey, err = parsePublicKey(pubKeyBytes)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if len(priKeyBytes) > 0 {
|
||||
priKey, err = parsePrivateKey(priKeyBytes)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return pubKey, priKey, nil
|
||||
}
|
||||
|
||||
func parsePublicKey(pubKeyBytes []byte) (*rsa.PublicKey, error) {
|
||||
block, _ := pem.Decode(pubKeyBytes)
|
||||
if block == nil {
|
||||
return nil, errors.New("failed to decode public key")
|
||||
}
|
||||
|
||||
pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rsaPubKey, ok := pubKey.(*rsa.PublicKey)
|
||||
if !ok {
|
||||
return nil, errors.New("not an RSA public key")
|
||||
}
|
||||
|
||||
return rsaPubKey, nil
|
||||
}
|
||||
|
||||
func parsePrivateKey(priKeyBytes []byte) (*rsa.PrivateKey, error) {
|
||||
block, _ := pem.Decode(priKeyBytes)
|
||||
if block == nil {
|
||||
return nil, errors.New("failed to decode private key")
|
||||
}
|
||||
|
||||
priKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
priKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
rsaPriKey, ok := priKey.(*rsa.PrivateKey)
|
||||
if !ok {
|
||||
return nil, errors.New("not an RSA private key")
|
||||
}
|
||||
|
||||
return rsaPriKey, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user