package auth import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/pem" "errors" logger "eta/eta_mini_ht_api/common/component/log" "os" ) // EncryptWithRSA 使用 RSA 公钥加密数据 func EncryptWithRSA(publicKey *rsa.PublicKey, data []byte) ([]byte, error) { encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, data) if err != nil { return nil, err } return encrypted, nil } // DecryptWithRSA 使用 RSA 私钥解密数据 func DecryptWithRSA(privateKey *rsa.PrivateKey, encrypted string) ([]byte, error) { encKey, _ := base64.StdEncoding.DecodeString(encrypted) blockSize := privateKey.Size() maxChunkSize := blockSize var plaintext []byte for len(encKey) > 0 { chunkSize := maxChunkSize if len(encKey) < chunkSize { chunkSize = len(encKey) } chunk := encKey[:chunkSize] encKey = encKey[chunkSize:] decryptedChunk, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, chunk) if err != nil { return nil, err } plaintext = append(plaintext, decryptedChunk...) } return plaintext, nil } // ParsePrivateKeyFromPEM 解析RSA公钥 func ParsePrivateKeyFromPEM() (privateKey *rsa.PrivateKey, err error) { pemBlock, err := os.ReadFile("./conf/rsa_private_key.pem") block, _ := pem.Decode(pemBlock) if block == nil { logger.Error("私钥解析失败") return nil, errors.New("私钥解析失败") } privateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, err } return } func ParsePrivateKey(configPath string) (privateKey *rsa.PrivateKey, err error) { pemBlock, err := os.ReadFile(configPath) block, _ := pem.Decode(pemBlock) if block == nil { logger.Error("私钥解析失败") return nil, errors.New("私钥解析失败") } privateInfo, err := x509.ParsePKCS8PrivateKey(block.Bytes) if err != nil { return nil, err } privateKey = privateInfo.(*rsa.PrivateKey) return } func ParsePublicKey(configPath string) (publicKey *rsa.PublicKey, err error) { pemBlock, err := os.ReadFile(configPath) block, _ := pem.Decode(pemBlock) if block == nil { logger.Error("公钥解析失败") return nil, errors.New("公钥解析失败") } key, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return nil, err } publicKey = key.(*rsa.PublicKey) return } // ParsePublicKeyFromPEM 解析RSA公钥 func ParsePublicKeyFromPEM() (publicKey *rsa.PublicKey, err error) { pemBlock, err := os.ReadFile("./conf/rsa_public_key.pem") block, _ := pem.Decode(pemBlock) if block == nil { logger.Error("公钥解析失败") return nil, errors.New("公钥解析失败") } key, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return nil, err } publicKey = key.(*rsa.PublicKey) return }