func DecryptWithRSA(encrypted, privKey, password []byte) ([]byte, error) {
	derKey, err := parsePrivKeyInDER(privKey)
	if err == nil {
		return rsa.DecryptOAEP(hashFunc(), rand.Reader, derKey, encrypted, nil)
	}
	pem, _ := pem.Decode(privKey)
	if pem == nil {
		return nil, fmt.Errorf("given private key format is neither DER nor PEM")
	}
	bytes := pem.Bytes
	if x509.IsEncryptedPEMBlock(pem) {
		var err error
		bytes, err = x509.DecryptPEMBlock(pem, password)
		if err != nil {
			return nil, fmt.Errorf("failed to decrypt the encrypted private key: %w", err)
		}
	}
	pemKey, err := parsePrivKeyInDER(bytes)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptOAEP(hashFunc(), rand.Reader, pemKey, encrypted, nil)
}
DecryptWithRSA decrypts the given encrypted data with RSA-OAEP.
privKey must be a RSA private key in PEM or DER format.
package crypto
import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"golang.org/x/crypto/pbkdf2"
)
const (
	defaultIterationCount = 100
	keyLength             = 32
)
var hashFunc = sha256.New
func DeriveKey(password string, salt []byte) []byte {
	return pbkdf2.Key([]byte(password), salt, defaultIterationCount, keyLength, hashFunc)
}
func Encrypt(key, plaintext []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	nonce := make([]byte, gcm.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		return nil, err
	}
	encrypted := gcm.Seal(nonce, nonce, plaintext, nil)
	return encrypted, nil
}
func Decrypt(key, encrypted []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	nonceSize := gcm.NonceSize()
	if len(encrypted) < nonceSize {
		return nil, fmt.Errorf("invalid cipher test")
	}
	nonce := encrypted[:nonceSize]
	encryptedText := encrypted[nonceSize:]
	return gcm.Open(nil, nonce, encryptedText, nil)
}
func EncryptWithRSA(plaintext, pubKey []byte) ([]byte, error) {
	derKey, err := parsePubKeyInDER(pubKey)
	if err == nil {
		return rsa.EncryptOAEP(hashFunc(), rand.Reader, derKey, plaintext, nil)
	}
	pem, _ := pem.Decode(pubKey)
	if pem == nil {
		return nil, fmt.Errorf("given public key format is neither DER nor PEM")
	}
	pemKey, err := parsePubKeyInDER(pem.Bytes)
	if err != nil {
		return nil, err
	}
	return rsa.EncryptOAEP(hashFunc(), rand.Reader, pemKey, plaintext, nil)
}
func parsePubKeyInDER(der []byte) (*rsa.PublicKey, error) {
	pkcs1Key, err := x509.ParsePKCS1PublicKey(der)
	if err == nil {
		return pkcs1Key, nil
	}
	key, err := x509.ParsePKIXPublicKey(der)
	if err != nil {
		return nil, fmt.Errorf("failed to parse public key: %w", err)
	}
	pkixKey, ok := key.(*rsa.PublicKey)
	if !ok {
		return nil, fmt.Errorf("given public key is not an RSA key")
	}
	return pkixKey, nil
}