版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/The_Reader/article/details/82503060
RSA算法
- 首先你需要先了解RSA算法原理,(大概了解一下就可以)
- 你知道RSA算法需要两个密钥,一个是私钥一个是公钥
- 创建公钥与私钥制作函数,其参数为(bits int)也就是密钥的长度,你也可以让函数返回存放着两个密钥的文件名(创建的密钥存放在文件里,也可以直接返回。)
-
privateKey, e := rsa.GenerateKey(rand.Reader, bits)得到私钥,(私钥里就有公钥)
- 将私钥转化为字节,私钥是一个特殊的类型,他有专门的转化函数即
PrivateBytes := x509.MarshalPKCS1PrivateKey(privateKey)
- 转化完,将私钥字节放在私钥块中,即
block := pem.Block{ Type: "RES Private Key ", Bytes: PrivateBytes, }将block块存进一个新建的文件中就可以
- 这时私钥就存好了,接下来就是公钥。
- 公钥存放在私钥里,
publicKey := privateKey.PublicKey
- 接下的就可以类似私钥处理就可以,先将公钥转换成字节,并存放在block中,然后放入文件。
加密:
创建加密函数,其参数为明文,公钥文件名(加密是使用公钥加密,解密即使用私钥解密),返回值为密文
首先你需要读取到密钥,打开文件,创建【】byte容器,并pem。decode为pubkey,将pubkey转化为特有类型(rsa*publickey),使用
rsa.EncryptPKCS1v15(rand.Reader, key, src)
进行加密
解密:
与加密同理,文件内容取出,转化,解密
得到明文
代码为:
package main
import (
"crypto/rsa"
"crypto/rand"
"fmt"
"crypto/x509"
"encoding/pem"
"os"
)
func GetTwokey(bits int)(prikey,pubkey string){
privateKey, e := rsa.GenerateKey(rand.Reader, bits)
if e!=nil{
fmt.Print(e)
}
PrivateBytes := x509.MarshalPKCS1PrivateKey(privateKey)
block := pem.Block{
Type: "RES Private Key ",
Bytes: PrivateBytes,
}
file, i := os.Create("privateKey.pem")
prikey="privateKey.pem"
if i!=nil{
fmt.Println("文件创建失败!",i)
}
defer file.Close()
j:= pem.Encode(file, &block)
if j!=nil{
fmt.Println("私钥存入失败!",j)
}
publicKey := privateKey.PublicKey
publickey ,_:= x509.MarshalPKIXPublicKey(&publicKey)
i2 := pem.Block{
Type: "RSA Public Key",
Bytes: publickey,
}
create, i3 := os.Create("publickey.pem")
pubkey="publickey.pem"
if i3!=nil{
fmt.Print("创建publickeyfile,error",i3)
}
pem.Encode(create,&i2)
create.Close()
return
}
//加密
func CryptRsa(src []byte,filenameofkey string)[]byte{
file, e := os.Open(filenameofkey)
defer file.Close()
if e!=nil{
fmt.Println(e)
}
info, i := file.Stat()
if i!=nil{
fmt.Print(i)
}
filebytes:=make([]byte,info.Size())
file.Read(filebytes)
block, _ := pem.Decode(filebytes)
pubkey, err:= x509.ParsePKIXPublicKey(block.Bytes)
if err!=nil{
fmt.Println("err=",err)
}
key := pubkey.(*rsa.PublicKey)
bytes, i2 := rsa.EncryptPKCS1v15(rand.Reader, key, src)
if i2!=nil{
fmt.Println(i2)
}
return bytes
}
//解密
func DeCrypt(src []byte,filenameofkey string)[]byte{
file, e := os.Open(filenameofkey)
if e!=nil{
fmt.Println("文件打开失败!",e)
}
info, _:= file.Stat()
buf :=make([]byte,info.Size())
file.Read(buf)
block, _ := pem.Decode(buf)
key, _:= x509.ParsePKCS1PrivateKey(block.Bytes)
bytes, _ := rsa.DecryptPKCS1v15(rand.Reader, key, src)
return bytes
}
func main() {
src:=[]byte("aaaaa")
prikey, pubkey := GetTwokey(128)
cryptRsa := CryptRsa(src, pubkey)
fmt.Print("密文===",fmt.Sprintf("%x",cryptRsa))
crypt := DeCrypt(cryptRsa, prikey)
fmt.Print("明文===",fmt.Sprintf("%s",crypt))
}