package main
import (
"crypto/rsa"
"crypto/rand"
"crypto/x509"
"os"
"encoding/pem"
"encoding/base64"
"fmt"
)
func RSA_Encrypt(plaintextStr string, path string) (string, error) {
plaintext := []byte(plaintextStr)
file, err := os.Open(path)
if err != nil {
return "", fmt.Errorf("open public key file failed: %s, %s", path, err.Error())
}
defer file.Close()
info, _ := file.Stat()
buf := make([]byte, info.Size())
file.Read(buf)
block, _ := pem.Decode(buf)
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return "", fmt.Errorf("parse public key file failed: %s, %s", path, err.Error())
}
publicKey := publicKeyInterface.(*rsa.PublicKey)
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plaintext)
if err != nil {
return "", fmt.Errorf("encode message using public key file failed: %s", err.Error())
}
return base64.StdEncoding.EncodeToString(cipherText), nil
}
func RSA_Decrypt(cipherTextStr string, path string) (string, error) {
ciphertext, err := base64.StdEncoding.DecodeString(cipherTextStr)
if err != nil {
return "", fmt.Errorf("decode std base64 message failed: %s", err.Error())
}
file, err := os.Open(path)
if err != nil {
return "", fmt.Errorf("open private key file failed: %s, %s", path, err.Error())
}
defer file.Close()
info, _ := file.Stat()
buf := make([]byte, info.Size())
file.Read(buf)
block, _ := pem.Decode(buf)
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return "", fmt.Errorf("parse private key file failed: %s, %s", path, err.Error())
}
plainText, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext)
if err != nil {
return "", fmt.Errorf("decode message using private key file failed: %s", err.Error())
}
return string(plainText), nil
}