Go語言rsa使用產生公開金鑰私密金鑰,GO使用rsa加密解密

來源:互聯網
上載者:User
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)}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.