生成RSA證書:
openssl方式生成
openssl genrsa -out rsa_private_key.pem 1024
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
Go代碼方式生成
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"os"
)
//生成RSA私鑰和公鑰,保存到文件中
// bits 證書大小
func GenerateRSAKey(bits int) {
//GenerateKey函數使用隨機數據生成器random生成一對具有指定字位數的RSA密鑰
//Reader是一個全局、共享的密碼用強隨機數生成器
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
panic(err)
}
//保存私鑰
//通過x509標准將得到的ras私鑰序列化為ASN.1 的 DER編碼字符串
X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)
//使用pem格式對x509輸出的內容進行編碼
//創建文件保存私鑰
privateFile, err := os.Create("private.pem")
if err != nil {
panic(err)
}
defer privateFile.Close()
//構建一個pem.Block結構體對象
privateBlock := pem.Block{Type: "RSA Private Key", Bytes: X509PrivateKey}
//將數據保存到文件
pem.Encode(privateFile, &privateBlock)
//保存公鑰
//獲取公鑰的數據
publicKey := privateKey.PublicKey
//X509對公鑰編碼
X509PublicKey, err := x509.MarshalPKIXPublicKey(&publicKey)
if err != nil {
panic(err)
}
//pem格式編碼
//創建用於保存公鑰的文件
publicFile, err := os.Create("public.pem")
if err != nil {
panic(err)
}
defer publicFile.Close()
//創建一個pem.Block結構體對象
publicBlock := pem.Block{Type: "RSA Public Key", Bytes: X509PublicKey}
//保存到文件
pem.Encode(publicFile, &publicBlock)
}
func main() {
//生成密鑰對,保存到文件
GenerateRSAKey(2048)
}
RSA數據加/解密
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
)
//RSA加密
// plainText 要加密的數據
// path 公鑰匙文件地址
func RSA_Encrypt(plainText []byte, path string) []byte {
//打開文件
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
//讀取文件的內容
info, _ := file.Stat()
buf := make([]byte, info.Size())
file.Read(buf)
//pem解碼
block, _ := pem.Decode(buf)
//x509解碼
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic(err)
}
//類型斷言
publicKey := publicKeyInterface.(*rsa.PublicKey)
//對明文進行加密
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
if err != nil {
panic(err)
}
//返回密文
return cipherText
}
//RSA解密
// cipherText 需要解密的byte數據
// path 私鑰文件路徑
func RSA_Decrypt(cipherText []byte,path string) []byte{
//打開文件
file,err:=os.Open(path)
if err!=nil{
panic(err)
}
defer file.Close()
//獲取文件內容
info, _ := file.Stat()
buf:=make([]byte,info.Size())
file.Read(buf)
//pem解碼
block, _ := pem.Decode(buf)
//X509解碼
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err!=nil{
panic(err)
}
//對密文進行解密
plainText,_:=rsa.DecryptPKCS1v15(rand.Reader,privateKey,cipherText)
//返回明文
return plainText
}
func main() {
//加密
data := []byte("hello world")
encrypt := RSA_Encrypt(data, "public.pem")
fmt.Println(string(encrypt))
// 解密
decrypt := RSA_Decrypt(encrypt, "private.pem")
fmt.Println(string(decrypt))
}