package mainimport ("crypto/rsa""crypto/x509""encoding/pem""crypto/rand""flag""log""os")func main() {var bits intflag.IntVar(&bits, "b", 2048, "密鑰長度,預設為1024位")if err := GenRsaKey(bits); err != nil {log.Fatal("密鑰檔案產生失敗。")}log.Println("密鑰檔案產生成功。")}func GenRsaKey(bits int) error {// 產生私密金鑰檔案privateKey, err := rsa.GenerateKey(rand.Reader, bits)if err != nil {return err}derStream := x509.MarshalPKCS1PrivateKey(privateKey)block := &pem.Block{Type: "私密金鑰",Bytes: derStream,}file, err := os.Create("private.pem")if err != nil {return err}err = pem.Encode(file, block)if err != nil {return err}// 產生公開金鑰檔案publicKey := &privateKey.PublicKeyderPkix, err := x509.MarshalPKIXPublicKey(publicKey)if err != nil {return err}block = &pem.Block{Type: "公開金鑰",Bytes: derPkix,}file, err = os.Create("public.pem")if err != nil {return err}err = pem.Encode(file, block)if err != nil {return err}return nil}
package mainimport ("crypto/rand""crypto/rsa""crypto/x509""encoding/base64""encoding/pem""errors""flag""fmt""io/ioutil""os")var decrypted stringvar privateKey, publicKey []bytefunc init() {var err errorflag.StringVar(&decrypted, "d", "", "加密過的資料")flag.Parse()publicKey, err = ioutil.ReadFile("public.pem")if err != nil {os.Exit(-1)}privateKey,err = ioutil.ReadFile("private.pem")if err != nil {os.Exit(-1)}}func main() {var data []bytevar err errordata, err = RsaEncrypt([]byte("fyxichen"))if err != nil {panic(err)}origData, err := RsaDecrypt(data)if err != nil {panic(err)}fmt.Println(string(origData))}// 加密func RsaEncrypt(origData []byte) ([]byte, error) {block, _ := pem.Decode(publicKey)if block == nil {return nil, errors.New("public key error")}pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)if err != nil {return nil, err}pub := pubInterface.(*rsa.PublicKey)return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)}// 解密func RsaDecrypt(ciphertext []byte) ([]byte, error) {block, _ := pem.Decode(privateKey)if block == nil {return nil, errors.New("private key error!")}priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)if err != nil {return nil, err}return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)}