1. 程式人生 > >Golang程式碼蒐集-基於RSA的公鑰加密私鑰解密-私鑰簽名公鑰驗證

Golang程式碼蒐集-基於RSA的公鑰加密私鑰解密-私鑰簽名公鑰驗證

首先由genkey.go生成公鑰和私檔案,在rsa.go裡使用生成的公鑰和私鑰進行加密和解密

//檔案 genkey.go
//生成公鑰和私鑰 pem檔案

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/pem"
    "flag"
    "log"
    "os"
)

func main() {
    var bits int
    flag.IntVar(&bits, "b", 1024, "祕鑰長度,預設為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: "RSA PRIVATE KEY"
, 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.PublicKey defPkix, err := x509.MarshalPKIXPublicKey(publicKey) if
err != nil { return err } block = &pem.Block{ Type: "RSA PUBLIC KEY", Bytes: defPkix, } file, err = os.Create("public.pem") if err != nil { return err } err = pem.Encode(file, block) if err != nil { return err } return nil }
//rsa.go
//公鑰加密私鑰解密  私鑰簽名公鑰驗證

package main

import (
    "crypto"
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha256"
    "crypto/x509"
    "encoding/pem"
    "errors"
    "fmt"
    "io/ioutil"
    "os"
)

var privateKey, publicKey []byte

func init() {
    var err error
    publicKey, err = ioutil.ReadFile("public.pem")
    if err != nil {
        os.Exit(-1)
    }
    privateKey, err = ioutil.ReadFile("private.pem")
    if err != nil {
        os.Exit(-1)
    }
    //fmt.Printf("%s\n", publicKey)
    //fmt.Printf("%s\n", privateKey)
}
func main() {
    var theMsg = "the message you want to encode 你好 世界"
    fmt.Println("Source:", theMsg)
    //私鑰簽名
    sig, _ := RsaSign([]byte(theMsg))
    fmt.Println(string(sig))
    //公鑰驗證
    fmt.Println(RsaSignVer([]byte(theMsg), sig))
    //公鑰加密
    //  enc, _ := RsaEncrypt([]byte(theMsg))
    //  fmt.Println("Encrypted:", string(enc))
    //  //私鑰解密
    //  decstr, _ := RsaDecrypt(enc)
    //  fmt.Println("Decrypted:", string(decstr))
}

//私鑰簽名
func RsaSign(data []byte) ([]byte, error) {
    h := sha256.New()
    h.Write(data)
    hashed := h.Sum(nil)
    //獲取私鑰
    block, _ := pem.Decode(privateKey)
    if block == nil {
        return nil, errors.New("private key error")
    }
    //解析PKCS1格式的私鑰
    priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    return rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA256, hashed)
}

//公鑰驗證
func RsaSignVer(data []byte, signature []byte) error {
    hashed := sha256.Sum256(data)
    block, _ := pem.Decode(publicKey)
    if block == nil {
        return errors.New("public key error")
    }
    // 解析公鑰
    pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        return err
    }
    // 型別斷言
    pub := pubInterface.(*rsa.PublicKey)
    //驗證簽名
    return rsa.VerifyPKCS1v15(pub, crypto.SHA256, hashed[:], signature)
}

// 公鑰加密
func RsaEncrypt(data []byte) ([]byte, error) {
    //解密pem格式的公鑰
    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, data)
}

// 私鑰解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
    //獲取私鑰
    block, _ := pem.Decode(privateKey)
    if block == nil {
        return nil, errors.New("private key error!")
    }
    //解析PKCS1格式的私鑰
    priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    // 解密
    return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}