ag_tools/cmd/rsa/key.go

72 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package rsa
import (
"fmt"
"os"
"archgrid.xyz/ag/toolsbox/encryption/rsa"
"github.com/spf13/cobra"
)
var (
rsaKeyOutputFile string
)
var keyGenCmd = &cobra.Command{
Use: "keygen",
Short: "生成RSA密钥对",
Long: `生成RSA密钥对密钥对将会被保存到指定的文件中。`,
Args: cobra.NoArgs,
Run: keyGenExecute,
}
func keyGenExecute(cmd *cobra.Command, args []string) {
if len(rsaKeyOutputFile) == 0 {
fmt.Println("必须指定密钥输出文件名的前缀。")
return
}
keyPair, err := rsa.NewKeyPair(rsaKeyLength.IntoRSAKeyLength())
if err != nil {
fmt.Printf("无法生成RSA密钥对%s\n", err)
return
}
privateKeyBytes, err := rsa.EncodePrivateKey(keyPair.PrivateKey)
if err != nil {
fmt.Printf("无法编码RSA私钥%s\n", err)
return
}
privateKeyFile, err := os.OpenFile(rsaKeyOutputFile+".pri.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
fmt.Printf("无法创建RSA私钥文件%s\n", err)
return
}
defer privateKeyFile.Close()
_, err = privateKeyFile.Write(privateKeyBytes)
if err != nil {
fmt.Printf("无法写入RSA私钥文件%s\n", err)
return
}
publicKeyBytes, err := rsa.EncodePublicKey(keyPair.PublicKey)
if err != nil {
fmt.Printf("无法编码RSA公钥%s\n", err)
return
}
publicKeyFile, err := os.OpenFile(rsaKeyOutputFile+".pub.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
fmt.Printf("无法创建RSA公钥文件%s\n", err)
return
}
defer publicKeyFile.Close()
_, err = publicKeyFile.Write(publicKeyBytes)
if err != nil {
fmt.Printf("无法写入RSA公钥文件%s\n", err)
return
}
fmt.Printf("RSA密钥对已经保存到文件%s.pri.pem, %s.pub.pem\n", rsaKeyOutputFile, rsaKeyOutputFile)
}
func init() {
keyGenCmd.Flags().StringVarP(&rsaKeyOutputFile, "output", "o", "", "用于保存密钥输出文件名的前缀。")
rsaCmd.AddCommand(keyGenCmd)
}