add openssh private key method

master
兔子 3 months ago
parent f3f50b4f6c
commit e722b958a4

@ -3,12 +3,14 @@ package starcrypto
import ( import (
"crypto" "crypto"
"crypto/ecdsa" "crypto/ecdsa"
"crypto/ed25519"
"crypto/rand" "crypto/rand"
"crypto/rsa" "crypto/rsa"
"crypto/x509" "crypto/x509"
"encoding/pem" "encoding/pem"
"errors" "errors"
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
"reflect"
) )
func EncodePrivateKey(private crypto.PrivateKey, secret string) ([]byte, error) { 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 nil, err
} }
return prikey, 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: default:
return nil, errors.New("private key type error") 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) { func DecodePublicKey(pubStr []byte) (crypto.PublicKey, error) {
blk, _ := pem.Decode(pubStr) blk, _ := pem.Decode(pubStr)
if blk == nil { if blk == nil {

Loading…
Cancel
Save