package main import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "fmt" "os" ) func main() { // 生成RSA密钥对 privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { fmt.Println("Failed to generate RSA private key:", err) return } // 将私钥保存到文件 privateKeyFile, err := os.Create("private_key.pem") if err != nil { fmt.Println("Failed to create private key file:", err) return } defer privateKeyFile.Close() privateKeyBlock := &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey), } err = pem.Encode(privateKeyFile, privateKeyBlock) if err != nil { fmt.Println("Failed to write private key to file:", err) return } fmt.Println("Private key generated and saved to private_key.pem") // 获取公钥 publicKey := &privateKey.PublicKey // 将公钥保存到文件 publicKeyFile, err := os.Create("public_key.pem") if err != nil { fmt.Println("Failed to create public key file:", err) return } defer publicKeyFile.Close() publicKeyBlock := &pem.Block{ Type: "RSA PUBLIC KEY", Bytes: x509.MarshalPKCS1PublicKey(publicKey), } err = pem.Encode(publicKeyFile, publicKeyBlock) if err != nil { fmt.Println("Failed to write public key to file:", err) return } fmt.Println("Public key generated and saved to public_key.pem") }