import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "fmt" "flag" "encoding/hex" )
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!") }
var key interface{} var errParsePK error if block.Type == "RSA PRIVATE KEY" { key, errParsePK = x509.ParsePKCS1PrivateKey(block.Bytes) } else if block.Type == "PRIVATE KEY" { key, errParsePK = x509.ParsePKCS8PrivateKey(block.Bytes) }
if errParsePK != nil { return nil, errParsePK } priv := key.(*rsa.PrivateKey)
return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext) }
func GenRsaKey(bits int) error { privateKey, err := rsa.GenerateKey(rand.Reader, bits) if err != nil { return err } derStream := x509.MarshalPKCS1PrivateKey(privateKey) block := &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: derStream, } file, err := os.Create("private.pem") if err != nil { return err } err = pem.Encode(file, block) if err != nil { return err } publicKey := &privateKey.PublicKey derPkix, err := x509.MarshalPKIXPublicKey(publicKey) if err != nil { return err } block = &pem.Block{ Type: "PUBLIC KEY", Bytes: derPkix, } file, err = os.Create("public.pem") if err != nil { return err } err = pem.Encode(file, block) if err != nil { return err } return nil }
func main() {
plainMsg := flag.String("plainMsg", "", "plain message to encrypt") encMsg := flag.String("encMsg", "", "ecrypted message to decrypt") isEnc := flag.Bool("isEnc", false, "1 is encrypt, 0 is decrypt") flag.Parse()
if *plainMsg == "" && *encMsg == "" { fmt.Println("Error@!@: no param") return }
if *isEnc { encData, err := RsaEncrypt([]byte(pub), []byte(*plainMsg)) if err != nil { fmt.Println("Error@!@") fmt.Println(err.Error()) } fmt.Println(hex.EncodeToString(encData)) } else { bData, err := hex.DecodeString(*encMsg) if err != nil { fmt.Println("Error@!@") fmt.Println(err.Error()) return } origData, err := RsaDecrypt([]byte(priv), bData) if err != nil { fmt.Println("Error@!@") fmt.Println(err.Error()) return } fmt.Println(string(origData)) } }
|