证书登录校验
This commit is contained in:
@@ -7,28 +7,35 @@ import (
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 解析PKCS1公钥
|
||||
// https://uutool.cn/rsa-generate/
|
||||
func ParsePKCS1PublicKey(publicKeyPEM string) (*rsa.PublicKey, error) {
|
||||
block, _ := pem.Decode([]byte(publicKeyPEM))
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("无效的公钥 -----BEGIN RSA PUBLIC KEY----- 编码")
|
||||
}
|
||||
|
||||
pubKey, err := x509.ParsePKCS1PublicKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return pubKey, nil
|
||||
}
|
||||
|
||||
// 验证签名
|
||||
func VerifySignature(publicKey *rsa.PublicKey, data, signature []byte) bool {
|
||||
// 验证私钥的签名, publicKey从证书里获取公钥 certificate.PublicKey
|
||||
func VerifySignature(publicKey any, data, signature []byte) bool {
|
||||
rsaPublicKey := publicKey.(*rsa.PublicKey)
|
||||
hashed := sha256.Sum256(data)
|
||||
err := rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hashed[:], signature)
|
||||
err := rsa.VerifyPKCS1v15(rsaPublicKey, crypto.SHA256, hashed[:], signature)
|
||||
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// 解析证书信息
|
||||
func ParseCert(carCertificate string) (*x509.Certificate, error) {
|
||||
// 解析头尾需要换行符
|
||||
result := strings.Split(carCertificate, "-----")
|
||||
result[2] = "\n" + result[2] + "\n"
|
||||
carCertificate = strings.Join(result, "-----")
|
||||
|
||||
// 解码证书
|
||||
block, _ := pem.Decode([]byte(carCertificate))
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("无法解码证书")
|
||||
}
|
||||
|
||||
// 解析证书
|
||||
certificate, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return certificate, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user