add openssh private key method

master
兔子 2 months ago
parent f3f50b4f6c
commit e722b958a4

@ -3,12 +3,14 @@ package starcrypto
import (
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"golang.org/x/crypto/ssh"
"reflect"
)
func EncodePrivateKey(private crypto.PrivateKey, secret string) ([]byte, error) {
@ -87,11 +89,41 @@ func DecodePrivateKey(private []byte, password string) (crypto.PrivateKey, error
return nil, err
}
return prikey, err
case "OPENSSH PRIVATE KEY":
var err error
var priv crypto.PrivateKey
if password == "" {
priv, err = ssh.ParseRawPrivateKey(private)
if err != nil {
return nil, err
}
} else {
priv, err = ssh.ParseRawPrivateKeyWithPassphrase(private, []byte(password))
if err != nil {
return nil, err
}
}
return priv, nil
default:
return nil, errors.New("private key type error")
}
}
func EncodeOpenSSHPrivateKey(private crypto.PrivateKey, secret string) ([]byte, error) {
var key interface{} = private
var block *pem.Block
var err error
if reflect.TypeOf(key) == reflect.TypeOf(&ed25519.PrivateKey{}) {
key = *(key.(*ed25519.PrivateKey))
}
if secret == "" {
block, err = ssh.MarshalPrivateKey(key, "")
} else {
block, err = ssh.MarshalPrivateKeyWithPassphrase(key, "", []byte(secret))
}
return pem.EncodeToMemory(block), err
}
func DecodePublicKey(pubStr []byte) (crypto.PublicKey, error) {
blk, _ := pem.Decode(pubStr)
if blk == nil {

Loading…
Cancel
Save