1 Star 1 Fork 0

zhuyuns / basic

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
key.go 2.32 KB
一键复制 编辑 原始数据 按行查看 历史
wing 提交于 2021-12-18 11:42 . 添加基础包
package rsa
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"io/ioutil"
"strings"
)
type Key interface {
PublicKey() *rsa.PublicKey
PrivateKey() *rsa.PrivateKey
Modulus() int
}
func ParsePKCS8Key(publicKey, privateKey []byte) (Key, error) {
puk, err := x509.ParsePKIXPublicKey(publicKey)
if err != nil {
return nil, err
}
prk, err := x509.ParsePKCS8PrivateKey(privateKey)
if err != nil {
return nil, err
}
return &key{publicKey: puk.(*rsa.PublicKey), privateKey: prk.(*rsa.PrivateKey)}, nil
}
func ParsePKCS1Key(publicKey, privateKey []byte) (Key, error) {
puk, err := x509.ParsePKIXPublicKey(publicKey)
if err != nil {
return nil, err
}
prk, err := x509.ParsePKCS1PrivateKey(privateKey)
if err != nil {
return nil, err
}
return &key{publicKey: puk.(*rsa.PublicKey), privateKey: prk}, nil
}
func LoadKeyFromPEMFile(publicKeyFilePath, privateKeyFilePath string, ParseKey func([]byte, []byte) (Key, error)) (Key, error) {
//TODO 断言如果入参为"" ,则直接报错
publicKeyFilePath = strings.TrimSpace(publicKeyFilePath)
pukBytes, err := ioutil.ReadFile(publicKeyFilePath)
if err != nil {
return nil, err
}
puk, _ := pem.Decode(pukBytes)
if puk == nil {
return nil, errors.New("publicKey is not pem formate")
}
privateKeyFilePath = strings.TrimSpace(privateKeyFilePath)
prkBytes, err := ioutil.ReadFile(privateKeyFilePath)
if err != nil {
return nil, err
}
prk, _ := pem.Decode(prkBytes)
if prk == nil {
return nil, errors.New("privateKey is not pem formate")
}
return ParseKey(puk.Bytes, prk.Bytes)
}
func ParsePKCS1KeyPublic(publicKey []byte) (Key, error) {
puk, err := x509.ParsePKIXPublicKey(publicKey)
if err != nil {
return nil, err
}
return &key{publicKey: puk.(*rsa.PublicKey)}, nil
}
func ParsePKCS1KeyPrivate(privateKey []byte) (Key, error) {
prk, err := x509.ParsePKCS1PrivateKey(privateKey)
if err != nil {
return nil, err
}
return &key{privateKey: prk}, nil
}
type key struct {
publicKey *rsa.PublicKey
privateKey *rsa.PrivateKey
}
func (key *key) Modulus() int {
return len(key.publicKey.N.Bytes())
}
func (key *key) PublicKey() *rsa.PublicKey {
return key.publicKey
}
func (key *key) PrivateKey() *rsa.PrivateKey {
return key.privateKey
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/zhuyuns/basic.git
git@gitee.com:zhuyuns/basic.git
zhuyuns
basic
basic
v0.0.53

搜索帮助

344bd9b3 5694891 D2dac590 5694891