package main
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"crypto/rand"
"flag"
"log"
"os"
)
func main() {
var bits int
(&bits, "b", 2048, "密钥长度,默认为1024位")
if err := GenRsaKey(bits); err != nil {
("密钥文件生成失败!")
}
("密钥文件生成成功!")
}
func GenRsaKey(bits int) error {
// 生成私钥文件
privateKey, err := (, bits)
if err != nil {
return err
}
derStream := x509.MarshalPKCS1PrivateKey(privateKey)
block := &{
Type: "私钥",
Bytes: derStream,
}
file, err := ("")
if err != nil {
return err
}
err = (file, block)
if err != nil {
return err
}
// 生成公钥文件
publicKey := &
derPkix, err := (publicKey)
if err != nil {
return err
}
block = &{
Type: "公钥",
Bytes: derPkix,
}
file, err = ("")
if err != nil {
return err
}
err = (file, block)
if err != nil {
return err
}
return nil
}
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
)
var decrypted string
var privateKey, publicKey []byte
func init() {
var err error
(&decrypted, "d", "", "加密过的数据")
()
publicKey, err = ("")
if err != nil {
(-1)
}
privateKey,err = ("")
if err != nil {
(-1)
}
}
func main() {
var data []byte
var err error
data, err = RsaEncrypt([]byte("fyxichen"))
if err != nil {
panic(err)
}
origData, err := RsaDecrypt(data)
if err != nil {
panic(err)
}
(string(origData))
}
// 加密
func RsaEncrypt(origData []byte) ([]byte, error) {
block, _ := (publicKey)
if block == nil {
return nil, ("public key error")
}
pubInterface, err := ()
if err != nil {
return nil, err
}
pub := pubInterface.(*)
return rsa.EncryptPKCS1v15(, pub, origData)
}
// 解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
block, _ := (privateKey)
if block == nil {
return nil, ("private key error!")
}
priv, err := x509.ParsePKCS1PrivateKey()
if err != nil {
return nil, err
}
return rsa.DecryptPKCS1v15(, priv, ciphertext)
}