直接上代码吧。哈哈, package main import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/pem" "errors" "fmt" "os" "io/ioutil" "bufio" // "reflect" ) func main() { var data []byte var err error privateKey, err := GetContent("private.txt") publicKey, err := GetContent("public.txt") content, err := GetContent("encryp.txt") // fmt.Println(reflect.TypeOf(content)) // fmt.Println(string(content)) base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(content))) l, _ := base64.StdEncoding.Decode(base64Text, []byte(content)) data = base64Text[:l] data, err = RsaEncrypt(publicKey, []byte("shaohualee.com")) if err != nil { panic(err) } fmt.Println(base64.StdEncoding.EncodeToString(data)) origData, err := RsaDecrypt(privateKey, data) check(err) f, err := os.Create("decrypt.txt") check(err) defer f.Close() f.Sync() //bufio 提供了和我们前面看到的带缓冲的读取器一样的带缓冲的写入器。 w := bufio.NewWriter(f) n4, err := w.WriteString(string(origData)) fmt.Printf("wrote %d bytes\n", n4) //使用 Flush 来确保所有缓存的操作已写入底层写入器。 w.Flush() } func check(e error) { if e != nil { panic(e) } } func GetContent(path string)([]byte, error) { privateKeyFile, err := os.OpenFile(path, os.O_RDWR, os.ModeType) check(err) defer privateKeyFile.Close() privateKey, err := ioutil.ReadAll(privateKeyFile) return privateKey, err } // 加密 func RsaEncrypt(publicKey []byte, 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(privateKey []byte, 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) } 可以用以下方法判断类型 var a interface{} a = 1 // a = "string"; switch vtype := a.(type) { case string: fmt.Println("string") case int: fmt.Println("int") default: fmt.Println(vtype) } 相关文件可以在这里下载rsa

分类: web

标签: