1 Star 0 Fork 0

叶明志 / golang练习

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
main.go 2.31 KB
一键复制 编辑 原始数据 按行查看 历史
yemingzhi 提交于 2020-03-31 22:30 . RSA,TLS,SSL初步练习
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
)
func createPriviteKeyAndPublicKey() {
privKey, err := rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return
}
privStream := x509.MarshalPKCS1PrivateKey(privKey)
block := &pem.Block{
Type: "private key",
Bytes: privStream,
}
privFile, err := os.OpenFile("private.pem", os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return
}
err = pem.Encode(privFile, block)
if err != nil {
return
}
//--------------------------------------------------------
pubKey := privKey.PublicKey
pubStream, err := x509.MarshalPKIXPublicKey(&pubKey)
if err != nil {
return
}
block = &pem.Block{
Type: "public key",
Bytes: pubStream,
}
pubFile, err := os.OpenFile("public.pem", os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return
}
err = pem.Encode(pubFile, block)
if err != nil {
return
}
fmt.Println("成功生成公钥和私钥")
}
//RSAPublicEncrypt 使用公钥对文件加密
func RSAPublicEncrypt(src []byte, pathName string) []byte {
pubFile, err := os.Open(pathName)
if err != nil {
return nil
}
fileInfo, err := pubFile.Stat()
if err != nil {
return nil
}
recevBuf := make([]byte, fileInfo.Size())
pubFile.Read(recevBuf)
block, _ := pem.Decode(recevBuf)
pubInter, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil
}
pubKey := pubInter.(*rsa.PublicKey)
msg, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, src)
if err != nil {
return nil
}
return msg
}
//RSAPrivateDecrypt 使用私钥对文件解密
func RSAPrivateDecrypt(cipherText []byte, pathName string) []byte {
privFile, err := os.Open(pathName)
if err != nil {
return nil
}
fileInfo, err := privFile.Stat()
if err != nil {
return nil
}
recevFile := make([]byte, fileInfo.Size())
privFile.Read(recevFile)
block, _ := pem.Decode(recevFile)
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil
}
msg, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)
if err != nil {
return nil
}
return msg
}
func main() {
// createPriviteKeyAndPublicKey()
src := []byte("通过某种算法将某种文本转换为其他文本。 ")
cipherText := RSAPublicEncrypt(src, "public.pem")
bytes := RSAPrivateDecrypt(cipherText, "private.pem")
fmt.Println(string(bytes))
}
Go
1
https://gitee.com/yemingzhi/GolangLearnPractice1.git
git@gitee.com:yemingzhi/GolangLearnPractice1.git
yemingzhi
GolangLearnPractice1
golang练习
2bf136849dce

搜索帮助