package crypto import ( "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/pem" "errors" "fmt" "io/ioutil" ) // LoadRSAPrivateKeyFromFile 加载私钥 func LoadRSAPrivateKeyFromFile(filename string) (*rsa.PrivateKey, error) { privBytes, err := ioutil.ReadFile(filename) if err != nil { return nil, fmt.Errorf("无法读取私钥文件: %v", err) } block, _ := pem.Decode(privBytes) if block == nil || block.Type != "RSA PRIVATE KEY" { return nil, errors.New("无效的私钥格式") } privKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("解析私钥失败: %v", err) } return privKey, nil } // RSADecrypt 使用私钥解密AES密钥 func RSADecrypt(privKey *rsa.PrivateKey, encryptedKeyBase64 string) ([]byte, error) { // Base64 解码 encryptedKey, err := base64.StdEncoding.DecodeString(encryptedKeyBase64) if err != nil { return nil, fmt.Errorf("Base64解码失败: %v", err) } // RSA 解密 decryptedKey, err := rsa.DecryptPKCS1v15(nil, privKey, encryptedKey) if err != nil { return nil, fmt.Errorf("RSA解密失败: %v", err) } return decryptedKey, nil }