golang RSA2加密/解密

$go get github.com/wenzhenxi/gorsa

test.go文件的内容

运行: $go run test.go

package main
 
import (
"fmt"
    "log"
    "errors"
    "github.com/wenzhenxi/gorsa"
)
 
var Pubkey = `-----BEGIN 公钥-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtjjnowvv475Aa+yxLRJu
wS8P6wIxtOmHbB9A5Vb77js9WaUYnWsC2R0JCz+24RZuuC4nn4whZvwMKBpI9WQh
vq6y4q07pnpFpu0x6jcSXNn/e+CWuC6HQXSorkwd2gP5pqQVsiT/a1xPRVpPVDpF
0AOR2TRDbXQx7vi/mmHnd4NKKxkjbmNG/tpjjpjuMhKj1geJeG46lcfpnvEUIYkK
ac1wgED09jcFhZDdtKV3f4VWUw+UntZLMIr1jZQn70HyVvSa8VvcFTchpC6+fE9l
l0D6Bb7Q9LD1rfs9SidGwX27BH05dx+aY1H9v8GTRHHwXrpvUP+VsTfH2puS8Kv7
awIDAQAB
-----END 公钥-----
`
 
var Pirvatekey = `-----BEGIN 私钥-----
MIIEpAIBAAKCAQEAtjjnowvv475Aa+yxLRJuwS8P6wIxtOmHbB9A5Vb77js9WaUY
nWsC2R0JCz+24RZuuC4nn4whZvwMKBpI9WQhvq6y4q07pnpFpu0x6jcSXNn/e+CW
uC6HQXSorkwd2gP5pqQVsiT/a1xPRVpPVDpF0AOR2TRDbXQx7vi/mmHnd4NKKxkj
bmNG/tpjjpjuMhKj1geJeG46lcfpnvEUIYkKac1wgED09jcFhZDdtKV3f4VWUw+U
ntZLMIr1jZQn70HyVvSa8VvcFTchpC6+fE9ll0D6Bb7Q9LD1rfs9SidGwX27BH05
dx+aY1H9v8GTRHHwXrpvUP+VsTfH2puS8Kv7awIDAQABAoIBAHc2NTxy48bvwX+Z
wrPE+lZCLrzFm7VKjkELFU60oG7TrKhIHRlnV96oYzFLxp3tKhQuhdeYOoYAYQef
Ypm/n1/7NKadRIf+ODEjvmMHEmlSaRUm8hOexPfqlSwqOeFW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bQrg1BTfEGSm9pujsEhVGdK3JiQHbaiw/q5p74dKjlL4HF8Kg==
-----END 私钥-----
`
 
 
func main() {
    // 公钥加密私钥解密
    if err := applyPubEPriD(); err != nil {
        log.Println(err)
    }
    // 公钥解密私钥加密
    if err := applyPriEPubD(); err != nil {
        log.Println(err)
    }
}
 
// 公钥加密私钥解密
func applyPubEPriD() error {
    pubenctypt, err := gorsa.PublicEncrypt(`hello world`,Pubkey)
    if err != nil {
        return err
    }
    fmt.Println("%s is:", pubenctypt)
    pridecrypt, err := gorsa.PriKeyDecrypt(pubenctypt,Pirvatekey)
    if err != nil {
        return err
    }
	fmt.Println("%s is:", pridecrypt)
    if string(pridecrypt) != `hello world` {
        return errors.New(`解密失败`)
    }
    return nil
}
 
// 公钥解密私钥加密
func applyPriEPubD() error {
    prienctypt, err := gorsa.PriKeyEncrypt(`hello world`,Pirvatekey)
    if err != nil {
        return err
    }
 
    pubdecrypt, err := gorsa.PublicDecrypt(prienctypt,Pubkey)
    if err != nil {
        return err
    }
    if string(pubdecrypt) != `hello world` {
        return errors.New(`解密失败`)
    }
    return nil
}

  

posted @ 2020-05-23 12:58  tochenwei  阅读(1374)  评论(0编辑  收藏  举报