Golang Code Collection-Public key encryption private key decryption based on RSA-private key signature public key authentication

Source: Internet
Author: User
Tags decrypt readfile
First, the public key and private file are generated by genkey.go, and the generated public and private keys are used for encryption and decryption in rsa.go.

/ / File genkey.go / / generate public and private key pem file


Package main

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

Func main() {
    Var bits int
    flag.IntVar(&bits, "b", 1024, "Key length, default is 1024")
    If err := GenRsaKey(bits); err != nil {
        log.Fatal("Frequent key file generation failed")
    }
    log.Println("secure key file generated successfully")
}

/ / Generate private key and public key file
Func GenRsaKey(bits int) error {
    / / Generate private key file
    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
    }
    / / Generate a public key file
    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
// public key encryption private key decryption private key signature public key verification

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 hello world"
    fmt.Println("Source:", theMsg)
    // private key signature
    Sig, _ := RsaSign([]byte(theMsg))
    fmt.Println(string(sig))
    // public key verification
    fmt.Println(RsaSignVer([]byte(theMsg), sig))
    //public key encryption
    // enc, _ := RsaEncrypt([]byte(theMsg))
    // fmt.Println("Encrypted:", string(enc))
    // // Secret key decryption
    // decstr, _ := RsaDecrypt(enc)
    // fmt.Println("Decrypted:", string(decstr))
}

// private key signature
Func RsaSign(data []byte) ([]byte, error) {
    h := sha256.New()
    h.Write(data)
    Hashed := h.Sum(nil)
    / / Get the private key
    Block, _ := pem.Decode(privateKey)
    If block == nil {
        Return nil, errors.New("private key error")
    }
    / / Parse the private key in PKCS1 format
    Priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    If err != nil {
        Return nil, err
    }
    Return rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA256, hashed)
}

// public key verification
Func RsaSignVer(data []byte, signature []byte) error {
    Hashed := sha256.Sum256(data)
    Block, _ := pem.Decode(publicKey)
    If block == nil {
        Return errors.New("public key error")
    }
    // parse the public key
    pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
    If err != nil {
        Return err
    }
    // type assertion
    Pub := pubInterface.(*rsa.PublicKey)
    / / Verify the signature
    Return rsa.VerifyPKCS1v15(pub, crypto.SHA256, hashed[:], signature)
}

// public key encryption
Func RsaEncrypt(data []byte) ([]byte, error) {
    / / Decrypt the public key in pem format
    Block, _ := pem.Decode(publicKey)
    If block == nil {
        Return nil, errors.New("public key error")
    }
    // parse the public key
    pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
    If err != nil {
        Return nil, err
    }
    // type assertion
    Pub := pubInterface.(*rsa.PublicKey)
    //encryption
    Return rsa.EncryptPKCS1v15(rand.Reader, pub, data)
}

// private key decryption
Func RsaDecrypt(ciphertext []byte) ([]byte, error) {
    / / Get the private key
    Block, _ := pem.Decode(privateKey)
    If block == nil {
        Return nil, errors.New("private key error!")
    }
    / / Parse the private key in PKCS1 format
    Priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    If err != nil {
        Return nil, err
    }
    // decrypt
    Return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.