123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- package utils
- import (
- "crypto"
- "crypto/rand"
- "crypto/rsa"
- "crypto/sha256"
- "crypto/x509"
- "encoding/pem"
- "errors"
- "fmt"
- )
- // RSA公钥私钥产生
- func GenRsaKey() (prvkey, pubkey []byte) {
- // 生成私钥文件
- privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
- if err != nil {
- panic(err)
- }
- derStream := x509.MarshalPKCS1PrivateKey(privateKey)
- block := &pem.Block{
- Type: "RSA PRIVATE KEY",
- Bytes: derStream,
- }
- prvkey = pem.EncodeToMemory(block)
- publicKey := &privateKey.PublicKey
- derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
- if err != nil {
- panic(err)
- }
- block = &pem.Block{
- Type: "PUBLIC KEY",
- Bytes: derPkix,
- }
- pubkey = pem.EncodeToMemory(block)
- return
- }
- // 签名
- func RsaSignWithSha256(data []byte, keyBytes []byte) []byte {
- h := sha256.New()
- h.Write(data)
- hashed := h.Sum(nil)
- block, _ := pem.Decode(keyBytes)
- if block == nil {
- panic(errors.New("private key error"))
- }
- privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
- if err != nil {
- fmt.Println("ParsePKCS8PrivateKey err", err)
- panic(err)
- }
- signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed)
- if err != nil {
- fmt.Printf("Error from signing: %s\n", err)
- panic(err)
- }
- return signature
- }
- // 验证
- func RsaVerySignWithSha256(data, signData, keyBytes []byte) bool {
- block, _ := pem.Decode(keyBytes)
- if block == nil {
- panic(errors.New("public key error"))
- }
- pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
- if err != nil {
- panic(err)
- }
- hashed := sha256.Sum256(data)
- err = rsa.VerifyPKCS1v15(pubKey.(*rsa.PublicKey), crypto.SHA256, hashed[:], signData)
- if err != nil {
- panic(err)
- }
- return true
- }
- // 公钥加密
- func RsaEncrypt(data, keyBytes []byte) []byte {
- //解密pem格式的公钥
- block, _ := pem.Decode(keyBytes)
- if block == nil {
- panic(errors.New("public key error"))
- }
- // 解析公钥
- pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
- if err != nil {
- panic(err)
- }
- // 类型断言
- pub := pubInterface.(*rsa.PublicKey)
- //加密
- ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, pub, data)
- if err != nil {
- panic(err)
- }
- return ciphertext
- }
- // 私钥解密
- func RsaDecrypt(ciphertext, keyBytes []byte) (data []byte, err error) {
- //获取私钥
- block, _ := pem.Decode(keyBytes)
- if block == nil {
- return nil, errors.New("private key error")
- }
- //解析PKCS1格式的私钥
- priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
- if err != nil {
- return data, err
- }
- // 解密
- data, err = rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
- return data, err
- }
|