From 5d3ebcd5015d1bd921c1f88172fb03aed472d3f0 Mon Sep 17 00:00:00 2001 From: starainrt Date: Sun, 10 Mar 2024 15:41:55 +0800 Subject: [PATCH] add asy.go --- asy.go | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/asy.go b/asy.go index c7cf600..ea72059 100644 --- a/asy.go +++ b/asy.go @@ -1 +1,68 @@ package starcrypto + +import ( + "crypto" + "crypto/ecdsa" + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "errors" + "golang.org/x/crypto/ssh" +) + +func EncodePrivateKey(private crypto.PrivateKey, secret string) ([]byte, error) { + switch private.(type) { + case *rsa.PrivateKey: + return EncodeRsaPrivateKey(private.(*rsa.PrivateKey), secret) + case *ecdsa.PrivateKey: + return EncodeEcdsaPrivateKey(private.(*ecdsa.PrivateKey), secret) + default: + return nil, errors.New("private key type error") + } +} + +func EncodePublicKey(public crypto.PublicKey) ([]byte, error) { + switch public.(type) { + case *rsa.PublicKey: + return EncodeRsaPublicKey(public.(*rsa.PublicKey)) + case *ecdsa.PublicKey: + return EncodeEcdsaPublicKey(public.(*ecdsa.PublicKey)) + default: + return nil, errors.New("public key type error") + } +} + +func DecodePrivateKey(private []byte, password string) (crypto.PrivateKey, error) { + blk, _ := pem.Decode(private) + if blk == nil { + return nil, errors.New("private key error") + } + switch blk.Type { + case "RSA PRIVATE KEY": + return DecodeRsaPrivateKey(private, password) + case "EC PRIVATE KEY": + return DecodeEcdsaPrivateKey(private, password) + default: + return nil, errors.New("private key type error") + } +} + +func DecodePublicKey(pubStr []byte) (crypto.PublicKey, error) { + blk, _ := pem.Decode(pubStr) + if blk == nil { + return nil, errors.New("public key error") + } + pub, err := x509.ParsePKIXPublicKey(blk.Bytes) + if err != nil { + return nil, err + } + return pub, nil +} + +func EncodeSSHPublicKey(public crypto.PublicKey) ([]byte, error) { + publicKey, err := ssh.NewPublicKey(public) + if err != nil { + return nil, err + } + return ssh.MarshalAuthorizedKey(publicKey), nil +}